Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn/Nginx/Django - 500 Error is not producing error logs
I have a django site in production running NGINX/Gunicorn/Supervisor. I have an imageupload Field which fails and returns a 500 error page from Gunicorn. Although my error logs don't tell me anything. How am I supposed to debug this problem? logs: ubuntu@ip-172-31-29-176:/logs$ cat gunicorn.err.log [2021-02-15 02:12:20 +0000] [11369] [INFO] Starting gunicorn 20.0.4 [2021-02-15 02:12:20 +0000] [11369] [INFO] Listening at: unix:/home/ubuntu/gsc/app.sock (11369) [2021-02-15 02:12:20 +0000] [11369] [INFO] Using worker: sync [2021-02-15 02:12:20 +0000] [11372] [INFO] Booting worker with pid: 11372 [2021-02-15 02:12:20 +0000] [11374] [INFO] Booting worker with pid: 11374 [2021-02-15 02:12:20 +0000] [11375] [INFO] Booting worker with pid: 11375 /etc/nginx/sites-enabled/django.conf server{ listen 80; server_name ec2-54-188-59-209.us-west-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/gsc/app.sock; } location /static { alias /home/ubuntu/gsc/assets/; } location /media { alias /home/ubuntu/gsc/media/; } } /etc/supervisor/conf.d/django.conf [program:gunicorn] directory=/home/ubuntu/gsc command=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/gsc/app.sock gsc.wsgi:application autostart=true autorestart=true stderr_logfile=/logs/gunicorn.err.log stdout_logfile=/logs/gunicorn.out.log -
How include Recipients to django-postman
in django postmon, when sending a message, an empty recipient field, how to auto-detect the recipient by ID, if the message is sent from the recipient's profile page? thank -
How to make the django-filter issue a request and transform it into a geoJSON?
I want to display my data from the database on a web map, in the form of a geoison. Since I'm new to development, I am lacking in knowledge. The Djnago filter displays my geoDjango coordinates from the database on HTML as: SRID = 4326; POINT (78.407707 44.998262). Is there an option for integration with Django Rest Framework, which gives data in the form of JSON? Help me please. Thank you in advance. #------------------------------------------------------------------------------------------------------ #filters.py import django_filters from .models import SubstationTable, PowerLine10Table, TransformerTable class SubstationFilter(django_filters.FilterSet): class Meta: model = SubstationTable fields = [ 'owner_substation', 'section_substation', 'substation_number', ] class PowerLine10Filter(django_filters.FilterSet): class Meta: model = PowerLine10Table fields = [ 'owner_powerline10', 'section_powerline10', 'substation', 'powerline10_number', ] class TransformerFilter(django_filters.FilterSet): class Meta: model = TransformerTable fields = [ 'owner_transformer', 'section_transformer', 'powerline10', 'transformer_number', ] #------------------------------------------------------------------------------------------------------ #views.py def web_map(request): substation_filter = SubstationFilter(request.GET, queryset=SubstationTable.objects.all()) powerline_filter = PowerLine10Filter(request.GET, queryset=PowerLine10Table.objects.all()) transformer_filter = TransformerFilter(request.GET, queryset=TransformerTable.objects.all()) context = { 'title': 'WEB_MAP', 'substation_filter': substation_filter, 'powerline_filter': powerline_filter, 'transformer_filter': transformer_filter, } return render(request, 'app_webmap/app_webmap_page.html', context)``` #------------------------------------------------------------------------------------------------------ #models.py from django.db import models from django.contrib.gis.db import models class SubstationTable(models.Model): """Substation""" owner_substation = models.ForeignKey( OwnersTable, on_delete=models.CASCADE, verbose_name='Owner:') section_substation = models.ForeignKey( SectionsTable, on_delete=models.CASCADE, verbose_name='Section:') substation_number = models.CharField(max_length=25, unique=True, verbose_name='Substation number:') substation_name = models.CharField( max_length=25, unique=True, blank=True, null=True, verbose_name='Substation name:') visibility_on_map= … -
Django stuck on default splash page in production
I just set up a deployment server with NGINX/GUNICORN. I've uploaded my project and all I see is the "welcome to django" splash page. No matter what I do, I can't get rid of this. When I run: ./manage.py runserver 0:8000 I can access my website through port 8000, and it works! I don't understand why the production server (using the same code) won't do anything. I even changed debug=False, and the splash screen still thinks I'm in debug mode. I have even deleted my pycache folder. No change. -
Django Template: Add Variable Into URL As Parameter
What's the proper way to add {{gamestoday|lookup:i}} into the <a href={%url 'stats'%}>. Do I need to make changes to urls.py? {% load tags %} <center> <div class = "scoreboardbackground"> <div class="row"> {% for i in ngames %} <div class="col"> <a href={%url 'stats'%}> <div class="livegamebox"> {{teamnames|lookup:i|lookup:0}} vs {{teamnames|lookup:i|lookup:1}} - {{gamestoday|lookup:i}} <br> <div style="font-size:12px;"> {{datetimegames|lookup:i}} </div> <br> <div style = "font-size:30px"> <b>{{latestscore|lookup:i}}</b> </div> </div> </a> -
Django: Need help returning 2 sets of data in the same view
I am trying to return 2 different sets of data in the same view. The two tables: Restaurant Foods Models class Restaurant(models.Model): PRICING = ( ("£", "£"), ("££", "££"), ("£££", "£££"), ) name = models.CharField(max_length=50) slug = models.SlugField(unique=True) description = models.TextField(null=True) price = models.CharField(max_length=10, null=True, choices=PRICING) category = models.ManyToManyField(Category) def __str__(self): return str(self.name) class Foods(models.Model): name = models.CharField(max_length=200, null=True) description = models.TextField(null=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) image = models.ImageField(null=True, blank=True, upload_to="food_images/") price = models.FloatField() def __str__(self): return self.name On this view, I'm trying to list the restaurant data as well as the food data. But how do I access the food data for that specific restaurant? Views def restaurantDetailView(request, slug): restaurant = Restaurant.objects.get(slug=slug) context = { "restaurant": restaurant, } return render(request, "restaurants/restaurant_detail.html", context) This is the HTML <div class="container restaurant-container" padding-top="40px"> <div class="card"> <div class="row no-gutters"> <div class="col-sm-5" style="background: #868e96;"> <img src="{{ restaurant.image.url }}" width="500px" class="card-img-top h-100" alt="..."> </div> <div class="col-sm-7"> <div class="card-body"> <h5 class="card-title" style="font-size:28px;">{{restaurant.name}}</h5> <hr> <p class="card-text">{{restaurant.description}}</p> <p class="card-text">{{restaurant.category.all|join:" | " }}</p> <div class="row" style="padding:10px 0px 10px;"> <div class="col">Price: {{restaurant.price}}</div> <div class="col">Location: {{ restaurant.postcode }} | {{ restaurant.city }}</div> </div> <div class="row" style="padding:10px 0px 10px;"> <div class="col">Avg Wait: {{restaurant.min_serve_time}} mins</div> <div class="col">Minimum Order: £{{restaurant.min_order_tk}}0</div> </div> </div> </div> … -
How to have Django raise ValidationError as Popup?
I am using a custom clean() function on one of my forms for a conditional field requirement. I am able to raise the validation error on my template as a part of the DOM using {{ form.non_field_errors }}. I would like to have the validation error come up as a popup like the default errors do, but do not know how. Here is the custom clean() function: class ReportForm(forms.Form): def clean(self): cleaned_data = super().clean() class_type = cleaned_data.get("class_type") class_other = cleaned_data.get("class_other") if class_type == "Other": if not class_other: msg = "Please fill out this field." raise ValidationError(msg) I don't know what to put in views or the template to have it show as a popup - I don't currently have anything special there. Is it possible with Django, or do I need to use javascript? -
Django Model @property duplicates queries
Django model properties is useful to access in run time, however this does not come without cost. Below property cause huge duplicate queries due to database hit with each query (product). @property def total_stock(self): """ SKU total stock """ total = SKU.objects.filter( product=self ).values_list("stock").aggregate(Sum(F("stock"))).get("stock__sum") or 0 return total Any thought how to use django model @property in efficient way? -
Fabric keep asking for user password, although key_filename is set
I am using fabfile for django deployment. I am connecting to my deployment servers through bastin host (using env.gateway option in fabfile, env.gateway=bastin_IP) and then running required commands. Following options are set in fabfile, added for reference. env.gateway = 'user@xx.xx.xx.1' #bastin_IP env.key_filename = ['path/to/pem/file'] env.user = 'user' env.port = 22 Now whenever I run command, it always prompt for password of user, message shown like this. [xx.xx.xx.002] Login password for 'user': Note: here IP shown before message is the IP of my deployment/prod server. What I am assuming (after seeing above message) is that connection is being made with bastin successfully, but it is not connecting with deployment/prod server. Although whenever I try to connect via putty (on windows), I can login to bastin host (using openssh private key) then from bastin to any other deployment/prod server without password. Please let me know, what is the actual issue and how to resolve that. What I am doing wrong? Any help is appreciated. -
Call Microsoft Authentication in a Custom Login Form
So I'm creating a custom login form and really would like to include the option so that users can login in via office365 account. To do this I have used the django_microsoft_auth functionality. When going to admin it is working perfectly, however really would like to know how should I use it in a custom form. I did not find any documentation how this can be done and really would like some feedback on this. So in my login there will be a button then when pressed it will redirect to Microsoft authentication site and when completed it will redirect to the homepage. What do I need to include the the href in my template? and do I need to add something in the views.py or there is no need? Thanks -
autoreload.restart_with_reloader - how to reboot with --noreload key? [django]
how to restart the server with the --noreload key and back? from django.utils import autoreload autoreload.restart_with_reloader(--noreload) #for example #some code autoreload.restart_with_reloader() can i restart the server with the --noreload key? and then back with no key? if manually, but it is necessary in the code dynamically python manage.py runserver ctrl+c python manage.py runserver --noreload ctrl+c python manage.py runserver -
Get a string variable from views to urls in Django
I am a beginner at python and especially Django, I am trying to solve a problem where when a user searches, if that search is valid, i want to get that search = var_X, in my URL like: "www.website.com/search/var_X" or something like, "www.website.com/search/<df.item>" -Views.py- def views_search(request): temp_dict = {} if request.method == 'POST': var_X = request.POST['var_X'] try: df = wsc.Summary(temp_dict, var_X) except Exception as e: df = "ERROR" return render(request,'search.html', {'df' : df}) else: return render(request,'home.html', {'var_X' : "Not Found"}) -- Urls -- from django.urls import path from . import views from requests import * urlpatterns = [ path('search/<var_X>', views.views_search, name="url-search"), ] -- HTML -- <form action="{% url 'url-search' var_X %}"class="d-flex" method="POST"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Enter String" aria-label="Search" name="var_X"> <button class="btn btn-outline-secondary" type="submit">Search</button> </form> -
Convertir lista a formato fecha en Django [closed]
estoy intentando convertir esta lista: `[datetime.date(2021, 1, 19), datetime.date(2021, 1, 20), datetime.date(2021, 1, 22)]` a un formato date() que se mire de la siguiente manera: [2021-01-19,2021-01-20, 2021-01-22...] estoy usando Django y no encuentro la manera de hacerlo convertir la lista a un formato date. -
django not picking up migration where managed = False
I have a simple web-app I'm trying to create to visualise some carbon data (to teach myself Django!) As my data model is a little complex I use the managed=False and import a view from my postgres database where I wrangle my data. When I first ran the migration I noticed I left in a field that I didn't have in my view, so naturally I changed it. Now when I run makemigrations for my app called carbon it says there are no changes. What is the correct way to remedy this? additionally, for some reason when I try to run an orm query to pull in some data it expected me to have an id field in my view, can someone explain this, if possible? models.py class CarbonViewHour(models.Model): daily_hour = models.CharField(max_length=50) reading = models.FloatField() #date = models.DateField() This was removed class Meta: managed = False db_table = 'carbon_v_hourly_meter_readings' def __str__(self) -> str: return f"{self.meter}-{self.reading}-{self.date}-{self.daily_time}" the change I made was to remove a field from CarbonTimeView date = models.DateField() views.py class CarbonTimeView(TemplateView): template_name = 'carbon/chart.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['qsm'] = CarbonViewMinute.objects.all().order_by('date') context['qsh'] = CarbonViewHour.objects.all() context['title'] = 'Daily Carbon Data' return context SQL View. DROP VIEW IF EXISTS … -
django storages AWS S3 SigVer4: SignatureDoesNotMatch
My configuration (very basic): settings.py AWS_S3_REGION_NAME = 'eu-west-3' AWS_S3_FILE_OVERWRITE = False # S3_USE_SIGV4 = True # if used, nothing changes # AWS_S3_SIGNATURE_VERSION = "s3v4" # if used, nothing changes AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "xxx" AWS_STORAGE_BUCKET_NAME = 'xxx' # AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' # if used, no pre-signed urls AWS_DEFAULT_ACL = 'private' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'xxx' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' INSTALLED_APPS = [ ..., 'storages' ] models.py class ProcessStep(models.Model): icon = models.FileField(upload_to="photos/process_icons/") What I get: Pre-signed url is generated (both in icon.url and automatically on admin page) Pre-signed url response status code = 403 (Forbidden) If opened, SignatureDoesNotMatch error. With text: The request signature we calculated does not match the signature you provided. Check your key and signing method. Tried: changing access keys (both root and IAM) changing bucket region creating separate storage object for icon field (same error SignatureDoesNotMatch) changing django-storages package version (currently using the latest 1.11.1) Opinion: boto3 client generate_presigned_url returns url with invalid signature Questions: What should I do? Why do I get the error? -
dictionaries of objects as fields in models.py
I want to create an option of inventory and skills list and for that I wrote those classes: class Drop(models.Model): name = models.CharField(max_length=200) description=models.CharField(max_length=2000) class Skill(models.Model): name = models.CharField(max_length=200) description=models.CharField(max_length=2000) manaCost=models.IntegerField() then I want the player to have them as dictionaries, the key will be "name" and the value all the object. here is the code for character modle: class Character(models.Model): raceList = Race.objects.all() roleList = Role.objects.all() user=models.ForeignKey(User,related_name='characters',on_delete=models.CASCADE) name=models.CharField(max_length=200) description=models.TextField() race = models.ForeignKey(choices = raceList,on_delete=models.CASCADE) role = models.ForeignKey(choices = roleList,on_delete=models.CASCADE) attack = race.attack+role.attack deffence = race.deffence+role.deffence intelligence = race.intelligence+role.intelligence agility = race.agility+role.agility wisdom = race.wisdom+role.wisdom charisma = race.charisma+role.charisma i want to add the fields "inventory" and "skills" -
Admin static files not loading in production for Django site
Django==2.1.1 I'm using Amazon ElasticBeanstalk I've ran collectstatic and the files are properly stored in my /Assets folder My main website images all load perfectly fine when I deploy. But the admin page does not load any statics, just get 404 errors. I already have 'django.contrib.staticfiles' installed under settings. here is a portion of my settings.py; STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = os.path.join(BASE_DIR,'assets') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' Thank you. -
How to seperate wagtail image's tags from page's tags?
Suppose we have a wagtail page defined like this: class PostTag(TaggedItemBase): content_object = ParentalKey( 'PostPage', related_name='tagged_items', on_delete=models.CASCADE ) class PostPage(Page): ... tags = ClusterTaggableManager(through=PostTag, blank=True) ... content_panels = Page.content_panels + [ ... FieldPanel('tags') ] When I want to edit tags field on wagtail admin, it suggests not only pages' tags but also images' tags. I want to some how remove images' tags from suggestions. In my project, pages' tags are not related to image's tags. To understand the scenario, look at these two pictures: The first one shows adding river as a tag into one of the images. The second one shows the tags field on PostPage. I don't want to see the river tag as a suggestion on page's tags: Is that possible? If not, Is it possible to remove tags field from wagtail image model? -
Django send email to user that is in the same group that login user is in
I have an app that sends the email to the director of the respective department when the manager of that particular department approved a leave. However, for some reason, when the manager approved the leave. The app also sends the email to the directors who are from different departments instead of one director who is in the same group as the manager. I want to send an email to only the director that is in the same group as the manager. For instance, I have three groups. finance, accounts, ICT. if the manager that approves the leave is in the finance department then when the finance manager approves the leave an email should be processed and send only to the director of finance. Here is the function that send the email to the director @login_required(login_url='home') def Manager_send_sick_leave_email_to_Director(request, staff_id): query_set = Group.objects.filter(user=request.user) in_group = User.objects.filter(groups__name="Director").filter(groups__name=query_set[0]).filter( groups__name="authorizer") for a in in_group: to_send = [a.email] send_mail("Approved Sick Leave", "The unit Manager" + " " + staff_id.Authorized_by_Manager + " " + "have " + staff_id.Manager_Authorization_Status + " " + staff_id.user.first_name + "'s" + " " + "Sick leave and we have forwarded it to you for " "final " "authorization\n" + "Please login to … -
Django inspectdb unable to inspect table - relation doesn't exist error
So, what I'm trying to achieve is to map the tables I have in my postgres database to django models. I've tried using inspectdb, but it keeps throwing errors and I'm out of ideas on how to fix it. Here is the code I ran: python3 manage.py inspectdb account And the output it gives me is: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'account' # The error was: relation "account" does not exist LINE 1: SELECT * FROM "account" LIMIT 1 What I think is going on here is that for some reason the inspectdb is wrapping the table name with double quote which is incorrect to psql syntax and this is … -
How to customize Django modle's field.value_to_string(self) for datetime field
Let's say I have a model class Job(Model): created_on = DateTimeField(_("Created On"), auto_now=True, editable=False) name = CharField(_("Name"), max_length=300, blank=False) Now I am trying to aggregate all fields with their verbose name and value to display it in a template. My aggregating function: def get_fields(self): result = [] for field in Job._meta.fields: result.append((field.name, field.verbose_name, field.value_to_string(self))) This gives me the values as string properly, however for a datetime field, I end up with a dumb unformatted string like 2021-02-13T22:39:47.561045+00:00 I really don't want to check and modify the value in some way by specifically checking for the particular field as that is the whole point of my get_field function I feel any of the following should work fine for me: Somehow provide the default format to use when calling value_to_string() Get a proper dateTime object instead, in which case the value should show up fine on the template Get field type and then instead of calling value_to_string() I manually convert the string to this type (This seems feasible from what I see but feels too hacky of a solution) -
What will happen if a Django request gets to long?
I am tryying to figure out a microservices architecture for my Django Restfull webapp.This Engineering app will envolve with heavy mechanical and geometrical calculations in some places. Due to the Django's slow (actually python's) calculation nature I will make main app with Django(becaue of its killer nice features) and also I want to design microservices as side functions on C# asp.net(due to its calculation power).This will allow me through heavy calculations on it so i can keep Django main app just like a bridge. So my questions; When Django main app sends a request to microservice What will happen if a calculation gets too long on micromicroservice? Lets say 10sec. , will my whole app be frozen along the 10sec.? I want to use async fuctions on ASP.NET, will it negativelly effect the sync Django main app? -
In Django, only the first form is evaluated in writing order. Why?
I have created some forms using the Django form model class But the strange problem I have is that the first form is always evaluated in writing order, even when another form is sent, that form is called I searched a lot but did not find a solution Form values are sent to the server in Ajax It works properly when I do not create the form from the Django model form class and write a normal HTML form without using the class views.py Ajax Code forms.py Html Models The form_default_user form is always validated even when it has not been submitted and another form is sending values enter image description hereenter image description here -
Select2MultipleWidget in formset
I'm trying to get a formset with Select2MultipleWidget widgets but am not successful. Using Django 2.2 LTS. class MealUpdateForm(forms.ModelForm): class Meta: model = Meal fields = ('noon', 'noon_options', 'evening', 'comments', ) widgets = { 'noon_options': Select2MultipleWidget, } When I render the above through a test form for a single item, everything is working fine: I get a Select2MultipleWidget for the noon_options field. Whenever I add the form to a modelformset_factory though, I'm getting Django's default SelectMultiple widget, which is not what I want. MealFormSet = modelformset_factory(Meal, extra=0, fields=('noon', 'noon_options', 'evening', 'comments', ), form=MealUpdateForm, ) I'm rendering the formset in my template pretty straightforward as: {% for form in formset.forms %} <tr> <td> {{ form.id }} </td> <td> {{ form.noon }} </td> <td> {{ form.noon_options }} </td> <td> {{ form.evening }} </td> <td> {{ form.comments }} </td> </tr> {% endfor %} Any idea what I'm doing wrong? I tried adding widgets={'noon_options': Select2MultipleWidget} to the modelformset_factory definition, this doesn't help. -
django.db.utils.ProgrammingError: (1146, "Table '' doesn't exist")
I'm trying to migrate my db from the local sqllite to a mysql one in aws, following the commands: 1)python manage.py dumpdata > db.json 2)Change the database settings to new database such as of MySQL / PostgreSQL. 3)python manage.py migrate 4)python manage.py shell Enter the following in the shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() 5)python manage.py loaddata db.json _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'mydb.mytable' doesn't exist") The above exception was the direct cause of the following exception: ... django.db.utils.ProgrammingError: (1146, "Table 'mydb.mytable' doesn't exist")