Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change django template and app folder?
I'm working on a project and my project structure looks like this. - project name - apps - app1 - app2 - templates - app1 - app2 To make django find app i have changed my project base directory path as import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) APPS_DIR = os.path.join("apps") sys.path.append(APPS_DIR) I want to change my template setting so that django could easily find the template directory. currently my template directory looks like this TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': False, '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', ], }, }, ] -
Django Object filter buy foreign key value reference
I want to filter models object of Django by using foreign key references. Here is my models class Category(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.CharField(max_length=255, unique=True) icon = models.CharField(max_length=255, blank=True, null=True) class Article(models.Model): title = models.CharField(max_length=255) slug = models.CharField(max_length=255, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) My Query: Article.objects.filter(category__name=value) Article.objects.filter(category__slug=value) I want to get all Article that category name that specify. But Error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: report_article_category -
Timezone issue in admin
I have set up a timezone aware django app. Now I have the issue that somehow the times are mixed up. In my form where I show and input the time everything is fine: class WeekView(FormView): template_name = "week.html" form_class = EntryForm def form_valid(self, form): ei = Entry() ei.start =(datetime.datetime.fromtimestamp(float(form.cleaned_data['start_div'])/1000)) Note that in the last line localizing is not necessary (and indeed does not have an effect) as the cleaned data does that already. For the rendering I use a model method that I call in the template: def get_time(self): return self.start.strftime("%Y-%m-%d %H:%M:%S") So those two work fine together: if I enter a time and save the form it redirects to the form again and shows the entered time. However, if I look into the record in the admin, the time is off. It seems to show me the timezone corrected time, where the other values seem to be UTC (or the server time). Settings should be correct: TIME_ZONE = 'Europe/Vienna' USE_TZ = True Where is my mistake? As my main motivation to use timezone aware times is the daylight save time issue, I do not want to jerry-rig a solution by subtracting the hours. -
django.db.utils.IntegrityError: in POST request
I am creating a post function to save data in a model, Here's the code: Views.py class take_quizapi(CreateAPIView): def post(self, request,pk, *args, **kwargs): supplier = request.user.supplier data = request.data.copy() data["supplier_id"] = supplier.user_id data["score"] = 0 data["quiz"] = pk print("data is", data) serializer = takenquizSerializer(data=data) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when I call the API from postman it says: django.db.utils.IntegrityError: null value in column "supplier_id" violates not-null constraint But I am clearly providing the data["supplier_id"] = supplier.user_id. What is it that I am doing wrong here ? Serializers.py class takenquizSerializer(serializers.ModelSerializer): supplier = ReadOnlyField(source='supplier.supplier_fname') class Meta: model = TakenQuiz fields = "__all__" Models.py class TakenQuiz(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='taken_quizzes') quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes') score = models.FloatField() date = models.DateTimeField(auto_now_add=True) least_bid = models.IntegerField(default=0) confirmed = models.CharField(max_length=100, default='Not Confirmed') -
Dajgo-oscar : deleting a voucher don't delete the associated "ConditionalOffer"
I'm facing a problem with Django-Oscar wile trying to play with offers and vouchers. When I delete a voucher the related entity ConditionalOffer is not deleted and remain in database. So when I try to add another voucher with the same code as the one I just deleted I get a beautiful IntegrityError duplicate key value violates unique constraint "offer_conditionaloffer_name_key" I'm using django-oscar (2.0.1) with PostgreSQL (11) and psycopg2 (2.8.3). Here a screenshot of the error and another of the ConditionalOffer table with entries (10off and 20off) remaining there. Is that a normal behaviour or it's a bug ? If it's normal how can I do to create a voucher with the same code as an old one already deleted ? -
Creating model with known foreign key
I have two models. Asset and Audit. Each asset can have multiple audits. When you "create" an audit you create it for a known existing asset. How can I pre-populate the asset foreign key when creating the audit in the admin view. In the command line I can create an asset, save it's id and then create the audit while passing the asset id to it. However, I'm not sure how to do that with forms and views in the admin. Currently what I'm doing is to pass a "GET" variable listing the asset ID into the add_view function and then adding the asset into extra_content. However, this doesn't seem very Django. class Asset(models.Model): name = models.CharField(max_length=200) serial_number = models.CharField(max_length=100, unique=True) class Audit(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) next_audit_date = models.DateField(default=get_audit_date) In change_form for the audit view I have a hidden field listing the asset id to use and in the save function I use this to populate the foreign key in audit, but this doesn't seem very Django-like. -
linux host raise sqlite3 error on running django project
I have a linux host and i want to run a django project on it with SSh. but when i run: python manage.py runserver it raise this error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/opt/alt/python37/lib64/python3.7/threading.py", line 917, in _bootstrap_inner self.run() . . . raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). should i do somethig special in cpanel?? -
Using minio server for multiple seperate django apps
What is the best way to use Minio for Multiple seperate Django apps I'm just beginning to learn Minio. I am hoping to use just one minio server and have seperate buckets for each app's media files (uploaded images/videos by app users). Am I able to set an app's setting files to an individual bucket without the need to supply the full access/secret key - that is, I don't want an app to be able to access the full minio server listings, only its specific bucket. I know I can set up user/group policies but how do I add that to a django app settings without supplying access/secret key. Or perhaps my whole understanding of how I should be using minio is wrong? -
what's the problem with django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field category to an Elasticsearch field
I'm making my models work with elastic search and i added simple code in documents.py in my app directory but "$ ./manage.py search_index --rebuild" giving me "django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field category to an Elasticsearch field!" models.py from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=30) slug = models.SlugField( default="cslug") picture = models.FileField(upload_to="static/product_pics/") parent = models.ForeignKey('self', blank=True,null=True,on_delete=models.CASCADE, related_name='children') class Meta : ordering = ('name', ) unique_together = ('slug', 'parent',) verbose_name_plural = 'Categories' def get_absolute_url(self): return reverse('store:productlist', args=[]) def __str__(self): full_path = [self.name] k=self.parent while k is not None: full_path.append(k.name) k=k.parent return '->'.join(full_path[::-1]) documents.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Category, Brand, Product @registry.register_document class CategoryDocument(Document): class Index: name = 'categories' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Category fields = [ 'name', ] -
Django pagination on model with foreign key
Post and comment models class Post(models.Model): title = models.CharField(max_length=120) content = models.TextField() class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() Class view of post detail class PostDetailView(DetailView): model = Post context_object_name = 'post' template_name = 'posts/detail.html' def get_queryset(self, *args, **kwargs): request = self.request pk = self.kwargs.get('pk') queryset = Post.objects.filter(pk=pk) return queryset In the template I do something like this {% for comment in post.comment_set.all %} {% comment.content %} {% endfor %} In this approach, all the comments are shown in the post detail page. However, I want to paginate the comments of a post so that I can do pagination on comments and not show the whole list of comments. How can I do this? -
How can I change this code : I don't want to use raw SQL but I don't know how can I do
I don't want to use SQL raw. but I don't know how can I change this code. Looking at the various materials, I tried to find a way not to use SQL raw, but failed. I'm not sure how to change this. def listSpecificPageWork(request): current_page = request.GET['current_page'] totalCnt = DjangoBoard.objects.all().count() print 'current_page=', current_page boardList = DjangoBoard.objects.raw('SELECT Z.* FROM(SELECT X.*, round((rownum / %s)+0.5) as page FROM(SELECT ID,SUBJECT,NAME, CREATED_DATE, MAIL,MEMO,HITS FROM BOARD_DJANGOBOARD ORDER BY ID DESC)X)Z WHERE page = %s', [rowsPerPage, current_page]) print 'boardList=',boardList, 'count()=', totalCnt pagingHelperIns = pagingHelper(); totalPageList = pagingHelperIns.getTotalPageList( totalCnt, rowsPerPage) print 'totalPageList', totalPageList return render_to_response('listSpecificPage.html', {'boardList': boardList, 'totalCnt': totalCnt, 'current_page':int(current_page), 'totalPageList':totalPageList} ) # -*- coding: utf-8 -*- class pagingHelper: "paging helper class" def getTotalPageList(self, total_cnt, rowsPerPage): if((total_cnt % rowsPerPage) == 0): self.total_pages = total_cnt/rowsPerPage; print 'getTotalPage #1' else: self.total_pages = (total_cnt/rowsPerPage) + 1; print 'getTotalPage #2' self.totalPageList = [] for j in range(self.total_pages): self.totalPageList.append(j+1) return self.totalPageList def __init__(self): self.total_pages = 0 self.totalPageList = 0 error : no such column : rownum I want to change boardList. -
how to setup accounts for django classified
I was able to install the django classified on my new django project as advised in the github documentation. The main page shows up and the search page as well. I'm trying to add classifications, sections and areas to the application but I think this can only be done by the admin user. When I try to login using the superuser I created, it says it's not able to see the admin page. Also when I try to access the admin app, it does not see it as well. It redirects to this URL, but it says it cannot be found: http://127.0.0.1:8000/accounts/login/?next=/user/profile/ do I need to set this page up in my main project? I also tried using the django classified demo app but it made things a bit more confusing since there are a lot more things in the codes that I am not familiar with. -
How can I choose the field of a ForeignKey that is displayed on a ModelForm?
I have the following models: class DirectoryDoctors (models.Model): num = models.AutoField(primary_key=True) name = models.CharField(max_length=100) designation = models.CharField( choices=design_choices, max_length=30, default='unspecified') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='', blank=True) email = models.CharField(max_length=50, default='', blank=True) dob = models.DateField(null=True, blank=True) specialty = models.ForeignKey(SpecialtyChoices, on_delete=models.DO_NOTHING,null=True) institution = models.ForeignKey(DirectoryHospital, on_delete=models.DO_NOTHING) def __str__(self): st = f"{self.name}" return st class DhanwantriComplaint(models.Model): num = models.AutoField(primary_key=True) sender = models.ForeignKey(DirectoryDoctors, blank=False, null=False, on_delete=models.PROTECT) location = models.ForeignKey(DirectoryHospital, blank=False, null=False, on_delete=models.PROTECT) complainttype = models.ForeignKey(DhanwantriComplaintCode, blank=False, null=False, on_delete=models.PROTECT) details = models.CharField(max_length=10000) since = models.CharField(max_length=100, blank=True, null=True) alertDNO = models.BooleanField(default=True) alertZNO = models.BooleanField(default=True) alertSNO = models.BooleanField(default=True) ITMinformed = models.BooleanField(default=False) ITMvisited = models.BooleanField(default=False) prevticketid = models.CharField(max_length=100, blank=True, null=True) raisedon = models.DateTimeField(default=timezone.now) lastupdate = models.DateTimeField(default=timezone.now) closed = models.BooleanField(default=False) closedon = models.DateTimeField(blank=True, null=True) I have the Modelform: class DhanwantriComplaintForm(ModelForm): class Meta: model = DhanwantriComplaint fields = [ 'sender', 'location', 'complainttype', 'details', 'since', 'alertDNO', 'alertZNO', 'alertSNO', 'ITMinformed', 'ITMvisited', 'prevticketid', ] widgets = { 'details': forms.Textarea(attrs={ 'rows': 10, 'cols': 15 }), 'sender': forms.TextInput(), } And the view: @login_required def complaint_dhanwantri_new(request): items = LinkSection.objects.all() docuser = DoctorUser(request) print(f'docuser is {docuser}. type is {type(docuser)}') form = DhanwantriComplaintForm( initial={ 'sender': docuser, 'location': docuser.institution, } ) if request.method == 'POST': print(f'Received POST: {request.POST.get}') form = DhanwantriComplaintForm(request.POST) if form.is_valid(): print("Form is valid") else: … -
Why is Geodjango returning the wrong distance between two points?
I am using geodjango with postgressql as a spatial database.I have a list of points in a queryset and I am using a for loop to return the distance between the user location and each point.However the distance returned by geodjango and the distance returned by google vary widely. Why is geodjango returning the wrong distance between two points? def feed(request): latitude = request.session['lat'] longitude = request.session['lng'] location = request.session['location'] lat = float(latitude) # Central point latitude lng = float(longitude) # Central point longitude radius = 10 point = Point(lng, lat) queryset2=Store_detail.objects.filter(store_location_point__distance_lt=(point, Distance(km=radius))) for query in queryset2: print(point.distance(query.store_location_point)*100) return render(request, 'main/feed.html', {'queryset': queryset, 'location':location,}) This is the line of code responsible for returning the distance between the users location and each query in the queryset: for query in queryset2: print(point.distance(query.store_location_point)*100) where point is the user location stored as a point field and query.store_location_point is the point field for every query in the queryset -
i am getting error when starting my server
File "C:\Users\Owner\AppData\Local\Programs\Python\Python36\lib\importlib__ini return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 674, in exec_module File "", line 781, in get_code File "", line 741, in source_to_code File "", line 219, in _call_with_frames_removed File "C:\Users\Owner\Desktop\Django\ScrumMaster\ScrumMaster\urls.py", line 21 path('scrum/' include('Scrum.url')), I keep getting this error. I don't understand what i have done wrong. please can you help. Thanks -
MX records and inbound emails with Django
I think I have some confusion of what happens with emails... I have a domain domain.com and I send email from sendgrid using django with address noreply@domain.com. Now, I also want to send mail to some users with the same domain.com email address that is simply aliased through a provider such as gmail. However, my understanding is once you setup the CNAME records etc this is actually incoming mail to the server which I don't want. What don't I understand here? I simply want to be able to trigger Django code hosted ondomain.com to send mail from noreply@domain.com to alias' of type XXX@domain.com -
How can I change this code? : error rownum
I need to use rownum on my website, but it didn't work well. Many people said change rownum to limit. However, limit needs seems to be to use numbers, like 'limit < 5'. So I didn't find solution. boardList = DjangoBoard.objects.raw('SELECT Z.* FROM(SELECT X.*, round( rownum / %s + 0.5) as page FROM ( SELECT ID,SUBJECT,NAME, CREATED_DATE, MAIL,MEMO,HITS FROM BOARD_DJANGOBOARD ORDER BY ID DESC ) X ) Z WHERE page = %s', [rowsPerPage, current_page]) error : no such column: rownum -
django allauth email subject for verification showing example.com
I'm using django-allauth, and I have ACCOUNT_EMAIL_VERIFICATION = 'mandatory' The issue is that when I receive the confirmation email, the subject is [example.com] Please Confirm Your E-mail Address I have set a site domain name and display name in http://<mysite>/admin/sites/site/ I've added a email_confirmation_message.html to my project->templates->account->email folder. Everything works fine with the template with both {{current_site.name}} and {{current_site.domain}} showing the correct info in the email body. I've also copied over email_confirmation_subject.txt and email_confirmation_signup_subject.txt but have not changed them... However I've noticed that if I DO make a simple change to the text inside email_confirmation_subject.txt, (for example simply adding a "!") the subject line will display the correct site url. [MySite] Please Confirm Your E-mail Address! I have not yet changed ACCOUNT_EMAIL_SUBJECT_PREFIX as the docs say "...By default, the name of the current Site (django.contrib.sites) is used..." what could be wrong? or what else should I check? -
Nginx not serving static files for django App
I am trying to deploy a Django project using nginx + gunicorn + mysql. All the configuration is done, but now my nginx is throwing 404 on any static content. setting.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Nginx conf file upstream app_server { server unix:/var/www/production/JDApps/jd/jd_gunicorn.sock fail_timeout=0; } server { listen 8000; server_name 10.1.1.2; keepalive_timeout 5; client_max_body_size 4G; access_log /var/log/nginx/jd-inventory-access.log; error_log /var/log/nginx/jd-inventory-error.log; location /static/ { alias /var/www/production/JDApps/jd/staticfiles; } location /media/ { alias /opt/; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } Gunicorn startup script #!/bin/bash NAME="jd_inventory" DJANGODIR=/var/www/production/JDApps/jd USER=nginx GROUP=nginx WORKERS=3 BIND=unix:/var/www/production/JDApps/jd/jd_gunicorn.sock DJANGO_SETTINGS_MODULE=jd.settings DJANGO_WSGI_MODULE=jd.wsgi LOGLEVEL=error LOGFILE=/tmp/jd.log echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../venv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Start your Django Unicorn exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOGLEVEL \ --log-file=$LOGFILE File Structure [root@vm-1 JDApps]# pwd /var/www/production/JDApps [root@vm-1 JDApps]# ll total 4 drwxr-xr-x. 7 nginx nginx 148 Aug 23 19:21 jd -rw-r--r--. 1 nginx nginx 455 Aug 22 19:19 requirements.txt drwxr-xr-x. 6 nginx nginx 69 … -
Django order_by for non english characters
I have a queryset of countries where some of them start with non english characters like "Þ" and "Í", when using order_by they are just shown at the end instead of being sorted properly. This is the result: >>> from someapp.models import Country >>> countries = Country.objects.all().order_by("country") >>> countries <QuerySet [<Country: Bandaríkin>, <Country: Bretland>, <Country: Danmörk>, <Country: Kanada>, <Country: Noregur>, <Country: Svíþjóð>, <Country: Ísland>, <Country: Þýskaland>]> How would I use order_by with a non english alphabet? Here is the model: class Country(models.Model): country = models.CharField(max_length=100, unique=True) def __str__(self): return "%s" % (self.country) class Meta: ordering = ['country'] -
Problems Rotate Image in Django Admin
I am using django 2.2.3 with python 3.6.6. I have a mode that uploads an image into a FileField (because there are images and pdfs). Sometimes the image is rotated and the EXIF data is not always present, so I put together a jQuery (v3.3.1) script to rotate the image in the admin change page, and send the correct rotation back to the server using an ajax call, and then I rotate the image on the file system using PIL 6.1.0. That all works, expect when I refresh the page the image displayed in the django admin is not rotated. If I check on the filesytem, the image is rotated. The jQuery script: (function($) { $(document).ready(function(){ var rotation = 0; var image_source = "" $('#uploaded_image').click(function() { $('#uploaded_image').rotate(rotation + 90); rotation += 90; if (rotation == 360) { rotation = 0; } image_source=$('#uploaded_image').attr('src') }); // Listen for clicking the a save function on the page // and then send the final roation value back to // the server to update the image. $('input[name="_save"]').click(function(){ save_rotation(rotation, image_source); }); $('input[name="_addanother"]').click(function(){ save_rotation(rotation, image_source); }); $('input[name="_continue"]').click(function(){ save_rotation(rotation, image_source); }); // ajax function to send rotation value back to the server function save_rotation(rot, src){ if (rot != … -
Import mongodb dump consistent with Django
I have a new Django App. I import json dump into mongodb using terminal like: mongoimport --db mydb --collection mycollection --file myfile.json The files are well displayed within the admin panel. But when I create a new entry into the mycollection via admin panel, Django gives it an id which already in the mongo json dump. Is there a way to tell Django to be consistent with the database and start incrementing the id from the last entry in the database collection? -
No 'Access-Control-Allow-Origin' header is present on the requested resource?
I solved some similar problems before.But for this time, I really don't know what's problem it is.I have checked all the possible that may rise the problem but still didn't solve it.And all the other api can work very well except this one. The problem is very common like this: Access to XMLHttpRequest at 'https://api.wzy-codify.com/api-app/MRI/' from origin 'https://www.wzy-codify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The frontend is written in Vue.js. The related code just like this: axios.post(this.API.mri_api,param,{headers:{'Content-Type':'multipart/form-data'}}).then((response)=>{ if(Number(response.data.status)===500){ this.$message.error(response.data.msg) } if(Number(response.data.status)===201){ this.$message.success('The upload object already exists') this.mri_data = response.data.data } else{ this.$message.success('Upload success!') this.polling() } }) The backend is supported by Django Rest Framework, and the CORS problem is fixed by using corsheaders The related settings like this: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( '*' ) ALLOWED_HOSTS = ['*'] CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', ) -
Import models.py from parent directory
Why is it so hard to import a module from a parent directory in python. I have this file "upload.py" in my app directory import os import sys from books.models import Books print(Books.objects.all()) This is my app directory format - books __init__.py models.py -uploader __init__.py upload.py So I am trying to import the model into the upload file ad it is logging ModuleNotFoundError: No module named 'books' -
Django many-to-many query dict representation
I have this query campaign_query = Campaign.objects.filter(id__in=campaign_ids).select_related('campaign_manager__name').prefetch_related('products').values( 'id', 'name', 'campaign_manager_id', 'campaign_manager__name', 'products' ) Which is supposed to return a dict representation of my Campaign obj. The problem is that 'products' is a many to many relationship and is only returning the first product, not a list of all of them. Return example: <QuerySet [{'id': 19, 'name': 'Gby id', 'campaign_manager_id': 3, 'campaign_manager__name': '', 'products': 34}]> What I want <QuerySet [{'id': 19, 'name': 'Gby id', 'campaign_manager_id': 3, 'campaign_manager__name': '', 'products': [34,35,36]}]>