Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed save update Profile Form Django
i want to validate a form using isValid but there's a problem that im unable to find is there anything wrong here? this is my web look like this is my views @login_required(login_url='pengurusan/signin') def post_update(request, pk): user = User.objects.get(id=pk) userr = User.objects.filter(id=pk) profilee = Profile.objects.filter(id=pk) if request.method == 'POST': #print(request.POST) user_form = PasswordChangeForm(user = request.user , data=request.POST) profile_form = ProfileForm(request.POST, instance=request.user) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return render(request, 'pengurusan/index.html') user_form = PasswordChangeForm(user = request.user , data=request.POST) profile_form = ProfileForm(instance=user.profile) context={ "user_form" : user_form, "profile_form" : profile_form, "user" : user, "userr" : userr, "profile" : user.profile, "profilee" : profilee, } return render(request, 'pengurusan/update-form.html', context) this is my form class Meta: model = User fields = ('email', 'username', 'password') widgets = { 'email' : forms.EmailInput(attrs={'class' : 'form-control form-control-user', 'id' : 'exampleInputEmail', 'placeholder' : 'Email Address', 'name' : 'email'}), 'username': forms.TextInput(attrs={'class' : 'form-control form-control-user', 'id' : 'exampleFirstName', 'placeholder' : 'username', 'name' : 'username'}) } class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['nama', 'nik', 'email', 'nomor_hp'] widgets = { 'nama': forms.TextInput(attrs={ 'id' : 'exampleFirstName', 'placeholder' : 'Name'}), 'nik' : forms.NumberInput(attrs={'id' : 'exampleLastName', 'placeholder' : 'Nomor Identitas Penduduk'}), 'email' : forms.EmailInput(attrs={'id' : 'exampleInputEmail', 'placeholder' : 'Email Address', 'name' : 'email'}), 'nomor_hp' : … -
How do I create a rich content preview of a Spotify track, playlist or album (I am using Django/Python)?
I am building a forum-type web application on Django. On Twitter, FB and WhatsApp, when you send a URL of a Spotify track to someone, a preview card is automatically generated showing an image and a title/description of the track (along with a link). I would like to know how to do this on my website, so that when a user sends a post, a similar preview is automatically generated (a link showing the image and title/description). -
Getting attendance meeting data, example: Microsoft teams to use for my attendance monitoring Web application made using django
So I'm trying to receive attendance data from a Teams meeting using Api, in form of json or any other object. (for Web application) -
Django error on image upload: raise MultiValueDictKeyError(key)
I am trying to upload an image with Ajax, however, when I submit my form using ajax I get an error: django.utils.datastructures.MultiValueDictKeyError: 'image' Below is my form element: <form method="POST" class="submit-img-pro-form" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image" accept="image/*" id="id_image"> <div class="mt-2 d-flex justify-content-center"> <div> <div class="d-flex justify-content-center mb-2"> <img class="img-create-post rounded-circle" style="height: 8rem;width: 8rem;" src="{{ request.user.image.url }}"/> </div> <div id="updtimgbtn" style="margin-left: 10px;" class="d-flex justify-content-center"> <button type='button' data-url='{% url 'main:update-image' hid=request.user.get_hashid %}' id='submit-img' class='btn no-border no-outline mr-3 edit-profile-clickable text-primary'>Update</button> </div> <div style="margin-left: 10px;"class="d-flex justify-content-center"> <button type="button" id="chppbtn" class="btn no-border no-outline text-center mr-3 edit-profile-clickable text-primary"> Change Profile Picture </button> </div> </div> </div> </form> This is my Ajax code: $(document).on('click','#submit-img', function (e){ alert("ok") $.ajax({ type: "POST", url: $(this).attr("data-url"), dataType: 'json', data: $(this).closest("form").serialize(), success: function (data){ $('.edit-pro-all .pro-img-ctr').text(data.image_updated); }, error: function(rs, e){ console.log(rs.responeText); }, }); }) And this is my views: @login_required def update_image(request, hid): data = dict() id = hashids_user.decode(hid)[0] user = Profile.objects.get(id=id) if request.method=="POST": image_not_default = False if request.user == user: user = request.user if request.user.is_authenticated: print(request.FILES) image = request.FILES['image'] user.image = image user.save() if request.user.image.url != 'defaults/user/default_u_i.png': image_not_default = True context = { 'image_not_default':image_not_default } data['image_updated'] = render_to_string('main/image_update.html',context,request=request) return JsonResponse(data) I have tried printing request.FILES but it returns an empty … -
How do I use abstract model field values as default values in child model fields in Django?
For example, class Foo(models.Model): foo_field = models.CharField(max_length=30) class Meta: abstract = True class Bar(Foo): bar_field = models.CharField(max_length=30, default=Foo.foo_field) def __str__(self): return self.name This code doesn't actually produce the results I want, but I think it illustrates the general idea. Basically, I want to take the value from foo_field and use it as a default value if no value is entered for bar_field. I've tried returning foo_field with a ___str___ method in the Foo model and defining a variable in Bar with that value (i.e. foo_field_value = Foo.foo_field, but that didn't allow me to access the value either. -
Deploying Django app to Heroku with incorrect migrations
I wrote a custom Django migration to pre-populate my sqLite database with data for my app. However, I messed up the migration a couple of times, and each time I didn't realize it until after and I had already run the migration. I ended up flushing my database and rewriting several custom migrations just to pre-populate my database. I then realized that I had an issue with how my models were defined, so I had to make a migration to redefine some fields of my models, run that migration, then rerun my own custom migration. Long story short, I have several incorrect migrations in an app that I'm trying to push to Heroku. I can't run all the migrations on Heroku, since half of them are incorrect. At the same time, I need to run the migrations in order for my app to have access to the data it needs. Is there a way I can run each migration except the incorrect ones? Or is there another solution? -
How to connect containerized django app to local mysql server, that is outside container running on host machine?
I am trying to connect my django application that is running inside container to use mysql that is running on local machine outside continer as database. Dockerfile FROM python:latest ENV PYTHONUNBUFFERED 1 RUN mkdir /src WORKDIR /src/ COPY ./requirements.txt /src/requirements.txt RUN pip install -r /src/requirements.txt COPY . /src/ EXPOSE 8000 CMD [ "python", "manage.py", "migrate" ] CMD [ "python", "manage.py", "runserver","0.0.0.0:8000" ] docker-compose version: '3' services: web: build: . command: sh -c "/wait && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" networks: host: settings.py DATABASES = { "default": { "ENGINE": 'django.db.backends.mysql', "NAME": 'dbname', "USER": 'devuser', "PASSWORD": 'test1234', "HOST": '127.0.0.1', "PORT": 3306, } } And i am using ubuntu system . When i am running this code getting this error django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") Any help will be highly appriciated. Thanks for your HELP :) -
Heroku not returning a Django JsonResponse
I have an django app which is being hosted by Heroku. My problem is that the Heroku is not returning the Json response. I know the code is working because the Heroku logs are printing the data, and response, in the log window yet Heroku is returning a 500 error. Below is what is being printed in the log console. Jul 31 08:03:27 app app/web.1 RUNTIME of get_advertiser_organic_pins: 10.77 seconds. Jul 31 08:03:27 app app/web.1 <JsonResponse status_code=200, "application/json"> Jul 31 08:03:27 app app/web.1 x.x.x.x - - [31/Jul/2020:15:03:26 +0000] "POST /organic/ HTTP/1.1" 500 27 "-" "PostmanRuntime/7.26.2" here is the code in my views.py # POST organic/ def get_data(request): if request.method in ["POST", "OPTIONS"]: access_token = request.headers.get("token") if access_token is None: return JsonResponse( { "error": "Access token is missing", } ) request.session["access_token"] = access_token request_payload = json.loads(request.body) profile_id = request_payload["selectedProfile"]["externalId"] try: data = atmospheric_digest(profiles_data) except Exception as error: return JsonResponse( { #"error": f"{error}", "error": str(data), }, status=401, ) payload = { "data": data, } print(JsonResponse(payload)) return JsonResponse(payload) -
Passing Ajax Request to Django View on Multiple Button Click
I'm trying to Pass data to View with two Click events with Ajax Post, everything goes well, when I have only one Button event (click event), but when I added the second click event I'm getting and error If there is a need of more reference please let me know. Template (With Two Buttons and Two dropdowns) <select class="selectpicker form-control Plottype"> <option value="1">Line</option> <option value="2">Scatter</option> <option value="3">Bar</option> <option value="3">Barh</option> </select> <div class="btn btn-primary getplot1">Plot1</div> <select class="valueCountCol selectpicker form-control" name="valueCountCol"> <option>Col1</option> <option>Col2</option> </select> <div class="btn btn-primary getplot2">Plot2</div> Ajax POST (in script) $(document).ready(function () { $(".getplot1").on('click',function () { var plottypevalue = $(".Plottype option:selected").text(); $.ajax({ url: "/", type: "post", // or "get" data: {'plot1':plottypevalue}, headers: { "X-CSRFToken": "{{ csrf_token }}" }, // for csrf token success: function (data1) { console.log(data1); }, }); }); $(".getplot2").on('click',function () { var valueCountCol = $(".valueCountCol option:selected").text(); $.ajax({ url: "/", type: "post", // or "get" data: {'plot2':valueCountCol}, headers: { "X-CSRFToken": "{{ csrf_token }}" }, // for csrf token success: function (data1) { console.log(data1); }, }); }); }); Views.py if request.POST['plot1']: plottypevalue = request.body.unicode('utf-8') data1 = plottypevalue return HttpResponse(json.dumps(data1), content_type="application/json") if request.POST['plot2']: valcountcol = request.body.unicode('utf-8') data1 = valcountcol return HttpResponse(json.dumps(data1), content_type="application/json") Error Internal Server Error: / Traceback (most recent call … -
Recommendations for Boilerplates for Django projects based on django-rest- framework
I am developing a side project with Django, django-rest-framework, celery, and MongoDB. I used to use cookiecutter boilerplate when initializing Django projects that work with HTML templates. Now things aren't the same, because my project will produce APIs, so I will use django-rest-framework. I know that I can use the cookiecutter and do some edits after initializing the projects, but I am seeking to know another alternative that working with django-rest-framework. So my questions are: Is it preferable to not use boilerplates, especially when using MongoDB, and to initialize the project by Django's traditional way? And if it is preferable to use boilerplates, what boilerplates do you recommend it to me? Actually I made a search and found "django-rest-framework-boilerplate", "cookiecutter-django-rest", and "django-drf-boilerplate". But it will be great if you shared your thoughts and recommendations with me. Thanks in advance. -
How to compress images uploaded through ckeditor in Django?
I'm using ckeidtors RichTextUploadingField for my Django app and I was wondering if there is a way of compressing the image uploaded through ckeditor before storing it in the server. -
How to let a user view a web page but if they click on a specific button it leads them to the login page using django
I am working on a E-com. website and have a category page in which i have products.Currently for my code the page wont open if a user is not a customer(logged in).I want a non-logged in user to access the page but if he chooses to add an item in cart it leads him to the login page. def category(request): customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() cartItems=order.get_cart_items types = Category.objects.all() prods= Product.objects.all() return render(request,"category.html",{'types':types,'prods':prods,'cartItems':cartItems}) -
How to query for permissions on custom model in Django?
I'm creating an app in which each user can be a member of many systems, each system can have many members, and on top of that, each member has system-specific permissions. I've created a System model along with intermediate SystemMember model that holds data about permissions: # apps/systems/models.py from django.contrib.auth.models import Permission class System(models.Model): name = models.CharField() class Meta: permissions = [ ('can_change_name', 'Can change the systems name'), ] class SystemMember(models.Model): system = models.ForeignKey(System, related_name="members") user = models.ForeignKey(User, related_name="memberships") # an extra field for permissions permissions = models.ManyToManyField(Permission) My question is - is this an optimal way of implementing permissions in this case, and how would I go about finding out if the member has specific permission? What would be ideal: member = user.memberships.get(system__id=1) if member.has_perm('systems.can_change_name'): pass Would I have to implement my own has_perm method, or is there an easier way of dealing with this particular problem? Are there any serious drawbacks of implementing a custom permissions model in your experience? eg. # apps/systems/models.py class SystemMemberPermissions(models.Model) member = models.ForeignKey(SystemMember, related_name="permissions") can_manage_system = models.BooleanField(default=False) can_manage_members = models.BooleanField(default=False) can_manage_documents = models.BooleanField(default=False) -
Change the displayed value in ModelchoiceField
I have a group model with 2 instances: groupA and GroupB. I am retrieving those values into my SignupForm with the ModelChoiceField. I need to give those 2 Groups other labels, lets say LabelA and LabelB due to UX design. I made a workaround by adding a new field (Slug) to the Group model that stores that Label value for each of the Group instances. I changed the Query set to make it retrieve the values of the Slug field. As expected I cant Signup like this because the two fields have different values. Is there a way to, or label the choices of the first queryset i made, or is there some kind of workaround to associate? forms.py class CustomSignupForm(SignupForm): user_group = forms.ModelChoiceField(queryset=CustomGroup.objects.values_list('slug', flat=True), widget=forms.RadioSelect(attrs={'placeholder': 'Soort klant:'}), initial='Voor jezelf', help_text='' ) # first_name = forms.CharField(max_length=30, label='Voornaam', # widget=forms.TextInput(attrs={'placeholder': 'Voornaam'}),) # last_name = forms.CharField(max_length=30, label='Achternaam', # widget=forms.TextInput(attrs={'placeholder': 'Achternaam'}),) field_order = ('user_group', 'email') #, 'first_name', 'last_name',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['user_group'].label = "" self.helper.error_text_inline = False custom_adapter.py class UserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): user = super(UserAccountAdapter, self).save_user(request, user, form, commit=False) user.user_group = form.cleaned_data.get('user_group') user.save() user.groups.add(user.user_group) if user.groups.filter(name='zakelijk').exists(): user.is_active = False else: user.is_active = True … -
Django DecimalField max_digits and decimal_places not explicitly known
I am working on adding a Django model where there are a number of fields that I want created as a DecimalField, but I don't know the max_digits or decimal_places for each of these columns. I am using a postgres database; the table structure comes from and will be populated by an API source. I was able to get DDL for the table, create the table in a blank postgres db, and use inspectdb to create a Django model. The result assigned all DecimalField columns with: models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) The model contains ~170 DecimalField fields. Are there any ideas or suggestions on how I should handle the creation of these fields? -
Display the {{MEDIA_URL}} that is inside the RichTextField in the Django template
I need to render {{MEDIA_URL}} within a Django RichTextField, along with HTML. I'm using {% autoescape off%} to display the HTML, and that's ok, but MEDIA_URL is not processed. The image link looks like this: <img src="{{MEDIA_URL}}image.jpeg"/> models.py: from ckeditor.fields import RichTextField from django.db import models class TextHTML(models.Model): text_html = RichTextField settings.py: 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', 'django.template.context_processors.media', ], }, }, ] Is there any way to do this? -
Graphene resolve nested object
I'm trying to query nested object but I'm getting an error about the type as playground docs is showing that it'is JSONString() I have a model: class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) data = JSONField() Query: class UserType(DjangoObjectType): class Meta: model = User class Query(ObjectType): user = graphene.Field(UserType, id=graphene.Int()) def resolve_user(self, info, **kwargs): id = kwargs.get('id') return User.objects.get(id=id) What I'm getting is correct but the type for data is JSONString() and I'm not able to query that.. Playground docs: id: UUID! name: String! data: JSONString! SO When I do query query { user(id: 12) { id, name, data {// cannot query nested objects ///} } } the example of data: data = { "key1": { "subKey": [], "subKey": [], }, "key1": { "subKey": { "subsubKey": [] } }, } Is it possible to make all keys queryable and get rid of JSONString() type ?? I've tried approach: def resolve_user(self, info, **kwargs): id = kwargs.get('id') user = User.objects.get(id=id) user.data = json.loads(user.data) return user Then I'm getting an error: "the JSON object must be str, bytes or bytearray, not dict" Is there any wau to change JSONString() type to make it queryable ? -
Django: Get the second user object
So I have this model objects in my project model objects each one of the objects has this data on it this data, what I need is to get the second user that is save in the objects. I am new in django so I dont know how to do it, but is this something to queryset?, and how can I get the second user in my views?. Here is my code: models.py from django.db import models from django.conf import settings from django.db import models from django.db.models import Q class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None qlookup1 = Q(first__username=username) & Q(second__username=other_username) qlookup2 = Q(first__username=other_username) & Q(second__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model( first=user, second=user2 ) obj.save() return obj, True return None, False class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() @property def … -
Celery Worker not starting with queue
celery -A proj worker --autoscale=6,4 --loglevel=INFO -n worker_name -Q queue1,queue2 I am using django-celery to run a task which in turn schedules another task in the 2nd queue. I am using redis as the broker. The problem is that with the above command, the worker isn't running, there's no message being printed in the logs about the task after the worker is "ready" as seen below: Logged in Successfully System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace -------------- celery@worker_name v3.1.25 (Cipater) ---- **** ----- --- * *** * -- Linux-5.4.0-42-generic-x86_64-with-Ubuntu-18.04-bionic -- * - **** --- - ** ---------- [config] - ** ---------- .> app: proj:0x7f0d03316eb8 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: redis://127.0.0.1:6379/ - *** --- * --- .> concurrency: {min=4, max=6} (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .> queue1 exchange=queue1(direct) key=queue1 .> queue2 exchange=queue2(direct) key=queue2 [tasks] . proj.celery.debug_task . task1 . task2 [2020-07-31 14:53:31,916: INFO/MainProcess] Connected to redis://127.0.0.1:6379// [2020-07-31 14:53:31,926: INFO/MainProcess] mingle: searching for neighbors [2020-07-31 14:53:32,933: INFO/MainProcess] mingle: all alone [2020-07-31 14:53:32,956: WARNING/MainProcess] {path}/superenv/lib/python3.6/site-packages/celery/fixups/django.py:265: UserWarning: Using settings.DEBUG leads to a memory leak, never use … -
Want to have Django From dropdown filtered by logged-in User (Customer), using __init__ method
Want to have Django From dropdown filtered by logged-in User (Customer), using init method. But when submit the form, keep having this Field 'id' expected a number but got <QueryDict: { error: class OrderForm(ModelForm): class Meta: model = Order fields = ['contract', 'quantity', 'status'] def __init__(self, customer, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['contract'].queryset = Contract.objects.filter(customer=customer) @login_required(login_url='login') def createOrder(request): customer = request.user.customer.id form = OrderForm(customer) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.customer = request.user.customer form.save() messages.success(request, 'Ticket submitted successfully .') return redirect('customer_table') context = {'form':form} return render(request, 'create-order.html', context) -
Intercept all exceptions from a certain app in Django/DRF
For example a have a main app, let’s say for users handling and secondary app where I would create logs, models change history, statistics, ets. Generally most of the CRUD activity in main app tigers CREATE operations in secondary app via signals to create logs and stuff. What I want to achieve is to avoid exceptions being raised by secondary app from being propagated and shown to user via DRF response or make them ‘fail silently’ in a way, as , for instance, is user would update his account and history log subsequently created in secondary model would raise Integrity error – better just continue and do nothing rather then notify user about it. There are to main types of exceptions - IntegrityError and ValidationError. I could try to try/except all validation ones and maybe use custom exception handler to intercept Integrity errors if I know constraints names but a) I still can’t intercept them all as some of them are originated from Django source code 2) A lot of hardcode. Question is – is it possible somehow to intercept all exceptions from a certain app and suppress them all? Thank you. -
Integrating django-import-export with react
I have a postgresql database and I want to add data to it. I want to upload an excel file containing the data and save it to database. I have a backend server of django and a frontend server of React. I am easily able to import the data from the excel sheet to database using django_import_export but from the django admin. What I want is, to do this using React and for normal users(non superusers) also. Is there a way to integrate django_import_export with react? Any other way to implement this functionality is also apreciated. -
how do i get discord user's guilds in django allauth
Im trying to get guilds that the discord user in. i have added the scope to the settings.py SOCIALACCOUNT_PROVIDERS = { 'discord': { 'SCOPE': [ 'email', 'identify', 'guilds' ] } } i have added the app to the django admin dashboard and it works fine when i try to login using discord but when i add guilds scope it wont store the records anywhere as far as i looked for. -
How to make clickable anchor text in django app
I am learning django by making a simple app. I have this text that i want to be clickable when the page is loaded. single_text = '<a href="https://my-link.dot-com">Cows lose their jobs as milk prices drop </a>' As of how, the whole thing is being displayed and i want only the text to show with the link attached. How do I go about it? Or maybe point me in the right direction as far as what i should search for in the docs? Thanks -
UnicodeEncodeError in model object creation in Django
I'm getting this error message: UnicodeEncodeError at /new_app/ 'charmap' codec can't encode character '\x87' in position 127: character maps to <undefined> I get data from a query in teradata using pandas and python teradata module. After creating connection, I do this: In [10]: df = pd.read_sql(sqlStr, self.session) In [11]: df Out[11]: Ref Client Order Group Start Date Item Date Value 0 2020-04-30 01234567890 SECURITIZAÃ?øO 45678901234 1995-11-13 2014-08-23 21031.96 1 2020-04-30 01234567890 SECURITIZAÃ?øO 45678901234 1995-11-13 2014-08-23 21031.96 There is a problem in the word "SECURITIZAÃ?øO". Then I've tried to do the following: In [12]: from django.core.files.base import ContentFile In [13]: from new_app.models import QSet In [14]: content = data.to_csv(index=False, encoding='utf-8') In [15]: csvname = "test_name" In [16]: csf = ContentFile(content, csvname) In [17]: q = QSet.objects.create(owner = "somebody", csv_file = csf) Then I got the error above. This is my model config: class QSet(models.Model): date_query = models.DateField(default=now, blank=True, null=True) owner = models.CharField(max_length=25) csv_file = models.FileField(blank=True, upload_to='new_app') And , I don't know if it matters, here are some settings of my project: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I am struggling with this error and I think that I am misunderstanding some steps …