@maximifn
Пока ты спишь - твой враг качается

Что я делаю не так?

models.py
class InstagramConnector(models.Model):
    user_id = models.ForeignKey("auth.User", on_delete=models.CASCADE)
    instagram_login = models.ForeignKey(Instagram, on_delete=models.CASCADE)

class Instagram(models.Model):
    instagram_login = models.CharField(max_length=30, primary_key=True)
    creation_date = models.DateTimeField()


views.py:
@login_required(login_url='/login/')
def add_account(request):
    if request.method == "POST":
        form = AddAccount(request.POST)
        if form.is_valid():
            insta = Instagram()
            connector = InstagramConnector()
            instagram_account = form.cleaned_data['instagram_login']
            account_description = form.cleaned_data['description']
            account_creation_date = timezone.now()
            try:
                Instagram.objects.get(instagram_login="instagram_account")
                print('Такой аккаунт есть в базе, связываю с пользователем')
                connector.user_id = User.objects.get(username=request.user)
                connector.instagram_login = Instagram.objects.get(instagram_login=instagram_account)
                connector.description = account_description
                connector.date = account_creation_date
                connector.save()
            except insta.DoesNotExist:
                print('Такой аккаунта нет, создаю аккаунт и коннектор')
                insta.instagram_login = instagram_account
                insta.creation_date = account_creation_date
                insta.save()
                print(User.objects.get(username=request.user))
                print(Instagram.objects.get(instagram_login=instagram_account))
                connector = InstagramConnector()
                connector.user_id = User.objects.get(username=request.user)
                connector.instagram_login = Instagram.objects.get(instagram_login=instagram_account)
                connector.description = account_description
                connector.date = account_creation_date
                connector.save()

            return HttpResponse(json.dumps({'server_answer': "Аккаунт успешно добавлен"}),
                                content_type="application/json")
        else:
            return HttpResponse(json.dumps({'server_answer': "Форма заполнена неверно"}),
                                content_type="application/json")
    else:
        form = AddAccount()
        return render(request, 'instagram/add_account.html', {'form': form})


Ошибка тут -
Instagram.objects.get(instagram_login="instagram_account")

Код ошибки
foreign key mismatch - "instagram_instagramconnector" referencing "instagram_instagram"


Из консоли
spoiler
Такой аккаунта нет, создаю аккаунт и коннектор
amigoz14
m.stikharev
Internal Server Error: /instagram/add_account/
Traceback (most recent call last):
  File "C:\instik-django\instagram\views.py", line 21, in add_account
    Instagram.objects.get(instagram_login="instagram_account")
  File "C:\instik\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\instik\venv\lib\site-packages\django\db\models\query.py", line 403, in get
    self.model._meta.object_name
instagram.models.DoesNotExist: Instagram matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\instik\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\instik\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: foreign key mismatch - "instagram_instagramconnector" referencing "instagram_instagram"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\instik\venv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\instik\venv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\instik\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\instik\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\instik-django\instagram\views.py", line 40, in add_account
    connector.save()
  File "C:\instik\venv\lib\site-packages\django\db\models\base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\instik\venv\lib\site-packages\django\db\models\base.py", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\instik\venv\lib\site-packages\django\db\models\base.py", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\instik\venv\lib\site-packages\django\db\models\base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "C:\instik\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\instik\venv\lib\site-packages\django\db\models\query.py", line 1125, in _insert
    return </spoiler>query.get_compiler(using=using).execute_sql(return_id)
  File "C:\instik\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1283, in execute_sql
    cursor.execute(sql, params)
  File "C:\instik\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\instik\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\instik\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\instik\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\instik\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\instik\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\instik\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: foreign key mismatch - "instagram_instagramconnector" referencing "instagram_instagram"

Почему не видит foreign key или что я делаю не так?
  • Вопрос задан
  • 361 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы