Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create right relations between models in Django project
I am developing Django progect with following models: class Aircraft_fleet(models.Model): Aircraft_type = models.CharField(max_length=16) Aircraft_Serial_Number = models.CharField(max_length=16) Engine_1_Ser_Num = models.ForeignKey('Engine', related_name='Engine_1', on_delete=models.PROTECT) Engine_2_Ser_Num = models.ForeignKey('Engine', related_name='Engine_2', on_delete=models.PROTECT) class Engine(models.Model): Ser_Num = models.PositiveIntegerField() Flight_Num = models.CharField(max_length=80) Flight_Date = models.DateField() Oil_Quantity_Departure = models.DecimalField(max_digits=5, decimal_places=2) Oil_Quantity_Arrival = models.DecimalField(max_digits=5, decimal_places=2) Oil_Temperature_Departure = models.DecimalField(max_digits=5, decimal_places=2) Oil_Temperature_Arrival = models.DecimalField(max_digits=5, decimal_places=2) One Aircraft (Aircraft_fleet model) have two Engine Ser_Num (different of course). Particular Engine Ser_Num (Engine model) is fitted only on one partucular Aircraft. The thing is that in database, "Engine" table has multiple records for each Engine "Ser_Num". See picture below: Engine Model in database look like: I can't determine how to create the proper relations between these two models. Currently, relation is one to many, but it doesn't work. Following error apears: django.db.utils.IntegrityError: The row in table 'oilcons_aircraft_fleet' with primary key '1' has an invalid foreign key: oilcons_aircraft_fleet.Engine _2_Ser_Num_id contains a value '193262' that does not have a corresponding value in oilcons_engine.id. -
Converting List to QuerySet Django
models.py class Part(models.Model): series = models.CharField(max_length=100) number = models.CharField(max_length=100) brand = models.CharField(max_length=100) class Request(models.Model): part_number = models.ForeignKey(Part, on_delete=models.CASCADE) brand = models.CharField(max_length=100) quantity = models.PositiveIntegerField() date = models.DateField() class Quota(models.Model): part_number = models.ForeignKey(Part, on_delete=models.CASCADE) brand = models.CharField(max_length=100) quantity = models.PositiveIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) supplier = models.CharField(max_length=100) date = models.DateField() views.py def requests_and_quotas(request): requests = Request.objects.all() quotas = Quota.objects.all() result = [] for req in requests: match = False for quo in quotas: if (req.part_number.series == quo.part_number.series) and (abs((req.date - quo.date).days) <= 2): result.append({'request': req, 'quota': quo}) if not match: result.append({'request': req, 'quota': None}) return render(request, 'requests_and_quotas.html', {'result': result,}) I wanted to connect django_filters, but ran into a problem AttributeError: 'list' object has no attribute '_meta'. How can I change the logic of my code to retrieve a QuerySet object? result_qs = QuerySet(result) it didn't help -
how to get task status in celery
I have a celery task and I want the status of the task using task ID. I have read the previous answers but couldn't make it work. I used the command celery -A proj inspect query_task e9f6c8f0-fec9-4ae8-a8c6-cf8c8451d4f8pe command result celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coutoEditor.settings") app = Celery("coutoEditor") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() settings.py CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" tasks.py @shared_task() def speed_up_vid_task(input_path, speed_factor, start, end): ''' Method Params: input_path: The video file url or directory path file name speed_factor: The factor for the speed up process start: start of the video part that needs to be sped up (in secs) end: end of the video part that needs to be sped up (in secs) ''' start = convert_to_sec(start) end = convert_to_sec(end) filename = str(uuid.uuid4()) print(filename, "new") temporary_dir = BASE_DIR + '/' + editor_speedUp_temp_dir # editor_temp_dir = media/editor/speed_vid/temp/" output_dir = BASE_DIR + '/' + editor_speedUp_output_dir # editor_speedUp_output_dir = media/editor/speed_vid/ # Check for broken url r = requests.get(input_path, stream=True) if not r.status_code == 200: return Response({ 'message': "media file is corrupted", 'data': "broken url process could not be completed", 'status': False }, status=status.HTTP_400_BAD_REQUEST) if not os.path.exists(output_dir): os.mkdir(output_dir) if not os.path.exists(temporary_dir): os.mkdir(temporary_dir) stream = os.popen( "ffmpeg.ffprobe -loglevel error -select_streams a … -
Error ! Please! Make sure all fields are entered and valid
Have been trying to use Django forms for contact tab - but getting the - Error ! Please! Make sure all fields are entered and valid. **forms.py ** from django import forms from content.models import Contact class ContactForm(forms.ModelForm): fullname = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100) subject = forms.CharField(required=True,max_length=300) phone_number = forms.CharField(required=True,max_length=100) message = forms.CharField(required=True,widget=forms.Textarea) class Meta: model = Contact fields = [ 'fullname', 'email', 'subject', 'message', 'phone_number', ] def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['fullname'].widget.attrs['placeholder'] = 'Your FullName' self.fields['fullname'].widget.attrs['class'] = 'form-control form-control-lg' self.fields['email'].widget.attrs['placeholder'] = 'Your Email' self.fields['email'].widget.attrs['class'] = 'form-control form-control-sm' self.fields['subject'].widget.attrs['placeholder'] = 'Subject' self.fields['subject'].widget.attrs['class'] = 'form-control form-control-sm' self.fields['phone_number'].widget.attrs['placeholder'] = 'Your Phone Number' self.fields['phone_number'].widget.attrs['class'] = 'form-control' self.fields['message'].widget.attrs['placeholder'] = 'Your Message' self.fields['message'].widget.attrs['cols'] = '30' self.fields['message'].widget.attrs['rows'] = '10' views.py from email.message import EmailMessage from django.shortcuts import render from content.forms import ContactForm from content.models import About, Profile,Primaryskill,Secondaryskill,Services,Portfolio,Blog,Testimonial,Contact from django.contrib import messages #for sending emails and contact from django.http import HttpResponseRedirect from django.core.mail import send_mail from django.conf import settings from django.template.loader import render_to_string from django.template import loader # Create your views here. def Homepage(request): #django orm concept profile = Profile.objects.first() #this will fetch all the data from Profile table first row and store it in profile about = About.objects.first() primaryskill = Primaryskill.objects.all() secondaryskill = Secondaryskill.objects.all() … -
Django : pre-filled forms by database
I created travels (pretty much like products) for my site and I want an admin to chnage some informations about those. So I created a form to change the informations. But I want the form to be pre-filled with the actual informations so the admin just have to change what he wants to change. I've been trying different ways to do it but it never worked. Here is my form : `class ModifAvantTravel(forms.ModelForm): class Meta : model = Travel fields = ['prix', 'description', 'quantite', 'date_depart', 'date_retour', 'lieu', 'affichage'] widgets = { 'prix': forms.NumberInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'quantite': forms.NumberInput(attrs={'class': 'form-control'}), 'date_depart': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), 'date_retour': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), 'lieu': forms.TextInput(attrs={'class': 'form-control'}), 'affichage': forms.CheckboxInput(attrs={'class': 'form-check-input'}), }` Here is my view : `def update_travel(request,id): travel = Travel.objects.get(pk=id) if request.method == 'POST': fm = ModifAvantTravel(request.POST, instance=travel) if fm.is_valid(): fm.save() return redirect("/accueil/gestion/") else: fm = ModifAvantTravel(instance=travel) context = { 'form': fm, } return render(request, 'accueil/update_product.html', context)` I've tried the view : `def update_travel(request,id): travel = Travel.objects.get(pk=id) if request.method == 'POST': fm = ModifAvantTravel(request.POST, instance=travel) if fm.is_valid(): fm.save() return redirect("/accueil/gestion/") else: fm = ModifAvantTravel(instance=travel, initial={'prix': travel.prix, 'description': travel.description, 'lieu': travel.lieu, 'date_depart': travel.date_depart, 'date_retour': travel.date_retour, 'quantite': travel.quantite, 'affichage': travel.affichage}) context = { 'form': fm, … -
How to fix 2005 (HY000): Unknown MySQL server host 'db' (8)
I want to run the database with mysql.connector to create a dataframe, but I caught the problem 2005 (HY000): Unknown MySQL server host 'db' (8) after running with python manage.py runserver. associationrule.py import os import pandas as pd import mysql.connector con = mysql.connector.connect(user='user', password='mariadb', host='db', database='mariadb', port='9051') dfParcel = pd.read_sql("SELECT * FROM LoanParcel", con) dfDurable = pd.read_sql("SELECT * FROM LoanDurable", con) docker-compose.py version: '3.7' services: db: image: mariadb:10 command: --default-authentication-plugin=mysql_native_password restart: always environment: - MYSQL_ROOT_PASSWORD=mariadb - MYSQL_DATABASE=mariadb - MYSQL_USER=mariadb - MYSQL_PASSWORD=mariadb - MARIADB_ROOT_PASSWORD=mysecretpassword ports: - 9051:3306 volumes: - "mysqldata:/var/lib/mysql" web: build: . restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - DATABASE_URL=mariadb+mariadbconnector://user:mariadb@db:9051/mariadb ports: - "9052:8000" depends_on: - db volumes: mysqldata: -
How to display a query on DetailView in Django?
I want my "CustomDetailView" to display a query(a single "flashcard"). I was able to it by using ListView CustomListView(ListView): model = Flashcard template_name = 'flashcards.html queryset = Flashcard.objects.all()[:1] But for DetaiView I'm getting this error Generic detail view CustomDetainView must be called with either an object pk or a slug in the URLconf. class FlashTemplateView(DetailView): model = Flashcard template_name = "flashcards.html" queryset = Flashcard.objects.all().first() How to fix this? -
How to set userkey_id with @setter and token in django?
I have created a client frontend and have tested the url using cUrl and it works, sending the auth token via axios headers allows me in to call the api. The problem is that I get a NOT NULL constraint failed: post_post.userkey_id error and have narrowed it down that the @user.setter is not getting the CustomUser from the Auth Token. How can I correctly use the @user.setter to set the user that has the corresponding auth token/created the post from the client frontend. Views.py class CreatePost(generics.CreateAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self,serializer): serializer.save(user = self.request.user) Post model.py from django.db import models from accounts.models import CustomUser class Post(models.Model): #foriegn keys userkey = models.ForeignKey(CustomUser, on_delete=models.CASCADE) #properties title = models.CharField(max_length=100,blank=True) image= models.FileField(upload_to='files/', null=True, verbose_name="",blank=True) #image field price = models.IntegerField(default=0,blank=True) description = models.TextField(blank=True) likes = models.IntegerField(default=0) tags = models.CharField(max_length=30,blank=True,default="tag1,tag2,...") #sqlite doesnt support arrays date_modified = models.DateTimeField(auto_now=True,blank=True) created = models.DateTimeField(auto_now_add=True,blank=True) sold = models.BooleanField(default=False,blank=True) @property def user(self): return self.userkey.username @user.setter def user(self,value): return models.ForeignKey(CustomUser,on_delete=models.CASCADE) @property def datejoined(self): return self.userkey.date_joined def __str__(self): return self.title The userkey is to get data from the user thus I have a @property def user function to collect data from another object. The userkey and @property def user work fine … -
Celery will continue to execute historical tasks after the worker terminates abnormally and restarts
I added the celery crontab task. When an exception occurs in the worker, I hope that the worker will no longer execute unfinished historical tasks. I used the following task base class and wanted to preprocess the task by judging the status of the worker, but it didn't achieve the result I expected. When I stop the worker, after the time exceeds the task execution time, I restart the worker, it still executes the expired task. class MyTask(Task): def before_start(self, task_id, args, kwargs): inspect = app.control.inspect() active_workers = inspect.active() if not active_workers: print('worker not runing') return False print('worker runing') return super().before_start(task_id, args, kwargs) @app.task(base=MyTask) def test(): return 'test' I hope there is any method or parameter setting that can make the worker no longer execute expired tasks -
Using django crispy-forms wrap to wrap multiple properties
I have a form with lots of repetition and I want to use the wrap function of django crispy forms to reduce this. This is the form as it stands: class MyForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Row(Field(PrependedText('field1', 'Field1title', wrapper_class='col-12 stretchprepend')), title = self.base_fields['field1'].help_text, data_bs_toggle='tooltip', data_bs_placement='bottom', data_html="true"), #fields 2-29 Row(Field(PrependedText('field30', 'Field30title', wrapper_class='col-12 stretchprepend')), title = self.base_fields['field1'].help_text, data_bs_toggle='tooltip', data_bs_placement='bottom', data_html="true") ) CHOICES = [tuple([x,x]) for x in range(1,8)] help_text = {'field1': ''''help text for field 1''' #etc for other fields) field1 = IntegerField( label='Field1title', widget=Select(choices=CHOICES), help_text=help_text['field1']) # Repeat up to field 30 class Meta: model = mymodel fields = ['field1',...,'field30'] I can get wrap to generate some aspects of the form like so: self.helper.layout('field1'...'field30') self.helper[:].wrap(Field, wrapper_class='col-12 stretchprepend') I cant' seem to get it to work to include all the other aspects e.g. PrependedText, title, data_bs_toggle etc Please could anyone advise? -
The code is not taking json payload as post request in terminal but its working in postman
from django.shortcuts import render from django.http import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from myapp.models import Car import json def get_car(request, car_name): if request.method == 'GET': try: car = Car.objects.get(name=car_name) response_data = {'Car': car.name, 'Top Speed': car.top_speed} return JsonResponse(response_data) except Car.DoesNotExist: return JsonResponse({'Error': f'No car with name "{car_name}" found!'}) @csrf_exempt def add_car(request): if request.method == 'POST': try: payload = json.loads(request.body.decode('utf-8')) car_name = payload['car_name'] top_speed = payload['top_speed'] car = Car(name=car_name, top_speed=top_speed) car.save() response_data = {'Success': 'Car added successfully!'} except: response_data = {'Error': 'Car could not be added!'} print(response_data) return JsonResponse(response_data) -
Issue using nested serializer with django-rest-framework
I'm trying to create a nested serializer, UserLoginSerializer , composed of a UserSerializer and a NotificationSerializer, but I'm getting this error when it tries to serialize: AttributeError: Got AttributeError when attempting to get a value for field email on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserSerializer instance. Original exception text was: 'UserSerializer' object has no attribute 'email'. Here is my models.py: class Notification(models.Model): kind = models.IntegerField(default=0) message = models.CharField(max_length=256) class User(AbstractUser): username = models.CharField(max_length=150, blank=True, null=True) email = models.EmailField(unique=True) customer_id = models.UUIDField(default=uuid.uuid4, editable=False) And my serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "id", "first_name", "last_name", "email", "customer_id" ] class NotificationSerializer(serializers.ModelSerializer): class Meta: model = Notification fields = [ "id", "kind", "message", ] class UserLoginSerializer(serializers.Serializer): user_info = UserSerializer(read_only=True) notifications = NotificationSerializer(many=True, read_only=True) The error occurs at the last line in this endpoint: def get_login_info(self, request): notifications = Notification.objects.filter(recipient=request.user) serializer = UserLoginSerializer( { "user_info": UserSerializer(request.user), "notifications": NotificationSerializer(notifications, many=True), } ) return Response(serializer.data) What am I doing wrong? -
Assiging the lastest terms and condtions to users upon sign in
I have the following model for the terms and conditions: class TermsAndConditions(models.Model): text = models.TextField() date_modified = models.DateTimeField(auto_now=True) def __str__(self): return f'Terms and conditions, last modified on {self.date_modified}' class UserAgreement(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) agreed = models.BooleanField(default=False) agreed_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) terms_and_conditions = models.ForeignKey(TermsAndConditions, on_delete=models.PROTECT) def __str__(self): return f'Agreement for user {self.user.username}' I have the following views: @login_required def show_terms_and_conditions(request): try: user_agreement = UserAgreement.objects.get(user=request.user) except UserAgreement.DoesNotExist: user_agreement = UserAgreement.objects.create(user=request.user) terms_and_conditions = user_agreement.terms_and_conditions return render(request, 'tac/termsandconditions.html', {'terms_and_conditions': terms_and_conditions}) @login_required def agree(request): if request.method == "POST": user_agreement = UserAgreement.objects.get(user=request.user) user_agreement.agreed = True user_agreement.save() return redirect(reverse('........')) else: return redirect(reverse('.......')) My objective to to assign the latest terms and conditions to every user who signs in and if it is not agreed then to show here is what I tried # @login_required # def show_terms_and_conditions(request): # latest_tac = TermsAndConditions.objects.latest('date_modified') # user_agreement, created = UserAgreement.objects.get_or_create(user=request.user, terms_and_conditions=latest_tac) # if created: # # If the user agreement was created in this request, set `agreed` to False and update the `agreed_at` field # user_agreement.agreed = False # user_agreement.agreed_at = timezone.now() # user_agreement.save() # terms_and_conditions = user_agreement.terms_and_conditions # # return render(request, 'tac/termsandconditions.html', {'terms_and_conditions': terms_and_conditions, 'user_agreement': user_agreement}) The reason I am doing this is because I keep … -
Django migrations deployment strategy with AWS ECS Fargate?
What is the recommended deployment strategy for running database migrations with ECS Fargate? I could update the container command to run migrations before starting the gunicorn server. But this can result in concurrent migrations executing at the same time if more than one instance is provisioned. I also have to consider the fact that images are already running. If I figure out how to run migrations before the new images are up and running, I have to consider the fact that the old images are still running on old code and may potentially break or cause strange data-corruption side effects. I was thinking of creating a new ECS::TaskDefinition. Have that run a one-off migration script that runs the migrations. Then the container closes. And I update all of the other TaskDefinitions to have a DependsOn for it, so that they wont start until it finishes. -
Property destructuring pattern expected.javascript
How to fix this ',' expected.javascript Property destructuring pattern expected.javascript var map_{{ forloop.counter }} = new google.maps.Map(document.getElementById('map_{{ forloop.counter }}'), { zoom: 8, center: {lat: {{ image.lat }}, lng: {{ image.lon }}} }); var marker_{{ forloop.counter }} = new google.maps.Marker({ position: {lat: {{ image.lat }}, lng: {{ image.lon }}}, map: map_{{ forloop.counter }} }); -
Django on Ubuntu giving libpq version 10 error
I am trying to setup a Django website on linux ubuntu with postgresql, gunicorn and nginx. However every time I try to start the development server I get this following error: Traceback (most recent call last): File "/home/ubuntu/personalserver/manage.py", line 22, in <module> main() File "/home/ubuntu/personalserver/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 323, in cursor return self._cursor() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 299, in _cursor self.ensure_connection() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 281, in ensure_connection with self.wrap_database_errors: File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, … -
Can´t find a way to change the initial value of the primary key id, and make start from it on my models
I really apreciate somebody's help.... I am working on django, so I created my table on my models.py.... by default when I start registering data, the id, set as primary key, begins with the initial value #1 and counting on each time I do a new register. But, I have loaded some data in my table, so the final id right now is 185. I runserver and try to add a new register, but I get an error about id duplicity..... django is trying to save in id # 1 the actual register.... but I want it to continue saving the register from id #186 and counting on... I have tried doing this on my models: class MyModel(models.Model): id = models.AutoField(primary_key=True, initial=123) but it does not recognizes the kwarg 'initial' So I am stuck right now.... -
How to creating Image with matplotlib and instaly displaying it? Django + Python
I want my program to display map created with matplotlib that uses .csv file and display that map alongside with JSON data. Map alone actually works, but I want it to open on next page with JSON data. Now I can only go to next page that contains JSON data after I close the map window which opens on home page. On next page I get "Failed to load resource: the server responded with a status of 404 (Not Found)" from DevTools. And other problem is after a while it doesn't even open, just keeps loading with no error. Closing terminal and putting again virtual env and python manage.py runserver works but then it happens again. And if you leave JSON alone, it works perfectly so I guess map is the problem. This is the main page. So you gotta click X on map window then it proceed to next page This is the next page, you can even go back and forth when map is minimalized from django.shortcuts import render import json import urllib import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np import pandas as pd def Last1Hour(request): # this is for reading … -
How to setup django-anymail with mailgun?
I've installed django-anymail and add it in the settings.py: # settings.py ... if not DEBUG: INSTALLED_APPS += [ "anymail", ... ] ... ...and configure as described in the quickstart docs: # settings.py ... # Mail configuration # https://anymail.dev/en/stable/quickstart/ ANYMAIL = { "MAILGUN_API_KEY": env("MAILGUN_API_KEY"), "MAILGUN_WEBHOOK_SIGNING_KEY": env("MAILGUN_WEBHOOK_SIGNING_KEY"), "MAILGUN_SENDER_DOMAIN": env("MAILGUN_SENDER_DOMAIN"), } EMAIL_BACKEND = ( "django.core.mail.backends.console.EmailBackend" if DEBUG else "anymail.backends.mailgun.EmailBackend" ) # DEFAULT_FROM_EMAIL = f"from@{env('MAILGUN_SENDER_DOMAIN')}" DEFAULT_FROM_EMAIL = "from@mysandboxdomain.mailgun.org" # SERVER_EMAIL = f"server@{env('MAILGUN_SENDER_DOMAIN')}" SERVER_EMAIL = "server@mysandboxdomain.mailgun.org" ... I also use dj-rest-auth for authentication. Which sends email after successful registration, tested with django.core.mail.backends.console.EmailBackend. But when I runserver and register a new account with DEBUG=False to test anymail.backends.mailgun.EmailBackend, it throws Server Error (500) and nothing else. Please help me, what I am doing wrong? -
Group by month based on DateTime Field
I have a model for hotel reservations: class PaymentRequest(SoftDeleteModel): class Meta: verbose_name_plural = "PaymentRequests" user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False, default=None) customer_first_name = models.TextField(blank=False, null=False) customer_last_name = models.TextField(blank=False, null=False) arrival_date = models.DateTimeField(blank=True, null=True) What I'd like to do is make a queryset to group my reservations by month and get a count of it. i.e {'jan' : 10, 'feb' : 11, etc..} I've seen some answers like this but does not work quite right, maybe since it was answered 10 years ago. Appreciate any help. -
this is the code for my manage.py script i would like someone to explain each line please i barely understand it
import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookr.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() the code works i just do not understand why -
How to convert a queryset quickly?
Through an ajax request I request data from the database that has 70 thousand lines. The query is very fast, it lasts 0.2 seconds but I can't return it because I can't return queryset by JsonResponse, so I have to convert it to json but that's the problem. How to convert as fast as possible? I tried using the following code, but it still takes like 6 seconds. queryset = Users.objects.all() list = [] [list.append({"id": query.id, "name": query.name}) for query in queryset] return JSONResponse(list, safe=False) -
How Do I properly create a three column responsive grid
I'm having a little difficulty implementing a three column grid in Django. I'm trying to create a page where my blog post are displayed in columns of three. I'm using bootstrap to do this and I just cant seem to figure out how to get this right. I implemented a for loop in order to display a grid of three. I'm either getting three of the same articles. Which is not what i'm trying to accomplish. Please let me know if you have any idea of how I accomplish fix this. Below you can find my code. {% for post in object_list %} <div class="row "> <div class="column" style="background-color:#grey" > <div class="card h-100 " style="max-width: 24rem; max-height: 28.5rem; "> <img src="{{ post.header_image.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"><a href="{% url 'article-detail' post.pk post.slug %}">{{ post.title }}</a></h5> <p class="card-text">{{ post.snippet }}</p> </div> <div class="card-footer"> <small class="text-muted">By: {{ post.author.first_name }} {{ post.author.last_name }} - {{ post.post_date }} - </small> <a href="{% url 'category' post.category|slugify %}" style=text-transform:uppercase;">{{ post.category }}</a> </div></div></div></div> {% endfor %} -
Unable to install mysqlclient using virtualenv (Fedora 37)
I am developing an app using Django 4 and have set up a virtual environment using venv. THe problem I have is I cannot get the mysqlclient package installed using pip in order to allow my django app to connect to an existing MariaDB hosted on the same server. I am using Fedora 37, Python 3.11.1 . Everytime I try to install mysqlclient via pip within my virtual environment I the the below error: (venv) $ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [18 lines of output] /bin/sh: line 1: mysql_config: command not found /bin/sh: line 1: mariadb_config: command not found /bin/sh: line 1: mysql_config: command not found Traceback (most recent call last): File "", line 2, in File "", line 34, in File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup.py", line 15, in metadata, options = get_config() ^^^^^^^^^^^^ File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup_posix.py", line 70, in get_config libs = mysql_config("libs") ^^^^^^^^^^^^^^^^^^^^ File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not … -
Django many-to-many: I want to query the bootcamps the user has signed up for
#This is my Model.py from django.db import models from django.contrib.auth.models import User class Tipo_Categoria(models.Model): nombre = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) class Bootcamp(models.Model): titulo = models.CharField(max_length=50) contenido = models.CharField(max_length=500) imagen = models.ImageField(upload_to='bootcamps') requisito1 = models.CharField(max_length=100) autor = models.ForeignKey(User, on_delete=models.CASCADE) categoria = models.ManyToManyField(Tipo_Categoria) fecha_inicio = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) class ProgramasAcademico(models.Model): codigo = models.BigIntegerField(null=False, unique=True, primary_key=True) nombre = models.CharField(max_length=100) status = models.BooleanField(default=True) class BootcampInscripcion(models.Model): cedula = models.IntegerField(blank=True, null=True) nombre = models.CharField(max_length=100) apellido = models.CharField(max_length=100) usuario = models.ForeignKey(User, on_delete=models.CASCADE) carrera = models.ManyToManyField(ProgramasAcademico) email = models.EmailField(max_length=254) direccion = models.CharField(max_length=100) telefono = models.CharField(max_length=10) bootcamp = models.ManyToManyField(Bootcamp) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) #This is my Views.py from django.shortcuts import render from bootcamps.models import * from django.contrib.auth.models import User def mis_bootcamp(request,id): try: bootcampBd = BootcampInscripcion.objects.filter(usuario=id) except BootcampInscripcion.DoesNotExist: print("no tiene cursos") else: cursos = Bootcamp.objects.filter() #Bootcamps return render(request, "campus/mis_bootcamp.html",{"bootcampBd":bootcampBd,"cursos":cursos}) Each user has signed up for a bootcamp or several. I want you to help me is in which It would be the query or the way to filter only the bootcamps to which the user signed up. user and thus publish (title, image) of the bootcamp in the html. I appreciate your help.