Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I ignore inserting a duplicate in Django?
I have some static tables that I'm initializing like this with a Management Command Suit(name="Clubs").save() Suit(name="Hearts").save() Suit(name="Diamonds").save() Suit(name="Spades").save() I want to be able to re-run this anytime, in case there are new values, but I want to avoid inserting duplicates. The database has a Unique constaint, so if there are duplicates I'll get an error. Other than wrapping each individual statement in a try/catch, is there a way I can run several statements like this and ignore the Constraint Violation and keep going? -
Understanding PostgreSQL benefits over ElasticSearch
I need help understanding the solution. What is in the project. It is Django project. There is a table with users, dependent table to it many to many, a table with geolocation and a large amount of specific data that are stored for each user, let's call them LargeData. Now these data are saved in ElasticSearch, which is bound to data from PostgreSQL, except for LargeData, they are not saved in PostgreSQL, but are saved in ES when registering a user. Problem. After receiving data from ES, the program filters these data additionally, it turns out slowly, so it was decided to move the filtering to ES or PostgreSQL. I considered both options and came to the conclusion that it is better to use PostgreSQL for filtering, and ES for getting LargeData, so you can use a convenient ORM in the program and have the advantages of ES to find the necessary data. Another programmer came to the conclusion that it is better to leave all data in ES and add data filtering there as well. Questions. I thought it's better to use SQL to implement links between tables, search them through ORM, solve normalization problems, but the other programmer … -
Django ORM to query string treats model choice value as column
I have the following Django ORM code and something weird is happening. When I comment the if part for library_level, query is working fine. If I add any new Q expression then the value provided as Q(field=value), value is treated as another field. query = ( (Q(domains=[]) | Q(domains__contains=domain)) # rule matches domain & (Q(klass=[]) | Q(klass__contains=dom_class)) # rule matches class & (Q(standards__contains=cdisc_version)) # rule matches standards & (~Q(exclusions__contains=domain)) # domain is not in excluded list & (~Q(exclusions__contains=dom_class)) # dom_class is not in excluded list ) if not library_level: query &= ~Q(rule_type=DataCheckRuleType.DATASET_CHECK) required_checks = DataCheckRule.objects.filter(query).values( "rule_id", "domains", "message", "description", "exclusions", "klass", "standards", "detail_string", "ex_domains", "rule_type", "params", ) sql_query = str(required_checks.query) Printing above sql_query gives SELECT "datacheck_rules"."rule_id", "datacheck_rules"."domains", "datacheck_rules"."message", "datacheck_rules"."description", "datacheck_rules"."exclusions", "datacheck_rules"."klass", "datacheck_rules"."standards", "datacheck_rules"."detail_string", "datacheck_rules"."ex_domains", "datacheck_rules"."rule_type", "datacheck_rules"."params" FROM "datacheck_rules" WHERE (("datacheck_rules"."domains" = \'[]\' OR "datacheck_rules"."domains" @> \'"DATA"\') AND ("datacheck_rules"."klass" = \'[]\' OR "datacheck_rules"."klass" @> \'"UNKNOWN"\') AND "datacheck_rules"."standards" @> \'"SDTMIG 3.2"\' AND NOT ("datacheck_rules"."exclusions" @> \'"DATA"\') AND NOT ("datacheck_rules"."exclusions" @> \'"UNKNOWN"\') AND NOT ("datacheck_rules"."rule_type" = dataset_check)) You can see that 'dataset_check' is treated as column instead of string which is giving me an error, mentioned column don't exist. I am creating sql_query to use as relevant_checks = pd.read_sql(sql_query, connections["default"]) My DataCheckRuleType is … -
Send email via EmailMultiAlternatives sudenly stopped working
I encounter a strange error. The email sending stopped working since yesterday before all was fine. I did not change a thing at all. Error message is: 2024-07-11 09:35:01,147 share.email.service ERROR Traceback (most recent call last): File "/srv/deduu/./share/email/service.py", line 318, in send_email_from_template cls.send_admin_email(subject, recipient_list, html_message=message) File "/srv/deduu/./share/email/service.py", line 330, in send_admin_email cls.send_email(subject, from_mail, recipient_list, message, html_message) File "/srv/deduu/./share/email/service.py", line 279, in send_email return email_wrapper.send_mail() File "/srv/deduu/./share/email/service.py", line 91, in send_mail return_value = bool(self.mail.send()) File "/srv/deduu/.venv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/srv/deduu/.venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 109, in send_messages sent = self._send(message) File "/srv/deduu/.venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 125, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/lib/python3.8/smtplib.py", line 874, in sendmail (code, resp) = self.mail(from_addr, esmtp_opts) File "/usr/lib/python3.8/smtplib.py", line 539, in mail return self.getreply() File "/usr/lib/python3.8/smtplib.py", line 398, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed Strangely the sending of the mail works with a testscript with the same credentials and settings but using this snippet from email.message import EmailMessage import smtplib username = "info@test.de" password = r"*****" smtp_server = "mail.test.de" smtp_port = 47999 receiver_email = "user@test.de" subject = 'Test Email' body = 'This is a test email sent using smtplib in Python.' # Create message em = EmailMessage() em['From'] = username em['To'] = … -
Does httpsstreamingresponse block the thread? or How many clients are allowed in one thread?
I have implemented basic server sent event in django using httpsstreamingresponse, which at every 5 second send the response! class task_status_stream(AuthententicatedOrReadOnlyAPIView): # to respond as text/event-stream we need to ignore exisiting Client Content negotiation content_negotiation_class = IgnoreClientContentNegotiation # sending pf creation status to as StreamingHttpResponse def get(self, request): timeout = int(request.query_params.get('timeout', 300)) def event_stream(): start_time = time.time() try: while True: if time.time() - start_time > timeout: yield f"data: {json.dumps({'status': 'TIMEOUT'})}\n\n" break task = AsyncResult(task_id) if task.ready(): yield f"data: {json.dumps({'status': 'DONE'})}\n\n" # noqa W503 break else: yield f"data: {json.dumps({'status': 'PENDING'})}\n\n" time.sleep(5) # Check every 5 seconds except Exception as e: logger.error(f"Error during streaming: {e}") yield f"data: {json.dumps({'status': 'ERROR', 'message': str(e)})}\n\n" finally: logger.info("Ending the streaming response") response = StreamingHttpResponse(event_stream(), content_type='text/event-stream') response['Cache-Control'] = 'no-cache' response['X-Accel-Buffering'] = 'no' return response now does this above implementation would block the thread or block the port untill event stream is closed from client side? or it will keep executing for 300 seconds timeout! also another question is how many users at a time can do start this streaming response using one thread and how to increase that limit? -
Logout Process in Django and " Url Logout next" Parameter Error
I am creating a blog page using Django where users can log in and out, write, and share blog posts. After logging in, users should be able to add blog posts, and if they are not logged in, they should only be able to view posts published by others. I am using the Django "{% url 'logout' %}?next=/" parameter for logging out and making a POST request in the form. However, I have another POST request in my code, and these two requests are conflicting. How can I fix this issue? Here is the code I am using for the logout request: <ul class="dropdown-menu text-small "> <li><a class="dropdown-item" href="{% url 'blogapp:profile' %}">Profile</a></li> <li><a class="dropdown-item" href="{% url 'blogapp:settings' %}">Settings</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="{% url 'login' %}">Sign in</a></li> <!-- <li><a class="dropdown-item" href="{% url 'logout' %}?next=/">Log out</a></li> --> <div class="logout"><li><form action="{% url 'logout' %}?next=/" method="POST"> {% csrf_token%} <button type="submit" class="nav-link btn btn-link">Logout</button></li></div> </ul> Here is the code I am using for the other POST request: {% extends "base.html" %} {% block content %} <div class="container" style="margin-top: 25px; padding: 20px; width: 60%; margin: auto;"> <form action="" method="POST"> {% csrf_token %} <div style="text-align: center;"> <input type="text" name="blog_title" placeholder="Title..." style="width: 80%; font-size: 2em; padding: 10px; … -
How to get specific user data from a table with foreignKey to another tables Django
I have 3 table from django.db import models from django.contrib.auth.models import User class Boost(models.Model): title = models.CharField(max_length=50,null=False)# point, storage, point p/s, expire = models.BooleanField(default=False) expireDate = models.DateTimeField(null=True) visiblity = models.BooleanField(default=True) def __str__(self): return "id:"+self.title class BoostLevel(models.Model): id = models.AutoField(primary_key=True) boost = models.ForeignKey(Boost, on_delete=models.CASCADE) level = models.IntegerField(null=False) def __str__(self): return self.boost.title + " level: " + self.level.__str__() class UserBoostList(models.Model): boostLevel = models.ForeignKey(BoostLevel, on_delete=models.CASCADE) boostId = models.ForeignKey(Boost, on_delete=models.DO_NOTHING) userId = models.BigIntegerField(null=False) In my case, Boost is a title, Boost level are levels for boost and UserBoostList are User selected boost Each boost can have many level from 1 to X. Each user should start boost from level 1 to level 2 to and go on I need to check each user have which level of boost for each boost let me explain I have Boost A and boost B in Boost table and boosts level 1 ,2 ,3 ... for each boost separate, Ex(boost A level 1, boost A level 2 and ... AND boost B level 1 , boost B level 2 and ...) Now how can I get info for username like Alex to know which level he boosted for each boost Note: You can add or remove any field … -
Where to store referral code until purchasing somthing in django ecommerce website
I am new to django and I have an ecommerce shop. Now I have added a referral link feature in which after ordering a unique link will be generated and other can come to the website using that link. the referral link url is somthing like this : http://127.0.0.1:8000/orders/referral/qEAKfbOx15n3maHKtgBmhflH1ISPo45q And the url pattern is : path('referral/<str:unique_id>/', views.referral, name='referral') I am redirecting referral user to store page and pass unique id in referral view: def referral(request, unique_id): if get_object_or_404(OriginOrder, unique_id=unique_id): return redirect(reverse("store") + "?u_id=" + unique_id) now in store page although I have the unique_id but until purchasing something, The user may call a lot of urls like choosing products, search on categories and see the products detail, so in fact I need to store this unique id until purchasing something and then add a reward to the person who sent the referral link to current user. So what is the best option here. I heard about sessions but I do not know if It is a right option here. I also was thinking about adding a parameter to the cart of the user called referral code with a null value for default but the problem is that, cart is created … -
Django static files doesn't work on smartphones
I am using the Django framework to build my web app and have deployed it using ngrok. Why can't my phone access the static images in the template when visiting the ngrok URL, but my computer can? My template {% load static %} <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <img src="{% static 'img/hero-img-1.png' %}"> </body> </html> My setting.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = "django-insecure-@p&wu2ht6d&50!yox%%#k*i(8*q(yc(3qyusw@uydit0hm42r&" DEBUG = True ALLOWED_HOSTS = [ '6785-123-240-57-1.ngrok-free.app', '127.0.0.1', ] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'testdebug.apps.TestdebugConfig' ] 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 = "debug.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates').replace('\\', '/')], "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", ], }, }, ] WSGI_APPLICATION = "debug.wsgi.application" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": 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_TZ = True STATIC_URL = "static/" DEBUG = True STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" My folder enter image description here Thank you … -
django-filter DateFromToRangeFilter can't not filte between two dates
I'm building vue3 + django DRF project. I'm making my consumelists from and I want to filte bewteen two days. likes 2024-06-01 to 2024-06-30. I used DateFromToRangeFilter but not work. please help. omz My model.py class ConsumeDetails(models.Model): date = models.DateField() category = models.CharField(max_length=100) subcategory = models.CharField(max_length=100) vendor = models.CharField(max_length=100) item = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=0) remarks = models.CharField(max_length=100) consumetype = models.ForeignKey(ConsumeType, on_delete=models.PROTECT) consumepurpose = models.ForeignKey(ConsumePurpose, on_delete=models.PROTECT) class Meta: managed = True app_label = 'myweb' db_table = 'Consume_Details' def __str__(self): return self.date My filter.py class ConsumeDetailsFilter(FilterSet): # date = filters.DateFilter(field_name='date') RegDate= DateFromToRangeFilter(field_name='date', lookup_expr='gte',lable='date range') category = filters.CharFilter(field_name='category', lookup_expr='icontains') subcategory = filters.CharFilter(field_name='subcategory', lookup_expr='icontains') vendor = filters.CharFilter(field_name='vendor', lookup_expr='icontains') item = filters.CharFilter(field_name='item', lookup_expr='icontains') class Meta: model = ConsumeDetails fields = ['RegDate','category', 'subcategory', 'vendor', 'item', 'price', 'remarks'] My serializers.py class ConsumeDetailsSerializer(serializers.ModelSerializer): consumepurpose = ConsumePurposeSerializer() consumetype = ConsumeTypeSerializer() class Meta: model = ConsumeDetails fields = '__all__' My views.py class ConsumeDetailsViewSet(ModelViewSet): queryset = ConsumeDetails.objects.all() serializer_class = ConsumeDetailsSerializer filterset_fields = ['consumepurpose','consumetype','category','subcategory','RegDate'] search_fields = ['category','subcategory','vendor','item'] pagination_class = MyPageNumberPagination Error message in here enter image description here I want use star_date and end_date to filte the range like the link below http://127.0.0.1:8000/accounts/consumedetails/?**start_date=2024-06-01&end_date=2024-06-30** -
Django view getting called twice (double get request) primary key gets set equal to None
Running a django project on localhost, and i have a go to profile button which sends a pk (the username) back to the profile view and currently i have some debugging code inside the view and i see it runs twice. First it prints the correct pk of whatever profile I clicked then it says pk :None and gives "GET /profile/None HTTP/1.1" 500 before error Received pk: tim [10/Jul/2024 21:15:52] "GET /profile/tim HTTP/1.1" 200 26400 before error Received pk: None Internal Server Error: /profile/None I have no idea why its calling twice, the weird thing is the site is still working, it correctly goes to the correct profile but just throws error in terminal. Thanks! -
How do I ensure that my Frontend is the Origin sending a POST request to my Backend
I have a Vue 3 frontend site that I want to be able to sign up new users. When the user enters their information into the frontend, the frontend will send a POST request to the backend which is a Django REST API. The backend will then create the user. But how can I verify that the frontend is the Origin sending the request? I would think there would be a problem if someone just set up a script to execute 1000 curl commands to flood my database with users (although I guess someone could still do this if they set up an automated script to enter information via selenium or something). Would it be secure for Django to look at the Origin header when handling the POST request or can this be forged? I have also already read the accepted answer here but it did not really answer my question. -
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 -->