Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing 'self.user' or 'self.user_id' in Django model's clean() method
I need to know if this is possible in a model's clean or save method (ideally clean), without using forms, as I want specific validation logic to be directly tied to the model so that both forms and manager commands (e.g., Model.objects.create() in shell or views) are validated equally. I have ModelB where user is a foreign key of ModelA. I then have a view where a form for ModelB is validated before ModelB is created: if form.is_valid(): form.save() As we all know, form.is_valid() calls model.clean() via self.instance.full_clean(). , and I'm looking to validate something about self.user under the clean() method of ModelB. However, in this Model B clean method, self.user produces: raise self.RelatedObjectDoesNotExist( models.ModelB.user.RelatedObjectDoesNotExist: ModelB has no user. and self.user_id returns None. Essentially, is it possible to reference self.user or self.user_id in ModelB's clean method, or must it go in its save method? -
Attribute Error, 'WSGIRequest' object has no attribute 'get' Django-HTMX
I'm building a homepage that includes a contact-us form. This contact-us form element should be reusable across multiple pages, so I've used HTMX to try incorporate. However am receiving the following error, which I can't make sense of because I'm submitting POST data. Request Method: POST Request URL: http://localhost:8000/contactus Django Version: 4.2.13 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'accounts', 'dashboard'] 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', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback (most recent call last): File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/utils.py", line 67, in render context = context or self.get_context() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 322, in get_context top_errors = self.non_field_errors().copy() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 358, in non_field_errors return self.errors.get( File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 196, in errors self.full_clean() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 433, in full_clean self._clean_fields() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 440, in _clean_fields value = bf.initial if field.disabled else bf.data File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/boundfield.py", line 135, in data return self.form._widget_data_value(self.field.widget, self.html_name) File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 220, in _widget_data_value return widget.value_from_datadict(self.data, self.files, html_name) File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/widgets.py", line 297, in value_from_datadict return data.get(name) Exception Type: AttributeError at /contactus Exception Value: 'WSGIRequest' object has no attribute 'get' ** Forms.py ** This file contains … -
Where is nginx.conf kept on Google App Engine flexible environment?
I am getting nginx.error: client intended to send too large body so I'm trying to fix by making changes to nginx.conf. This is in a Google App Engine that uses Django and deploys to the flexible environment with a Dockerfile. It executes gunicorn to start the app. My nginx.conf file is in the same directory as my app.yaml file. So far, I've tried copying nginx.conf to /etc/nginx/nginx.conf in the Dockerfile just before starting gunicorn. I've tried naming the file nginx-app.conf as suggested elsewhere. I've tried commenting out the entire nginx.conf file to see if it is being used. In every case, I get the "client intended to send too large body" error. Where does nginx.conf live in the flexible environment? Can I change it and copy it to where it needs to be as part of my Dockerfile? Current Dockerfile: FROM ubuntu:bionic RUN apt-get -y update && apt-get -y upgrade \ ... RUN pip3 install virtualenv RUN virtualenv -p python3.8 env ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt ADD . /app WORKDIR /app ENV PORT 8000 EXPOSE 8000 COPY nginx.conf /etc/nginx/nginx.conf CMD exec gunicorn --workers 2 --threads 8 -b :$PORT mysite.wsgi:application My current … -
Django Debug=False returns error traceback
I support Django 4.0 project and notice that even though DEBUG=False, all errors return with tracebacks. I've commented all extras in settings.py, but still receive the traceback. All variebles are deffinately loading (DEBUG) and it happens both localy and on server. we don't need templates to return, just return json, so simply return the basic functionality. Please, give ideas where to look at? # from pathlib import Path import os from datetime import timedelta from django.utils.translation import gettext_lazy as _ # for translation from dotenv import load_dotenv import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from django.utils import timezone from logging.handlers import TimedRotatingFileHandler BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROGECT_DIR = os.path.dirname(os.path.dirname((BASE_DIR))) load_dotenv(os.path.join(PROGECT_DIR, 'infra', '.env'), verbose=True) ENVIRONMENT = os.getenv('ENVIRONMENT') DEVELOPER = os.getenv('DEVELOPER') # LOG_DIRECTORY = os.path.join(BASE_DIR, 'logging') # if not os.path.exists(LOG_DIRECTORY): # os.makedirs(LOG_DIRECTORY) # LOGGING = { # "version": 1, # "disable_existing_loggers": False, # "formatters": { # "verbose": { # "format": "{levelname} {asctime} {pathname} {funcName} {process:d} {thread:d} {message}", # "style": "{", # }, # }, # "handlers": { # "console": { # "level": os.getenv('CONSOLE_LOG_LEVEL', 'DEBUG'), # "class": "logging.StreamHandler", # "formatter": "verbose", # }, # "file": { # 'level': os.getenv('FILE_LOG_LEVEL', 'DEBUG'), # 'class': 'logging.handlers.TimedRotatingFileHandler', # 'filename': os.path.join(LOG_DIRECTORY, 'yume.log'), # 'formatter': 'verbose', # 'encoding': 'utf-8', # # … -
python send InMemoryUploadedFile to requests.request
In postmen I send data like this: My python code is: headers = { "Accept": "*/*", "Content-Type": "multipart/form-data; boundary=974767299852498929531610575", } response = requests.request( "POST", LINK, headers=headers, data={ 'product_id': 1, 'product_images': [file, ] } ) Where file has InMemoryUploadedFile format. But I've got error. Also I've tried file = my_file.file.getvalue() But still the error. How can I fix my cod and get 200 status? Any ideas? -
Wagtail view with URL params, or multiple custom URLs
I have a calendar that is used in a general Django app, but I also want to show it within the Wagtail app (which shows general text content/blog) for this site. I have got to the point where I can display the calendar on the Wagtail page, with some manual entry for the date params. The model for that looks like: class SchedulePage(PostPageExtras, RoutablePageMixin, Page): content_panels = Page.content_panels def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) context['schedule'] = self.get_calendar() return context def get_calendar(self): the_year = 2024 the_month = 7 cal = ScheduleCalendar().formatmonth(the_year, the_month, withyear=True) return cal I have tried to work this out with the RoutablePageMixin but didn’t make any progress. I can generate the_year and the_month values that derive from .now(), so the calendar always shows the current month. But I want the user to be able to navigate to next/previous months. The way that this is done in the Django app is that there are two urls that point to the same view, and the view interprets the parameters as required: path('/schedule/', views.ScheduleCalendarView.as_view(), name='control-schedule-calendar'), re_path(r'^/schedule/(?P<year>\d+)/(?P<month>\d+)/$', views.ScheduleCalendarView.as_view(), name='control-schedule-monthview'), With these two URLs you'll get the same page display (at July 2024): https://example.com/schedule/ https://examle.com/schedule/2024/07/ Because, in the first … -
Nested Serializers create method for each serializer
I have a Club Model as well as an Address model. class Club(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(UserAccount,on_delete=models.CASCADE,related_name = 'owner_of') ##members = models.ManyToManyField(UserAccount,related_name = 'member_of') ##staff = models.ManyToManyField(UserAccount,related_name = 'staff_of') def __str__(self): return f'{self.name}' class Address(models.Model): name = models.CharField(max_length=100) street = models.CharField(max_length=150) city = models.CharField(max_length=100) state = models.CharField(max_length=100, blank=True, null=True) # Optional for countries without states province = models.CharField(max_length=100, blank=True, null=True) # Optional for countries without provinces country = models.CharField(max_length=50) postal_code = models.CharField(max_length=20) club = models.ForeignKey(Club,on_delete=models.CASCADE,related_name = 'address') def __str__(self): return f'{self.name}' They have their respected serializers. class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ['id', 'name', 'street', 'city', 'state', 'province', 'postal_code', 'country'] def create(self,validated_data): user=self.context['user'] club=Club.objects.get(owner=user) address=Address.objects.create(club=club,**validated_data) return address class ClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields = ['id', 'name'] def create(self,validated_data): user=self.context['user'] club=Club.objects.create(owner=user,**validated_data) return club class ClubRegistrationSerializer(serializers.Serializer): address= AddressSerializer2() club=ClubSerializer2() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # We pass the "upper serializer" context to the "nested one" self.fields['address'].context.update(self.context) self.fields['club'].context.update(self.context) this is the data that I am posting { "club":{"name":"someclub"}, "address":{ "name":"Bodrum Location", "street":"140", "city":"bodrum", "state":"california", "province":"some provence", "postal_code":"123", "country":"USA" } } I can easily implement the create method of my view and do this: @action(detail=False,methods=['post']) def register(self, request): serializer = ClubRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) clubinfo_data=serializer.validated_data.pop("club") club_serializer=ClubSerializer(data=clubinfo_data) club_serializer.is_valid(raise_exception=True) club=club_serializer.save(owner=self.request.user) … -
The BaseCommand command is not executed
from django.core.management import BaseCommand class Command(BaseCommand): help = 'Run parser' def handle(self, *args, **options): print('Hello!') I do not understand what this error is related to. The command "run_parser" should have started the parser in Django. -
How to pass list of integers as arguments for django's raw SQL, without formatting string
I'm struggling to figure out how to pass list of integer as arguments for Django's raw SQL without using f-string method. I have tried a simple method of def raw_query(self) -> str: return """select * from table where some_id in %s""" and call with (where ids are list of integer that I already wrap them as tuple) tupled_ids = tuple(ids) with connection.cursor() as cursor: cursor.execute(self.raw_query(), [ids]) Apparently, this wraps the argument with single quote, making them '(1,2,3)' instead of (1,2,3). Thus, syntax error. django.db.utils.ProgrammingError: syntax error at or near "'(1,2,3)'" I've also tried def raw_query(self) -> str: return """select * from table where some_id = any(%s)""" also give me similar error django.db.utils.DataError: malformed array literal: "(1,2,3,4,5)" LINE 2: ...om table where some_id = any('(1,2,3...` I've also tried with named params def raw_query(self) -> str: return """select * from table where some_id in %(ids)s""" with connection.cursor() as cursor: cursor.execute(sql=self.raw_query(), params={ "ids": tuple(ids) }) Still produce syntax error. Looks like django keep wrapping my list with quote. I feel like there must have been an obvious mistake but I can't really figure it out. There are other solutions that suggest to generate a place holder and use f-string to format the raw … -
How to track emails statuses
I am creating an SAAS email marketing system where users can create a company and run campaigns. Each campaign will have its own connected accounts (SMTP). Each user receives emails, which I send through smtplib. I then fetch the emails back using IMAP. I need to track the status of the emails, such as whether they are delivered, opened, or received an automated reply, etc. For all connected accounts that are linked with a company's campaign, the emails will be fetched and shown in the inbox. How can I determine that an email is a reply to a sent email and establish this relationship? How can I track the email status? Here is my model structure class SentEmail(models.Model): campaign = models.ForeignKey(to=Campaign, null=False, blank=False, on_delete=models.CASCADE) company = models.ForeignKey(to=Company, null=True, blank=False, on_delete=models.CASCADE) template = models.ForeignKey(to=EmailVariant, null=True, blank=True, on_delete=models.CASCADE) followup_template = models.ForeignKey(to=FollowUpEmail, null=True, blank=True, on_delete=models.CASCADE) contact = models.ForeignKey(to=Contact, null=False, blank=False, on_delete=models.CASCADE) connected_account = models.ForeignKey(to=ConnectedAccount, null=False, blank=False, on_delete=models.CASCADE) resend_id = models.CharField(max_length=250, null=True, blank=True) email_content = models.TextField(null=True, blank=True) email_sent = models.BooleanField(default=False) email_delivered = models.BooleanField(default=False) email_complained = models.BooleanField(default=False) email_bounced = models.BooleanField(default=False) email_opened = models.BooleanField(default=False) email_clicked = models.BooleanField(default=False) is_followup = models.BooleanField(default=False) is_lead_replied = models.BooleanField(default=False) is_automated_reply = models.BooleanField(default=False) is_positive_reply = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) objects = SentEmailManager() class … -
Errors crash the local development django cookie-cutter container
I've setup Django cookie-cutter for local development in Docker. It all works fine, even with VSCode devcontainer, changes are tracked and reloaded until there's a syntax or some other error. Then the entire container exits with code 1, which launches a cascade of errors in other containers that manage to stay alive while the django container remains dead :( It's all pretty much a generic django cookie cutter install with a few changes like: compose/local/django/start changed to: exec python manage.py runserver_plus --reloader-interval 3 --reloader-type stat 0.0.0.0:8000 watchdog dropped from local requirement, changed to: Werkzeug==3.0.3 Any hints how to reload changes, log errors but keep the container and server alive? Here's the container log for reference: 2024-07-10 13:57:55 Operations to perform: 2024-07-10 13:57:55 Apply all migrations: account, admin, auth, contenttypes, django_celery_beat, mfa, sessions, sites, socialaccount, users 2024-07-10 13:57:55 Running migrations: 2024-07-10 13:57:55 No migrations to apply. 2024-07-10 13:57:55 Your models in app(s): 'core' have changes that are not yet reflected in a migration, and so won't be applied. 2024-07-10 13:57:55 Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. 2024-07-10 13:58:01 Performing system checks... 2024-07-10 13:58:01 2024-07-10 13:58:01 System check identified no issues (0 silenced). … -
how can i fix vercel 404 not found i am working with django [closed]
404: NOT_FOUND Code: NOT_FOUND ID: fra1::ghmqv-1720609782490-787a6e7846dc how i can fix this error on vercel deployment script and screen shot of solutions contact me ifyou can ---------------------------------------------------------------------- -
The less than sign (<) does not work in my django template
The less than sign (<) does not work in my django template, it either treats it as html or it just does not work even if i try to do something simple like {% if 2<5 %}, the greater than sign works fine though I am using it for the paginator but its not working even for normal stuff as mentioned before As evident from the image above the < shows up in red, it does not work even for a simple operation. Here's the same code as text: {% for page in nums %} {% if forloop.counter >= 2 %} {% if forloop.counter == ticket_page.number ⅝} <li class="page-item active">a class="page-link" href="?page={{ forloop. counter }}">{{ forloop. counter }}</a></li> {% elif forloop.counter <= ticket_page-paginator.num_pages %} <li class="page-item"><a class="page-link" href="?page={{ forloop.counter }}">{{forloop. counter }}</a></li> {% endif %} {% endif %}{% endfor %} <!-- Dealing with the Next Pages --> -
Making a @property.setter an editable field in Django Admin Inlines
Documenting my solution here, maybe someone will have a better idea. In my current project, we have a calculated @property displaying a value based off criteria from other fields. Up until this point this was a readonly field so there was no issue with the regular django admin interface. Recently the client wanted to make this field editable (in my actual project it is displaying a DateTime); however, the values were being pulled from two different locations based on the data type and DB constraints. My first thought was to put both fields on the form and inject some JS to show/hide the relevant fields, but I wanted to see if this could be done with django. Going off of some answers I found here and here, I decided to go with a @property.setter and attempt to make it work with the Admin site, the additional context is that this form was currently being displayed in an Inline so I was unable to get either of those solutions to work for my situation. Inline forms... -
Edit entry URL not linking correctly in Django (Python crash course 3rd Ed.)
I'm working through the Python Crash Course book by Eric Matthes. In Chapter 19 i start to run into problems. The 'Edit Entry' section does not load correctly when clicking the link. The link displays where it should, with the text that it should, but when clicking the link i get this message in my browser: Page not found (404) Request Method: GET Request URL: http://localhost:8000/topics/1/%7Burl%20'learning_logs:edit_entry'%20entry.id%7D Using the URLconf defined in ll_project.urls, Django tried these URL patterns, in this order: admin/ [name='index'] topics/ [name='topics'] topics/<int:topic_id>/ [name='topic'] new_topic/ [name='new_topic'] new_entry/<int:topic_id>/ [name='new_entry'] edit_entry/<int:entry_id>/ [name='edit_entry'] The current path, topics/1/{url 'learning_logs:edit_entry' entry.id}, didn’t match any of these. runserver shows this output in the terminal: Not Found: /topics/1/{url 'learning_logs:edit_entry' entry.id} [10/Jul/2024 09:49:24] "GET /topics/1/%7Burl%20'learning_logs:edit_entry'%20entry.id%7D HTTP/1.1" 404 3357 Django Version 5.0.6 Python Version 3.12.4 Here is the relevant code i have so far in the project for reference: **learning_logs/views.py:** from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): ''' The home page for learning_logs ''' return render(request, 'learning_logs/index.html') def topics(request): ''' Show all topics ''' topics= Topic.objects.order_by('date_added') context= {'topics': topics} return render(request,'learning_logs/topics.html',context) def topic(request, topic_id): ''' Show a single topic and all it's entries ''' topic= Topic.objects.get(id=topic_id) entries= … -
How to wrap HTML around a block in django?
Similar to this question which didn't have an answer that works for me. I'm trying to customise allauth templates: email.html extends base_manage_email.html base_manage_email.html extends base_manage.html base_manage.html extends manage.html which I've overidden to extend my base layout. I want to wrap content as follows in base_manage.html: {% extends "allauth/layouts/manage.html" %} {% block content %} <div class="format"> {{ block.super }} </div> {% endblock %} This doesn't work though because I actually need something like {{ block.child }} to wrap where the child content (email.html) will be included. What actually happens is the contents of email.html is directly rendered as in my base.html. How can I simply add default formatting to all the allauth templates that extend base_manage.html? -
How to send authentication session id to django backend using fetch api?
saveBtn.addEventListener('click', function() { const csrftoken = getCookie('csrftoken'); fetch('http://localhost:8000/card/{{ auction.slug }}/add/', { method: 'GET', credentials: 'include', headers:{ 'Content-Type':'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, }, }) .then(function(response) { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(function(data) { if (data.added === true) { saveBtn.innerHTML = 'Saved'; } else { saveBtn.innerHTML = ' Save'; } }) .catch(function(error) { console.error('Fetch request failed', error); }); }); function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.startsWith(name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } I am sending request to django backend via fetch api. When I try to retrieve the request user, TypeError: Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000184986CDE80>>. it returns an error Why django not authenticating using session id? Should I need to send request.user.id but if send that any user can make requests for other users I think. Or am I sending session id incorrectly to backend? views.py def add_to_card(request, slug): if request.user.is_anonymous: pass auction = get_object_or_404(Auction, slug=slug) user = request.user … -
Why session field is not being deleted in django Server sent event?
class task_check(AuthententicatedOrReadOnlyAPIView): content_negotiation_class = IgnoreClientContentNegotiation def get(self, request): timeout = int(request.query_params.get('timeout', 300)) task_id = request.session.get('pending_task_id') if not task_id: return HttpResponse("No pending task", status=404) def event_stream(): start_time = time.time() while True: if time.time() - start_time > timeout: del request.session['pending_task_id'] request.session.modified = True yield f"data: {json.dumps({'status': 'TIMEOUT'})}\n\n" break event_task_id = request.session.get('pending_task_id') if not event_task_id: yield f"data: {json.dumps({'status': 'TIMEOUT'})}\n\n" task = AsyncResult(event_task_id) if task.ready(): del request.session['pending_task_id'] request.session.modified = True yield f"data: {json.dumps({'status': 'DONE'})}\n\n" break else: yield f"data: {json.dumps({'status': 'PENDING'})}\n\n" time.sleep(5) # Check every 5 seconds response = StreamingHttpResponse(event_stream(), content_type='text/event-stream') response['Cache-Control'] = 'no-cache' response['X-Accel-Buffering'] = 'no' return response Now this code inside event_stream does not delete the pending_task_id for some reason, this lines execute as per the logic without error or warning but in next call to get of task_check , the session field pending_task id is as it is -
if my application is runing with docker compose how can I access localhost of within that application
I have a django application which run through docker compose on my local system on localhost:80. I have another application which runs at localhost:3000. I want to access http://localhost:3000 within the django application. While I try to access this I get the below error: ConnectionError at / HTTPConnectionPool(host='localhost', port=3000): Max retries exceeded with URL: /render (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f1a03d7a610>: Failed to establish a new connection: [Errno 111] Connection refused')) If my question is vague or not clear please suggest what more information I can provide? -
How to check a generate code by simply-jwt
I try to verify a code generate by simply-jwt, but the second step when I tried to verify this, it's become False and I try to understand why the purpose it's to generate a code after login and verify this code in a second step here the views calls on the url: class ObtainAuthTokenStep1(TokenViewBase): serializer_class = AuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.validated_data['user'] # Generate a 2FA code and secret secret = base64.b32encode(SECRET_KEY.encode()).decode() totp = pyotp.TOTP(secret) verification_code = totp.now() send_verification_code_via_email(user, verification_code) # Generate a code token with the secret embedded refresh = RefreshToken.for_user(user) refresh['totp_secret'] = secret code_token = str(refresh.access_token) response_data = { 'code_token': code_token, 'message': 'Verification code sent to your email.' } return Response(response_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and the serializers for the check: class AuthTokenStep2Serializer(serializers.Serializer): code_token = serializers.CharField() code = serializers.CharField() def validate(self, attrs): code_token = attrs.get('code_token') code = attrs.get('code') if code_token and code: decode_token(code_token) secret = base64.b32encode(SECRET_KEY.encode()).decode() totp = pyotp.TOTP(secret) if not totp.verify(code): raise serializers.ValidationError(_('Invalid code.')) else: raise serializers.ValidationError(_('Must include "code_token" and "code".')) return attrs If I do the same thing in a terminal I don't have any problem and the sending code work well -
Wagtail/Django Taggit - Unique Tag pool for each set of child pages
For the sake of example, let's say we wanted to create multiple blogs, but in the same app. Each blog has blog posts that are children of each respective blog. Is there away to set up Taggit so that each blogs pool of tags remain separate from each other. Say if one is a food blog, and the other is a car blog, you don't want auto-completion suggestions from one showing up on the other. I have attempted the "Custom Tag Models" example on the Wagtail docs here. With no luck. I've also tried the suggestion on this stackoverflow question. Here is the code from the Wagtail docs above: from django.db import models from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.fields import ParentalKey from taggit.models import TagBase, ItemBase class BlogTag(TagBase): class Meta: verbose_name = "blog tag" verbose_name_plural = "blog tags" class TaggedBlog(ItemBase): tag = models.ForeignKey( BlogTag, related_name="tagged_blogs", on_delete=models.CASCADE ) content_object = ParentalKey( to='demo.BlogPage', on_delete=models.CASCADE, related_name='tagged_items' ) class BlogPage(Page): ... tags = ClusterTaggableManager(through='demo.TaggedBlog', blank=True) Thanks in advance! -
How do I make ApolloClient use multipart/form-data when sending requests to django graphql endpoint
I am writing a Django/GraphQL/Apollo/Vuetify app, and I am struggling to navigate the CORS/CRSF consequences. As far as I understand, I think that Django and GraphQL are doing the right thing on the backend with regard to CORS and CRSF. When I use the python requests library, I can successfully send a request to the graphql endpoint and get a response. To do this, I send a POST request with Content-Type multipart/form-data and make sure that data contains the correct csrfmiddlewaretoken value. @when(u'we execute the GraphQL query "{query}"') def step_impl(context, query): context.response = context.rest_client.post("/graphql/", data={"query": query}) def post(self, path, **kwargs): csrftoken = self.session.cookies.get('csrftoken') if 'data' in kwargs and csrftoken: kwargs['data']['csrfmiddlewaretoken'] = csrftoken return self.session.post(url(path), **kwargs) However, ApolloClient insists on sending the query using application/json and not multipart/form-data. As a result, I cannot add the csrfmiddlewaretoken field to the request payload, and I get a 403 Forbidden response. I've followed the steps outlined in https://apollo.vuejs.org/guide-option/setup.html import { registerPlugins } from '@/plugins' import mitt from "mitt" import { ApolloClient, InMemoryCache } from '@apollo/client/core' const cache = new InMemoryCache() const apolloClient = new ApolloClient({ cache, uri: 'http://localhost:8000/graphql/', credentials: 'include' }) import { createApolloProvider } from '@vue/apollo-option' const apolloProvider = createApolloProvider({ defaultClient: apolloClient, }) … -
No Module Found (import cloudinary) - Django Heroku
import cloudinary_storage import os import ssl import certifi import dj_database_url anytime i try to deploy to heroku, it deploys successful but the page says Application error and cloudinary module not found. I use VSCode and the import cloudinary_storage greys out and i have done everything i could do and still not working, same with import cloudinary I have set my CLOUDINARY_STORAGE and DEFAULT_FILE_STORAGE also. I uninstalled and also install cloudinary and included it in the requirements.txt, same problem occurs -
How do I create a REST API for a project for a hackathon using django which I have no experience of?
I have to create a REST API for a project in django for a hackathon, I have never created one. I have worked on basic django projects but have not built an api. I tried following along a tutorial but the demo project of the tutorial is very different. I have less time how do I approach it -
I have problems loading a machine learning model on my Django site
I've build an image classification model that classifies images as one of three classes: cucumber, zucchini, or neither. Now I want to deploy this model to a Django website but I am currently experiencing some problems. When I run the python manage.py runserver command I get the following printed in the terminal: Watching for file changes with StatReloader Performing system checks... 2024-07-10 01:26:11.875397: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. 2024-07-10 01:26:12.947630: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. C:\path\to\virtual\environment\virtual_environment_name\Lib\site- packages\keras\src\layers\preprocessing\tf_data_layer.py:19: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead. super().__init__(**kwargs) 2024-07-10 01:26:14.748468: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. Now, to me this does not appear …