Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i start learning django
How can i start learning django.Can anyone tell me some good books or videos to watch.I have created virtualenv and created a normal project using django-admin startproject djangopro but i cant understand anything about it -
How do I get coordinates programatically from Google Maps url sharing current location?
If I share my current location to a web server how can I get my coordinates from the shortened url? This feature is available in the Google Maps mobile app in which users can choose to share a url of their live location to friends via sms. For example, if my current url sharing location is https://maps.app.goo.gl/random sequence of letters how can I get my location? I've set up a Django web server that communicates with a Twilio client. When I text the Twilio number with the url of my live location I want it to return my coordinates. Any help is appreciated! -
Give user access only to one field - Django
I am building an API using Django Rest Framework for my car-sharing app. I want to let not owner users to have access to update "participants" field in race, so they can join. Other fields should be available only to owner. I was reading about django-guardian, but i don't realy understand how to implement it. Here's my model: from django.db import models from django.contrib.auth.models import User class Race(models.Model): owner = models.ForeignKey("auth.User", related_name = 'races', on_delete=models.CASCADE) origin_long = models.DecimalField(max_digits=8, decimal_places=3) origin_lat = models.DecimalField(max_digits=8, decimal_places=3) destination_long = models.DecimalField(max_digits=8, decimal_places=3) destination_lat = models.DecimalField(max_digits=8, decimal_places=3) start_time = models.TimeField(auto_now=False, auto_now_add=False) participants = models.ManyToManyField(User,blank=True) schedule = models.DurationField(blank=True,null=True) subs = models.ManyToManyField(User, related_name='subs',blank=True) cost = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.user.get_full_name() Thank you in advance. -
Call discord bot function from django
I have hard problem to solve. I run website in django. I would like to allow website to call some discord bot functions. For example when user will go to index page bot will send "Hello word" on discord. It's simplified version of this what I want to do. Is there any way to call bot function from views.py or to put discord bot code directly into views.py? -
Django 2.1 static files loading in production but not development
Usually I have this issue exactly the other way around! In my development environment my Django app will not load some of my static files, specifically ones that I have added myself: that is, the two packages I've added to my app (admin and ckeditor) are both loading up fine, but two of the folders I've created and linked myself (img and css) are not being found. Here's a map of my directory: root |-- blog (this is the name of my app) |-- mysite (name of my site) |-- media |-- static |-- admin |-- ckeditor |-- css |-- img As stated, ckeditor and admin load fine while the others do not. Here's an example from the runserver output in debug mode (the file at static/css/base.css exists in my file tree): GET /static/ckeditor/ckeditor/ckeditor.js HTTP/1.1" 200 690627 GET /static/admin/css/fonts.css HTTP/1.1" 200 423 GET /static/admin/css/widgets.css HTTP/1.1" 200 10340 GET /static/css/base.css HTTP/1.1" 404 1761 GET /static/img/brand.png HTTP/1.1" 404 1764 Here's some other information which may be of interest: It works fine in production! I assumed this was because I had dedicated aliases in my apache config, but that doesn't explain why admin and ckeditor work. I have routed media in much the … -
Django: how to get the latest related object
I'm working on optimization Django queries and struggling with getting the last related item. Models: class Car(models.Model): title = models.CharField(max_length=255) class CarTechnicalInspection(models.Model): car = models.ForeignKey(Car) date_to = models.DateField() class Meta: ordering = ['date_to', ] View: cars = Car.objects.all() for car in cars: ti = car.cartechnicalinspection_set.last() #hit DB query! if ti and ti.date_to < timezone.now(): #do something How to Annotate the last Technical Inspection for each car without a DB query for each car? Thanks! P.S. prefetch_related('cartechnicalinspection_set') does not work -
my UserProfile modelform rejects using user id to update and fill the form in the updateview class:
guys, I feel stuck separating user model and userprofile model to generate two separate views and apps in general. It worked for user but not for userprofile, I used userchangeform with user and forms.modelforms with UserProfile. I am trying to use updateview, so the user can see and update his info. the codes: #user profile models file from django.db import models from easyinstall import settings ####################################################################### class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) picture = models.ImageField(upload_to='uploads/profile_images', blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) website = models.URLField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'users profiles' def __str__(self): return self.user.username #userprofile forms from django import forms from .models import UserProfile ################################################################### class EditProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('picture', 'bio', 'location', 'birth_date', 'website',) #userprofile views from .models import UserProfile from django.views.generic import UpdateView from django.urls import reverse_lazy from .forms import EditProfileForm ############################################ class ProfileUpdateView(UpdateView): model = UserProfile form_class = EditProfileForm template_name = 'profiles/profileupdate.html' success_urls = reverse_lazy('profiles') pk_url_kwarg = 'UserProfile_pk' context_object_name = 'UserProfile' I really stuck with that "pk" thing, how to get the pk for the user profile and use it? is it ok to have id and user_id in the … -
How To Fetch 5 Data from Api
How To fetch only 5 dats from api in react Js componentDidMount() { var self = this; houseService.getHouses() .then(function (result) { console.log(result); self.setState({ houses: result.data, nextPageURL: result.nextlink }) }); } -
Delay on ubuntu with Nginx and uwsgi
Im using django framework and im serving my project on Ubuntu server using nginx & uwsgi . The problem is when im trying connect to API or website after a while , it takes some times (10 to 15 seconds ) to give me the response . after first response it will be fast until requests are gone . it seems os puts nginx or uwsgi to sleep And waiting for new request to fire it up . Anyone can help to prevent nginx from sleep ? nginx conf : user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## … -
Set password using user end point
I am new to python and is trying to set/update password for the created user. What I am trying to achieve is: Set Password for the created user Update password for the created user i don't want my password field to be available while creating user or viewing use details. The code is as below. serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'id', 'username', 'email', 'first_name', 'last_name') class PasswordSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = 'password' and views.py is from urllib import request from rest_framework import viewsets, status from django.contrib.auth.models import User from atest.serializers import UserSerializer,PasswordSerializer from rest_framework import permissions from atest.permissions import IsOwnerOrReadOnly from rest_framework.decorators import action from rest_framework.response import Response class UserViewSet(viewsets.ModelViewSet): """ This viewset provides operations on Users table to the same user. """ # permission_classes = (permissions.IsAuthenticatedOrReadOnly, # IsOwnerOrReadOnly,) queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post', 'put']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.data['password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Please help me how to achieve what I want. -
Django TypeError objects is not iterable
I tried to show a model data in html template in django. My Model: class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(blank=True, null=True) date_of_death = models.DateField(blank=True, null=True) def get_absolute_url(self): return reverse('author_detail', args=[str(self.id)]) class Meta(): ordering = ['first_name', 'last_name'] def __str__(self): return f'{self.first_name} {self.last_name}' My View: def author_detail_view(request, pk): author = get_object_or_404(Author, pk=pk) return render(request, 'author_detail.html', context={'author_detail': author}) My URL: path('author/<int:pk>', views.author_detail_view, name='author_detail') And My Templates View: {% extends 'base.html' %} {% block content %} <h1>Author Detail</h1> {% for author in author_detail %} <ul> <li>Name: {{ author.first_name }} {{ author.last_name }}</li> <li>Date of Birth: {{ author.date_of_birth }}</li> </ul> {% endfor %} {% endblock %} But the probelem is, it shoing error that : TypeError at /author/2 'Author' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/author/2 Django Version: 2.1.5 Exception Type: TypeError Exception Value: 'Author' object is not iterable Exception Location: /home/pyking/.local/lib/python3.6/site-packages/django/template/defaulttags.py in render, line 165 Python Executable: /usr/bin/python3 Python Version: 3.6.7 -
unread notification in django-private-chat
I have used django-private-chat for implementing one to one chat in my django project,But the problem is,it doesn't show unread message notification to user who as unread messages. I can't seem to find a way to implement this functionality.Can anyone please help me out with this.Thanks in advance -
Django signals with ForeignKey Fields
I have created a knowledge structure that has "blocks"and each block has children to cater for different situations. The code is: models.py class KBSBlock(models.Model): name = models.CharField(max_length=150, unique=True) code = models.CharField(max_length=4, blank=True) status=models.CharField(max_length=1, choices=Status_Choices, default='Draft') enter_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT) tags = TaggableManager(blank=True) attribute1 = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def save(self, *args, **kwargs): if self.code is None or self.code == "": self.code = create_code4(self) super(KBSBlock, self).save(*args, **kwargs) @receiver(post_save, sender=KBSBlock) def create_block(sender, instance, created, **kwargs): if created: #create_block = BlockDetails.objects.create(block_dts=instance) print('Working!') class BlockDetails(models.Model): block_dts = models.ForeignKey('KBSBlock', on_delete=models.CASCADE) code = models.CharField(max_length=2, blank=True) attribute1 = models.CharField(max_length=100, default='All') created_at = models.DateTimeField(auto_now_add=True) enter_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT) status=models.CharField(max_length=1, choices=Status_Choices, default='Draft') Whenever I create a block, I want to create a generic detail in BlockDetails for the block with (code='00', attribute1='All', enter_by='request.user') It prints the 'working' bit with the 'create_block' line hashed out. I am using PostgreSQL, Django 2.1 and Python 3.7, and cannot get it right. Help Please -
Previewing unpublished drafts in Wagtail when frontend relies on headless wagtail API
Suppose I have the following setup: A backend CMS in Wagtail which uses the Wagtail API to expose the data A frontend that takes aforementioned API and using React, generates HTML & JS This would break Wagtail's preview as it uses the templates by default. Unfortunately, the preview functionality is important to this particular project, so I need to find a mechanism to keep it. So far I managed to create a template that outputs a custom-serialized JSON which is read by a specially built front-end. Unfortunately, this solution is far from ideal as maintaining two serializers - rest_framework and Wagtail's endpoints (with api_fields on the models themselves). I have not been able to generate JSON from Wagtail's BaseEndpoint (using .as_view or otherwise), but that could be a possible solution. I've also considered generating an endpoint that serves temporary serialized JSONs for specific pages under unique timed GUIDs. This will technically expose unpublished drafts to the public if anyone gets that (temporary) link somehow, but that is a risk we might be able to take if there was a good way to do it. How do I approach this problem? Have you solved it for your own project somehow? -
Can django project and django app have different docker image?
If I have 1 Django project and multiple Django apps. every Django app has its own requirements.txt and settings. hence every apps have its own docker image. my doubt is can I execute code from one django app to other Django app while both apps have a different container? -
django-filter button filtering
With django-filter package I've created filter that allow me or users to filter company by type, city, technologies by selecting options and submit form. But the select view looks so ugly and I'm trying to make this filter by buttons, like All Cities | City_1 | City_2 All types | Type_1 | Type2 All technologies | Python | Javascript etc. So I've created filter and it actually works with {{ filter.form.as }} but when I'm trying to create buttons with {% for city in filter.form.city %} for example, I'm getting buttons with bugged values, and If I click button with any City I'm getting no results, and the URL is changing to search?city= Im new to django (4 days) and I've been trying since morning to make it work, googled everything but couldn't find solution To better understand, just check the images (selecting filters by form works fine, just buttons dont works) https://imgur.com/a/ZXUUiap I don't really know what's wrong because it should work fine but it doesnt My code is here #models.py from django.db import models # Create your models here. from django.db import models from django.utils import timezone from django.core.validators import MinValueValidator from multiselectfield import MultiSelectField import django_filters TYPES … -
Django fields.E300 Field defines a relation with model 'Construct', which is either not installed, or is abstract
I'm creating an app called swetheory and ran into this problem: swetheory.Cause.cause_name: (fields.E300) Field defines a relation with model 'Construct', which is either not installed, or is abstract. swetheory.Cause.cause_name: (fields.E307) The field swetheory.Cause.cause_name was declared with a lazy reference to 'swetheory.construct', but app 'swetheory' doesn't provide model 'construct'. swetheory.Effect.effect_name: (fields.E300) Field defines a relation with model 'Construct', which is either not installed, or is abstract. swetheory.Effect.effect_name: (fields.E307) The field swetheory.Effect.effect_name was declared with a lazy reference to 'swetheory.construct', but app 'swetheory' doesn't provide model 'construct'. The code: # Defining our proposition model from django.db import models from django.urls import reverse class AreaOfInterest(models.Model): area_name = models.TextField(max_length=40, help_text='Enter area of study') def __str__(self): return self.area_name @property def get_absolute_url(self): return reverse('area-of-interest', args=[str(self.id)]) class Value(models.Model): value_name = models.TextField() def __str__(self): return self.value_name class Construct(models.Model): construct_name = models.TextField() construct_area = models.ForeignKey(AreaOfInterest, on_delete=models.CASCADE) construct_values = models.ManyToManyField(Value) class Meta: abstract = True def __str__(self): return self.construct_name class Cause(models.Model): cause_name = models.ForeignKey(Construct, on_delete=models.CASCADE, related_name="causeconstruct",default='') reference_cause_value = models.ForeignKey(Value, on_delete=models.CASCADE, related_name="referencevalue",default='') observed_cause_value = models.ForeignKey(Value, on_delete=models.CASCADE, related_name="observedvalue",default='') def __str__(self): return self.cause_name.construct_name class Effect(models.Model): effect_name = models.ForeignKey(Construct, on_delete=models.CASCADE) observed_effect_value = models.ForeignKey(Value, on_delete=models.CASCADE) def __str__(self): return self.effect_name.construct_name class Proposition(models.Model): proposition_area = models.ForeignKey(AreaOfInterest, on_delete=models.CASCADE) proposition_cause = models.ManyToManyField(Cause) proposition_effect = models.ManyToManyField(Effect) class EvidenceEffect(models.Model): evidence_name = … -
How to implement Where Exists in Django?
I have two models in Django, one for Songs, one for Albums, an Album has many Songs. I am trying to filter Albums where Songs are valid. For example, at least one Song has to have an audio file in order for the Album to be returned by the filter. I am using Postgres. I am trying to figure out how to do this logic via a Django QuerySet but i am not certain how to use where exists instead of exists. The following is the Django orm statement i am trying to get to work: valid_songs = Song.objects.filter( album=OuterRef('pk'), audio_file__isnull=False).only("album") Album.objects.annotate(valid_song=Exists(valid_songs)) This is the query that is generated: SELECT "api_album"."id", "api_album"."created_at", "api_album"."updated_at", "api_album"."title", "api_album"."artwork_file_id", "api_album"."user_id", "api_album"."description", "api_album"."tags", "api_album"."genres", EXISTS(SELECT U0."id", U0."album_id" FROM "api_song" U0 WHERE ( U0."album_id" = ( "api_album"."id" ) AND U0."audio_file_id" IS NOT NULL )) AS "valid_song" FROM "api_album" This is the postgres query plan for the above query generated by Django's QuerySet: Seq Scan on api_album (cost=0.00..195.70 rows=120 width=641) SubPlan 1 -> Seq Scan on api_song u0 (cost=0.00..1.54 rows=1 width=0) Filter: ((audio_file_id IS NOT NULL) AND (album_id = api_album.id)) SubPlan 2 -> Seq Scan on api_song u0_1 (cost=0.00..1.43 rows=10 width=4) Filter: (audio_file_id IS NOT NULL) However, … -
Connected detailView with templates
I've have a simply problem with DetailView. I tried to connect to show only paired value(like question -> choice) but i doesn't work. I create a detail view, and try to change urls but or a have a error or empty site. (problem with adding code so link) Github -
Ubuntu nginx and uwsgi delay
Im using django framework and im serving my project on Ubuntu server using nginx & uwsgi . The problem is when im trying connect to API or website after a while , it takes some times (10 to 15 seconds ) to give me the response . after first response it will be fast until requests are gone . it seems os puts nginx or uwsgi to sleep And waiting for new request to fire it up . Anyone can help to prevent nginx from sleep ? -
how to split post view on the same page in django
I have no idea if this question make much sense or not but i am so confused about it. I have a post list view and it is rendering some of the post here. My question is how can I split the sections of the page.something like this. what should be the approach of making this kind of view. -
Django DeleteView __str__ returned non-string (type model name)
I'm trying to implement DeleteView. However, I get the following TypeError : __str__ returned non-string (type Fund) How can I solve this? many thanks to all in advance, Code : views.py : class CashFlowDelete(DeleteView): model = CashFlow success_url = reverse_lazy('fds:fds') urls.py: path('deletecashflow/<int:pk>/', views.CashFlowDelete.as_view(),name = "delete_cashflow"), funds_detail.html <a href="{% url 'fds:delete_cashflow' pk=cashflow.pk %}">Delete</a> cashflow_confirm_delete.html <form method="post"> {% csrf_token %} <p>Are you sure you want to delete "{{ object }}"?</p> <input type="submit" value="Confirm"> </form> -
When does Celery task time start being counted?
Currently in production with my django app, I am having issues with Celery, where a task sometime takes 1-2 seconds, but sometimes takes 15-25 seconds. My app is a chatbot related app so it needs to proccess a lot of data. So I was a bit confused, the task time being logged in logger is the amount of time it takes the task to execute after it is received by the worker or does it also take in account the time the task was waiting in the Queue? -
Foreign Key Mismatch Error with django csv import-export
I'm trying to import three datasets with csv import-export package for three models: service, library and price. I am getting this error when I try to upload a dataset for the service model. The library model loads, but the price model also does not load. Line number: 1 - foreign key mismatch - "catalog_price" referencing "catalog_service" models.py There are three models: service, library, and price. class Service(models.Model): serviceid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular service in database') desc_us = models.TextField(blank=True, primary_key = True) cpt = models.IntegerField(default= 10000) price = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) class Library(models.Model): hid = models.CharField(max_length = 8, null=True) name = models.CharField(max_length=200, primary_key=True) hopid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular library in database') address = models.CharField(max_length = 200, null = True) city = models.CharField(max_length = 50, null = True) state = models.CharField(max_length = 2, null=True) zipcode = models.CharField(max_length = 5, null=True) phone = models.CharField(max_length = 12, null=True) updateDate = models.DateField(blank=True, null=True) class Price(models.Model): priceid = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular service in database') com_desc = models.CharField(max_length = 200, blank = True, null = True) service = models.ForeignKey("Service", on_delete=models.SET_NULL, null=True) price_offer = models.DecimalField(max_digits=8, decimal_places=2, blank=True) comments = models.CharField(max_length = 200, blank = True, null =True) … -
Model methods won't show in admin; solution in docs doesn't seem to work
I have a basic model in my models.py file class DiceImage(models.Model): original_image = models.TextField (validators=[URLValidator()]) new_image = models.TextField (validators=[URLValidator()]) image_width = models.IntegerField() # in dice image_height = models.IntegerField() # in dice number_of_dice = models.IntegerField() def _get_construction_cost(self): # return an approximate charge for time for construction # based on number of dice and 10 seconds per dice rate_per_hour = 20 # in £ construction_time_seconds = self.number_of_dice * 10 construction_time_hours = construction_time_seconds / 60 / 60 construction_cost = rate_per_hour * construction_time_hours return construction_cost def __str__(self): return os.path.basename(self.new_image) The model works and shows up in the admin section but without the construction cost. I therefore looked at the docs (https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#modeladmin-methods) and found out about list_display So I went to admin.py and entered the following code: from django.contrib import admin from .models import DiceImage admin.site.register(DiceImage) class DiceImageAdmin(admin.ModelAdmin): list_display = ('original_image', 'new_image', 'image_width', 'image_height', 'number_of_dice', 'construction_cost') admin.site.register(DiceImageAdmin) But my server logs show an error. 2019-03-03 15:43:45,675: Error running WSGI application 2019-03-03 15:43:45,682: TypeError: 'MediaDefiningClass' object is not iterable 2019-03-03 15:43:45,682: File "/var/www/mutatedllama_pythonanywhere_com_wsgi.py", line 12, in <module> 2019-03-03 15:43:45,682: application = StaticFilesHandler(get_wsgi_application()) 2019-03-03 15:43:45,683: 2019-03-03 15:43:45,683: File "/home/mutatedllama/.virtualenvs/django2/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-03-03 15:43:45,683: django.setup(set_prefix=False) 2019-03-03 15:43:45,683: 2019-03-03 15:43:45,683: File "/home/mutatedllama/.virtualenvs/django2/lib/python3.6/site-packages/django/__init__.py", line 24, in setup 2019-03-03 …