Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add class to form field Django ModelForm and datapicker
I am learning to program in django, but i have a question, I created a dynamic form, which by default will always have the 'form control' class for all fields. I am trying to add a datapicker to a specific field but I need to add a new class and some other HTML elements, any solution? <form action="." method="POST"> {% csrf_token %} <div class="row"> {% for field in form %} <div class="form-group col-md-6" > {{ field.errors }} <label for="{{ field.id_for_label }}"> {{ field.label }} </label> {{ field |add_class:'form-control '}} </div> {% endfor %} I want to add, a specific class for a specific field, but i need html elements and add other classes. Here's the code of datapicker <div class="form-group" id="data_1"> <label class="font-noraml">Simple data input format</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control" value="03/04/2014"> </div> </div> -
Integrate attachments from users in the send_mail() framework
Can you help me by integrating the images that the users upload to my form (which has already been programmed and words) to the e-mail that I want to send to our company mail? At the moment the mail works perfectly and all the inputs of the users are going through, however, where we come to the immages I checked the documentation for the attach methods but I didn't fully understand how it works... ''' def publicationmemoria(request): if request.method == "POST": inputEmail = request.POST['inputEmail'] inputTelefono = request.POST['inputTelefono'] inputNome = request.POST['inputNome'] inputCognome = request.POST['inputCognome'] inputNascita = request.POST['inputNascita'] inputMorte = request.POST['inputMorte'] inputLuogo = request.POST['inputLuogo'] inputImmagine1 = request.POST['inputImmagine1'] inputImmagine2 = request.POST['inputImmagine2'] inputImmagine3 = request.POST['inputImmagine3'] inputFrase = request.POST['inputFrase'] inputTesto = request.POST['inputTesto'] inputAutori = request.POST['inputAutori'] #send an email send_mail( 'Richiesta di pubblicazione - Memoria', #subject 'Dati persona di contatto:' + '\n' + 'Email:' + ' ' + inputEmail + '\n' + 'Numero di telefono:' + ' ' + inputTelefono + '\n' + '\n' + 'Dati per articolo:' + '\n' + 'Nome:' + ' ' + inputNome + '\n' 'Cognome:' + ' ' + inputCognome + '\n' 'Data di nascita:' + ' ' + inputNascita + '\n' 'Data di morte:' + ' ' + inputMorte + … -
Autosave user input in textarea in Django
I'd like to save user input in a text area automatically without any submit button. The UI I'm looking for is google docs kind of thing. Ideally there should be a time interval of 2-3 seconds after the input to prevent submitting requests every-time something is typed. Here's my current implementation. model: class ActionField(models.Model): content = models.TextField() def __str__(self): return self.content view: def action_view(request): all_todo_items = ActionField.objects.all() return render(request, 'action.html', {'all_items': all_todo_items}) and html displaying the form and the submit button I'd like to remove: <form action="/add/" method='post'>{% csrf_token %} <textarea name="content" rows="30" cols="100"></textarea> <br><br> <input type="submit" value="enter"> </form> After some quick research, it seems this would be normally done with AJAX or Jquery but is there any simple approach using purely Django? I'm new to the framework as well as html / FE. -
Django filter by brand
im making an ecommerce website with django and im having problems with the filter, I want to show all the brands that I choose. Here is the view: marca = request.GET.get('marca') if marca == 'marca': products = products.filter (brand__name = marca) marca is Brand. here is the template: {% for brand in q %} <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="{{brand.brand}}" name="marca" value="{{brand.brand}}" {% if marca == '{{brand.brand}}' %} checked="checked" {%endif%}> <label class="custom-control-label" for="{{brand.brand}}">{{brand.brand}}</label> </div> {% endfor %} okay so, its showing me with the filter, but only the last one that I checked. If i check 2 brands, it only showing up the last one. So pls i need some help with this:( -
def __str__(self) being ignored in Django admin
I have the following model defined: from django.db import models class Patient(models.Model): BIRTH_GENDERS = ( ('F', 'Female'), ('M', 'Male'), ('U', 'Unknown') ) first_name = models.CharField(max_length=60) middle_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) date_of_birth = models.DateField() gender = models.CharField(max_length=1, choices=BIRTH_GENDERS) def __str__(self): return self.last_name On the Django admin panel it is showing Patient Object(1), no the last name. Can not figure out what is going wrong, no errors in the command line. -
django pagination doesn't work when click on the same page number
I am currently facing two issues Issue 1: the application developed in Django. I am able to navigate to Page 1 or Page 2 with no issues but if suppose I am there on page 1 and click the same page 1 link URL will be ( 127.0.0.1:8000/query/="?page=1" ) I am getting the error for the page Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/query/%3D%22?page=1%22 on the console : Not Found: /query/=" [14/Oct/2020 17:46:10] "GET /query/=%22?page=1%22 HTTP/1.1" 404 3710 Views @login_required(login_url='login') def query(request): print("ddd",request) tasks = Task.objects.all() form = TaskForm() if request.method =='POST': form=TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') products = Task.objects.all() paginator = Paginator(products, 5) page_number = request.GET.get('page', 1) page = paginator.get_page(page_number) NoOfProducts = Task.objects.count() try: xyz = paginator.page(page) except PageNotAnInteger: xyz = paginator.page(1) except EmptyPage: xyz = paginator.page(paginator.num_pages) print("Price1", page_number) print("Price",NoOfProducts) if page.has_next(): next_url = f'?page={page.next_page_number()}' else: next_url = '' if page.has_previous(): prev_url = f'?page={page.previous_page_number()}' else: prev_url = '' print("next", next_url) print("prev", prev_url) context = {'tasks':products,'form':form,'Totalprice':Task.get_price_total,'page': page, 'next_page_url': next_url, 'prev_page_url': prev_url, 'NoOfProducts': NoOfProducts} return render(request,'tasks/cart.html',context) urls urlpatterns = [ #path('', views.index, name="list"), path('', views.query, name="query"), path('create/', views.createTask, name="create"), path('update_task/<str:pk>/', views.updateTask, name="update_task"), path('register/', views.registerPage,name="register"), path('login/', views.loginPage,name="login"), # path('login/', views.loginPage,name="login"), path('logout/', views.logoutUser,name="logout"), path('delete/<str:pk>/', views.deleteTask, name="delete"), path('query/', views.query, name="query"), … -
why did Django not create the dateTime field of the DB model?
I wrote the model: class Blog(models.Model): title = models.CharField(max_length=20) date = models.DateTimeField('date published') content = models.TextField() email = models.EmailField() when I run the migrate it creates the table in the db.sqlite3 file but with no dateTime field (it does it also for date Field). and in the admin site when I try to accsess the blog table it throws an exeption 'no such column' with the direct cause: django\db\backends\utils.py in _execute 86. return self.cursor.execute(sql, params) django\db\backends\sqlite3\base.py in execute 396. return Database.Cursor.execute(self, query, params) I run the 'sqlmigrate' (after 'makemigration' and 'migrate') in the terminal and it shows that the date is in there and also in the migration file, but no dateTime field in the database!: >manage.py sqlmigrate blog 0001 BEGIN; -- -- Create model Blog -- CREATE TABLE "blog_blog" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(20) NOT NULL, "date" datetime NOT NULL, "content" text NOT NULL, "email" varchar(254) NOT NULL); COMMIT; does someone knows why? -
django authenticatie function only works for superuser
def customer_login(request): if request.method == 'POST': body_unicode = request.body.decode('UTF-8') received_json_data = json.loads(body_unicode) username = received_json_data.get("username") password = received_json_data.get("password") user = authenticate(request=request, username=username, password=password) if user: login(request=request, user=user) content = {"message": "You are logged in successfully."} return JsonResponse(content, status=200) else: content = {"message": "Username or Password is incorrect."} return JsonResponse(content, status=404) authenticate function always returns None except for superuser. what can I do? -
Django DateTimeRangeField: default=[timezone.now()]-[timezone.now()]+[10YEARS]
I want an "active_in" attribute as a timeframe. I assume that the DBMS is optimized for the postgresql tsrange field, and as such it is preferable to utilize the DateTimeRangeField rather than 2 separate fields for start_date and end_date. Doing this I desire a default value for the field. active_in = models.DateTimeRangeField(default=timezone.now+'-'+timezone.now+10YEARS) Is my assumption about the DateTimeRangeField performance true? Is there a smart solution be it creating a new; function,class or simply manipulating the 2nd last digit? My possible solutions: Code using string manipulation: active_in = models.DateTimeRangeField(default=timezone.now+'-'+timezone.now[:-2]+'30') Code using custom function object: (adjusted from here: https://stackoverflow.com/a/27491426/7458018) def today_years_ahead(): return timezone.now + '-' timezone.now() + timezone.timedelta(years=10) class MyModel(models.Model): ... active_in = models.DateTimeRangeField(default=today_years_ahead) -
Can an UpdateView work without an object from the beginning?
Is there a way to use UpdateView without an object to update at first so I can pass it through AJAX? I want to create some sort of unique UpdateView for all the item where I can just select the item I want to update from a select. Can I do this with UpdateView or I am going to need to code the view from scratch_ -
Swift Networking with Django and without Firebase (Authorization, Databases, etc)
I've been learning Swift through following various tutorials and noticed they all pretty much use Firebase for their authorizations/databases. I'd prefer to avoid giving control of my backend to google, and I recently did a tutorial for a basic chat app that registers and logs in users with Firebase that used to work in Xcode 11 but has now horribly broke after updating to Xcode 12, so I’d also prefer to avoid extensions. It seems running a Django backend is a recommended solution as my intention is create a web app that can be updated by an iOS app and vice versa (similar to how I can download a reddit app, make a post, go to reddit itself and see the post and also create a post that can be seen on the app, or like a chat app even - the concept is more what matters). Is this something I can do "out of the box" with Swift/Xcode or do I need an extension (I hear Alamofire is good, but again, am terrified of extensions beyond my control breaking when I update something, but am not opposed to them outright). It seems that with Firebase, google provides a plist … -
Need to create checkout session GraphQL + Django
I need to create a session for Stripe Checkout. According to Stripe Checkout Docs: Add an endpoint on your server that creates a Checkout Session. A Checkout Session controls what your customer sees in the Stripe-hosted payment page such as line items, the order amount and currency, and acceptable payment methods. Return the Checkout Session's ID in the response to reference the Session on the client. I am struggling with creating this service in Graphene (GraphQL wrapper for Django implementation). This is what the docs show as an example (Flask): 21@app.route('/create-session', methods=['POST']) 22def create_checkout_session(): 23 try: 24 checkout_session = stripe.checkout.Session.create( 25 payment_method_types=['card'], 26 line_items=[ 27 { 28 'price_data': { 29 'currency': 'usd', 30 'unit_amount': 2000, 31 'product_data': { 32 'name': 'Stubborn Attachments', 33 'images': ['https://i.imgur.com/EHyR2nP.png'], 34 }, 35 }, 36 'quantity': 1, 37 }, 38 ], 39 mode='payment', 40 success_url=YOUR_DOMAIN + '?success=true', 41 cancel_url=YOUR_DOMAIN + '?canceled=true', 42 ) 43 return jsonify({'id': checkout_session.id}) 44 except Exception as e: 45 return jsonify(error=str(e)), 403 I know how to get the frontend(react) working and know how to request this create session id every time a user wants to purchase something but I am stuck on the GraphQl server implementation for the create session service. … -
Connecting values in a database to Django models
I have manually imported data (via a .csv file) into a database, how can I now connect the values imported into the database to a Django model so that I could then reference the data via application logic? I know that this is the opposite of the standard process and as a result, I have been able to find no references to this process online. -
Why isn't my attribute value printing correctly to the shell in Django?
This feels very simple but I can't find the solution anywhere... I have an object (question) defined as an instance of my Question model. It has the attribute 'type' which has 2 options. When querying it in the shell, I can see the correct attribute value, but when I try to print this value I get 'None'. This is affecting one of my views as I need to call a different html template depending on the type of question. e.g.: question=Question.objects.get(id=24) q_type = question.type When I call q_type, the correct attribute ['Single'] is printed to shell , When I call print(q_type), None (with no quotation marks) is printed to shell Feel like I'm missing something obvious here.. please help -
ValueError at /profiles/testuser/ Field 'id' expected a number but got 'testuser'
Well I need a help. I am working with class base views and models in django. I am trying to build follow system but got an error. : ValueError at /profiles/testuser/ Field 'id' expected a number but got 'testuser'. , I have search on it but couldn't solve it. Can you guys help me. I hope you python and django community help me. urls.py urlpatterns = [ path('<str:username>/',UserProfileDetailView.as_view(),name = 'detail'), ] views.py class UserProfileDetailView(DetailView): model = UserProfile template_name = "profiles/userprofile_detail.html" slug_url_kwarg = "username" # this the `argument` in the URL conf slug_field = "user" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args,**kwargs) print(self.object.user,'view profile') print(self.request.user.userprofile.follower.all(),'my profile') is_following = False if self.object.user in self.request.user.userprofile.follower.all(): is_following = True context["is_following"] = is_following return context models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) def __str__(self): return f'{self.user.username}' traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/testuser/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) The above … -
Django unit testing form with field assigned from request object
I have this form class PostCreationForm(forms.ModelForm): def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and I'm trying to unit test it with this test class PostCreationByFormTestCase(TestCase): def __init__(self, *args, **kwargs): super(PostCreationByFormTestCase, self).__init__(*args, **kwargs) self.CustomUser = get_user_model() def setUp(self): self.credentials = { 'username': 'john_smith', 'password': 'St0ngPassw0rd' } self.user = self.CustomUser.objects.create( username=self.credentials['username'], email='john_smith@mail.com', password=self.credentials['password'], first_name='John', last_name='Smith' ) def test_simple_form(self): form_data = { 'author': self.user, 'title': 'Simple Post', 'description': 'very good description', } form = PostCreationForm(form_data) self.assertTrue(form.is_valid) post = form.save() the assert passes, but the form.save() produces django.db.utils.IntegrityError: null value in column "author_id" violates not-null constraint I tried changing the form to class PostCreationForm(forms.ModelForm): def form_valid(self, form): if not form.instance.author: form.instance.author = self.request.user return super().form_valid(form) but it still does not work. I saw this as a recommended way to assign field to object if I don't want to take it as an input from the user as in this case where I want the author of the post to be the current user. How should I fix that in order to be able to test the form? -
Is this MySQL query equivalent to this Django query
Is this MySQL Query SELECT * from books WHERE ISBN = (SELECT ISBN FROM userWishlist WHERE userid_id = request.user.id) equivalent to this Django query? q = userWishlist.objects.filter(userid_id = request.user.id).values('isbn_id') return books.objects.filter(ISBN = q) -
Django makemigration freezes / hangs
I recently updated my project and it had changes that needed to be migrated. I tried to run migrations but the process freezes, and I don’t get the stack trace as I have to kill the process manually. I have also tried to run migrations with a very verbose output (migrate -verbosity 3) but nothing comes out of the command line. I've also run python manage.py makemigrations with faulthandler, but the log is empty in that. I have tried making migrations both in the IDE and in the terminal, but both have the same behavior. Here are the troubleshooting steps I’ve tried so far: Docker-compose down and docker-compose down –volumes to delete the database Killed all postgres processes running on my computer Deleted all migrations and tried rerunning makemigrations (makemigrations freezes in the same way migrate does) Switched branches and tried running migrations from the other branch I’ve googled this issue but the steps I’ve outlined above cover what was recommended. If you have any thoughts on how to handle this issue I appreciate any guidance you might have. -
Why do retrieved Django models don't have the timezone set to its datetime?
I have a question about the way Django works with timezones. In my settings I configure my timezone: USE_TZ = True TIME_ZONE = 'Europe/Amsterdam' # At time of writing UTC+2 I have a model with a DateTimeField. I know that whenever Django saves this model in the timezone UTC regardless of timezone settings. I also know that whenever Django encounters a datetime without timezone (a naive datetime) it will assume it in the default time zone (in my case Amsterdam) and convert it to UTC upon saving. See https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/#interpretation-of-naive-datetime-objects However, whenever I retrieve a model from the DB using Django, the DateTimeField will have a datetime that does not have a timezone. I know by specification that it is in UTC, but whenever I save my model back to the DB (after updating some fields) Django will see the datetime is naive and assume it is in the default timezone. In my case it keeps subtracting 2 hours from the datetime every time an object is updated. So, whenever I do this. A = MyModel.object.get(pk=1) A.some_field = 10 A.save() I will get a RuntimeWarning: DateTimeField received a naive datetime and my timestamp got subtracted 2 hours. I can solve this … -
In Django, is it possible to force prefetch_related to exec only one SQL query?
with these models: class CustomUser(PaymentUserMixin, AbstractUser): pass class Customer(StripeModel): subscriber = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="djstripe_customers", ) Is it possible to force this QuerySet to use only one SQL query (instead of two) ? CustomUser.objects.prefetch_related('djstripe_customers').get(email="user@gmail.com") that generates that: SELECT "accounts_customuser"."id" FROM "accounts_customuser" WHERE "accounts_customuser"."email" = 'user@gmail.com' LIMIT 21; args=('user@gmail.com',) SELECT "djstripe_customer"."djstripe_id" FROM "djstripe_customer" WHERE "djstripe_customer"."subscriber_id" IN (6); args=(6,) Note: I cannot modify Customer model -
Editing Django formset data creating new records instead of updating
I am trying to update a group of formsets that are related the main form (Project Information) by the main forms pk. The create form works fine, but I am finding it extremely difficult to implement the update version. I swear to you that I have read everything and taken some online courses and I just cannot get this. The form that is presented to the user has a dropdown choice and they select the project they would like to update. I've included an image of this. The selected project triggers an AJAX request to def project_data(request) below in view.py and the data for each formset is looped through and the formsets are created dynamically and populated. This also can be partially seem in the included image. All of that works fine. It's the save as an update part that I cannot for the life of me figure out. Here comes the example. Don't laugh! view.py @login_required def edit_project(request): SampleInformationFormSet = formset_factory(SampleInformationForm, extra=1) DissolutionMethodsFormSet = formset_factory(DissolutionMethodsForm, extra=1) DissolutionEndAnalysisFormSet = formset_factory(DissolutionEndAnalysisForm, extra=1) DissolutionSamplingFormSet = formset_factory(DissolutionSamplingForm, extra=1) DissolutionStandardsFormSet = formset_factory(DissolutionStandardsForm, extra=1) DissolutionMediaFormSet = formset_factory(DissolutionMediaForm, extra=1) DissolutionAnalysisRunFormSet = formset_factory(DissolutionAnalysisRunForm, extra=1) form = ProjectInformationForm(request.POST or None) si_formset = SampleInformationFormSet(request.POST or None, prefix='si') d_formset = … -
The django admin login in is not working and the template is lost
I just get into the Django. everything works on my local: enter image description here but after I deploy it on the on Heroku, the admin login page becomes like this: enter image description here enter image description here and I can not log in ever thought I create the superuser. here is my setting.py INSTALLED_APPS = [ 'event.apps.EventConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', #'django.contrib.gis', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'meetUpFinder.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':[os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] WSGI_APPLICATION = 'meetUpFinder.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR , 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR , 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, … -
Django and Azure SQL Database connection error?
I'm trying to link my SQL database in azure to my django application, here are my settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'network-project', 'USER': 'adminenrique@network-project', 'PASSWORD': '***', 'HOST': 'network-project.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver':'ODBC Driver 13 for SQL Server' }, }} Here's the error when I'm trying to migrate: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial...Traceback (most recent call last): File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Foreign key 'django_admin_log_user_id_c564eba6_fk_network_user_id' references invalid table 'network_user'. (1767) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Enrique … -
Cant get page to redirect with Django
I cant seem to get the redirecting to work. Everything else works up till there please help. Below are my code and error views.py error -
How does one keep a user logged in with Django Rest Framework?
I'm new to Django coming from the Firebase world, where authentication and keeping a user logged in is super easy. In learning Django (Rest Framework) I came to find out that you can log in a user, get a token and save the token in Cookies to reuse is next time that same user goes into the website. Is this the best way to keep a user logged in? So far, I can log a user in, get their token and some additional info, but I'm not sure how to prevent this from happening over and over again. I'd like to know how to keep the user logged in. Also, whenever the user gets back on the browser, do I place a POST request to get their own information (if needed to display on the screen)? Always? I'm very confused as to how authentication/logging in works.