Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django Channels with Docker
I'm trying to deploy django channels with Docker and Django doesn't seem to find Redis (which I'm using as a channel layer). When I do it locally, I just run redis-server and point to it from settings: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, }, } Everything works fine, web sockets are accepting connections and easily transfer my data. For production environment I use this docker config: version: "3" services: backend: container_name: backend restart: 'on-failure' image: registry.testtesttest.com/app/backend:${BACKEND_VERSION:-latest} ports: - "8000:8000" environment: DJANGO_SETTINGS_MODULE: ${DJANGO_SETTINGS_MODULE:-settings.production} DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY:-dev} redis: image: "redis:alpine" ports: -"6379:6379" And I point to redis from production settings: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('redis', 6379)], }, }, } And on production, Django says: Cannot find redis on 127.0.0.1:6379 What am I doing wrong? Do I have to add any extra services do docker-compose file? -
While using SMTP in views.py file it is showing CSRF token error.I have enalbled EMAIL_USE_TLS as true
When the user is authenticated i want to use smtp server to send the mail,But it is showing CSRF token error -
Customizing Django Admin Site
I am building an application using Django JET which is essentially a skin on the Django Admin site. I need to enable batch updates for a field in a related model. So ultimately my question is how can I do so? To illustrate, I have two models: from django.db import models class Foo(models.Model): name = models.CharField(max_length=255) class Bar(models.Model): CHOICES = ( ('A', 'BEST'), ('B', 'GOOD'), ('C', 'WORST'), ) name = models.CharField(max_length=255) quality = models.CharField(max_length=1, choices=CHOICES) foo = models.ForeignKey(Foo, on_delete=models.DO_NOTHING) I also have an admin for the parent model and an inline for the related model: from django.contrib import admin from admin_example import models class BarInline(admin.StackedInline): model = models.Bar @admin.register(models.Foo) class FooAdmin(admin.ModelAdmin): inlines = (BarInline,) I want to be able to batch update Bar.quality for all Bar instances related to the current Foo instance. My idea is to add a <select> dropdown box to the BarInline. I've looked into writing my own template for BarInline. How do I approach this problem? -
RedirectView give NoReverseMatch
Recently I've changed the paths of the blog posts to give more legible the urls. Before I've this paths: path("category/<slug:slug_category>/", views.singleCategory_postList, name="single_category"), path("<slug:slug_post>/", views.singlePost, name='single_blog_post'), Now I've this: path("<slug:slug_category>/", views.singleCategory_postList, name="single_category"), path("<slug:slug_category>/<slug:slug_post>/", views.singlePost, name='single_blog_post'), Before get_absolute_url was this: class Category(models.Model): ..... def get_absolute_url(self): return reverse("single_category", kwargs={"slug_category": self.slug_category}) class BlogPost(ModelPost, TimeManager): ..... def get_absolute_url(self): return reverse("single_blog_post", kwargs={"slug_post": self.slug_post}) Now is this: class Category(models.Model): ..... def get_absolute_url(self): return reverse("single_category", kwargs={"slug_category": self.slug_category}) class BlogPost(ModelPost, TimeManager): ..... def get_absolute_url(self): return reverse("single_blog_post", kwargs={ "slug_post": self.slug_post, "slug_category": self.category.slug_category, }) I'm trying to use the RedirectView for redirect all the old paths; then into urls.py I've this now: path("category/<slug:slug_category>/", RedirectView.as_view(pattern_name='single_category', permanent=True)), path("<slug:slug_post>/", RedirectView.as_view(pattern_name='single_blog_post', permanent=True)), path("categorie/", views.categoryList, name="list_category"), path("<slug:slug_category>/", views.singleCategory_postList, name="single_category"), path("", views.postList, name='list_post'), path("<slug:slug_category>/<slug:slug_post>/", views.singlePost, name='single_blog_post'), When I use those RedirectView it's shown me this error: NoReverseMatch at /blog/gis/ Reverse for 'single_blog_post' with keyword arguments '{'slug_post': 'gis'}' not found. 1 pattern(s) tried: ['blog\/(?P[-a-zA-Z0-9_]+)\/(?P[-a-zA-Z0-9_]+)\/$'] If I comment the two RedirectView paths the error disappear and I can use the site without problems but when I use the old paths I see 404 error. I don't have understood how RedirectView works. Someone can give me an example? -
How to compile a list of favuroites / bookmarked images in Django?
I am trying to create a page that contains a list of favourite / bookmarked images by any logged in user. Ideally, the below table in the .html will contain all the images favourite/bookmarked by the user. The browser view. The bookmark link takes you back to the image url the user has bookmarked bookmark.html file for the above page {% extends 'base.html' %} {% block head %} <title>Bookmarked Videos</title> {% endblock %} {% block content %} <table class="table table-bordered text-center"> <thead> <tr> <th>Picture Name</th> <th>Bookmark Link</th> </tr> </thead> <tbody> <tr> <td>--</td> <td>---</td> </tr> </tbody> </table> {% endblock %} I understand I need to create ManyToManyField relationships as all users are able to bookmark all pictures. However, I am not able to piece the puzzle together. Here is my models.py from django.db import models from django.contrib.auth.models import AbstractUser class Images(models.Model): picture_name = models.CharField(max_length=255) imageFile = models.FileField(upload_to="static/videos/", null=True, verbose_name="", unique=True) def __str__(self): return self.imageFile class UserProfile(models.Model): favorites = models.ManyToManyField(Images, related_name='favorited_by') class ProjectUser(AbstractUser): # add additional fields in here def __str__(self): return self.email The user should be able to bookmark this specific picture by clicking on something under the click to bookmark Video: Here is the image.html for the above page {% … -
Django SuspiciousFileOperation
I have a model that contains a FileField: class Foo(models.Model): fileobj = models.FileField(upload_to="bar/baz") I am generating a file, and saving it in /tmp/ as part of the save method. This file then needs to be set as the "fileobj" of the model instance. Currently, I'm trying this: with open( f"/tmp/{self.number}.pdf", "r" ) as h: self.fileobj = File(h) Unfortunately, this fails with: django.core.exceptions.SuspiciousFileOperation:, because the file exists outside of the django project. I've tried reading the docs, but they didn't help much. Does django take a file, and upon assigning it as a FileField, move it to the media directory, or do I need to manually put it there myself, before attaching it to the model instance. If the second case, what is the point of "upload_to"? -
Python virtual environment venv
Im trying to install this code onto my computer but I,m not sure what the .venv means. Doesnt this hide the folder you have just made? $ python3.7 -m venv .venv -
Is it possible to have Django actually upload a default file when using Google Cloud Storage?
I'm using Djangae, with Google Cloud Storage as my storage backend. I'd like to know how I can set a default ImageField value and have it actually be processed by the upload mechanism and sent to the cloud. I could manually upload the file myself using a signal if the user didn't provide an image, but it'd be nice to find a simpler solution. Environment: Djangae 0.9.11 Django 1.11.20 Python 2.7 -
LogIn if you are in the AD
I want to create a website for my company but I can't decide which is the best option for me. We use ActiveDirectory and I want to If the user is part of the AD They can log in the website their AD username and password combo. Could you give me some information which is the best choice for me Django or asp.net or something else? Thanks your time and your help. -
template_name not resolving for some views
My webapp was working fine, but after doing some ldap configurations (only changes regarding ldap in settings.py) my routing to certain pages seemed to brake. My urls.py seems to be in order but when i go to the view page i want to see it gives me another template.html file. my urls.py appname = 'app' urlpatterns = [ path('logout/', views.LogOutView.as_view(), name='logout'), path('', views.LoginView.as_view(), name='login'), path('index/search', views.SearchView.as_view(), name="search"), path('index/<slug:key>', views.EpicView.as_view(), name="detail"), **path('index/exec_report', views.ExecView.as_view(), name = "exec"), **path('index/exec_version_report', views.ExecVersionView.as_view(), name = "version"), path('index/', views.IndexView.as_view()), ] Now all the paths work well, but the 2 with ** next to them are the ones returning with the EpicView template So in my index.html is where you click on a search to bring you to index/exec_report index.html <form method="GET" action = "{% url 'app:version' %}"> <select name ="versionA" > <option value = 0>0</option> </select> <select name = "versionB"> <option value = 4.2> 4.2</option> <option value = 4> 4.0</option> </select> <input type="submit" value="Search"/> </form> Now the url routing is correct when i click on "Search" but it is giving me the wrong template, but you can see that the template_name is not resolving to the one i had given it: class ExecVersionView(LoginRequiredMixin, TemplateView): template_name= 'APP/exec.html' def … -
How can you edit two models, without a ForeignKey relationship, in the same admin?
I would like to display two unrelated models in the same Admin. A simplified version of my problem: I have a model that represents a Status Update. Every week each employee will write a quick blurb, and below the TextField in the admin I want to show a list of all their uncompleted tasks. Next to each task I would like a check box for whether they have completed their task. The models.py is below: def Employee(models.Model): name = models.CharField(max_length=50) def Task(models.Model): assignee = models.ForeignKey(Person) description = models.TextField() completed = models.BooleanField(default=False) def StatusUpdate(models.Model): employee = models.ForeignKey(Person) date = models.DateField() update_text = models.TextField() I cannot add Task as an inline model in my StatusUpdateAdmin because they are not related by a ForeignKey. Is there any way around this? The only solution I can think of is to: define a ManyToMany relationship between Task and StatusUpdate make completed a field on the through model update Task.completed every time the through model is saved (with a signal perhaps?) For instance: def StatusUpdate(models.Model): ... current_tasks = models.ManyToManyField(Task, through='StatusTasks') def StatusTasks(models.Model): status_update = models.ForeignKey(StatusUpdate) task = models.ForeinKey(Task) completed = models.BooleanField() def save(self, *args, **kwargs): self.task.update(completed=self.completed) StatusTasks.objects \ .filter(task=self.task) \ .update(completed=self.completed) return super(StatusTasks, self).save(*args, **kwargs) But … -
Django Channels Worker is returning TypeError: zadd() got an unexpected keyword argument 'daphne
In my server, i am running a Daphne and a Worker for Django Channels. I have already reboot all containers (I use Docker), cleaned Redis Cache. Today, these applications stoped to work and return this stack: KeyError: 'leads-198' 2019-03-27 13:51:59,719 - ERROR - worker - Error processing message with consumer crm.consumers.ws_connect: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels/sessions.py", line 78, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels/auth.py", line 42, in inner return func(message, *args, **kwargs) File "/opt/app/integrador/crm/consumers.py", line 10, in ws_connect Group(group).add(message.reply_channel) File "/usr/local/lib/python3.6/site-packages/channels/channel.py", line 70, in add self.channel_layer.group_add(self.name, channel) File "/usr/local/lib/python3.6/site-packages/asgi_redis/core.py", line 291, in group_add **{channel: time.time()} TypeError: zadd() got an unexpected keyword argument 'daphne.response.lGekRGuTPv!bsgpJbNJLP' crm - is my app in Django leads-198 - is the group of Channels Requirements.txt: boto3 coreapi Django==1.11 asgi_redis==1.2.1 channels==1.1.8 daphne==1.3 celery==4.1 PyMySQL djangorestframework==3.7.7 django-oauth-toolkit==0.12.0 django-cors-headers==2.1.0 django-redis==4.5.0 django-storages==1.5.1 raven==5.30.0 jsonfield==1.0.3 requests==2.18.4 simplejson suds-py3==1.3.2.0 xmltodict==0.10.2 Any suggestion ? Thanks -
How to properly create json arrays from two database table using Django
For many hours, I have been working on this since am new to django. Am trying to display database records from two tables in the following json below [ {"id":"1","title":"post title 1","content":"post content 1.","totalrating":"4"}, {"id":"2","title":"post title 2.","content":"post content 2","totalrating":"1"}, {"id":"3","title":"post title 3","content":"post content 3","totalrating":"2"} ] In Django If run this code below. I can successfully get all the posts records in json but without total rating models.py class Posts(models.Model): title = models.CharField(max_length=40) content = models.CharField(max_length=400) def __str__(self): return self.title + " " + self.content class Rating(models.Model): userid = models.IntegerField() postid = models.IntegerField() tpy = models.IntegerField() def __str__(self): return self.userid + " " + self.postid view.py def read(request): response_data = [ {'title': post.title, 'content': post.content} for post in Posts.objects.all()] jsondata = json.dumps(response_data) return HttpResponse(jsondata, content_type='application/json') My Problem: My issue is getting the record of rating count based on postid I knew I can do something like this Eg. rate = Rating.objects.filter(postid=1,userid=5).count() Finally I tried the following code below def read(request): response_data = [ {'id': post.id, 'title': post.title, 'content': post.content, 'total_rating': rate} for post in Posts.objects.all() rate = Rating.objects.filter(postid=post.id,userid=5).count() ] jsondata = json.dumps(response_data) return HttpResponse(jsondata, content_type='application/json') it displays error rate invalid syntax. can someone help me to get the database records as … -
Dynamic query building for search with Q Objects
I'm having a challenge with filtering my django queryset based on search criterias entered. Currently i have it working fine with all the search fields entered with valid data. The search should be able to work if a user just wants to search by one of the criteria. Here's what my view looks like results = documents.objects.filter( Q(f_filer__filer_first_name__istartswith=request.GET.get('first_name','')) & Q(f_filer__filer_last_name__istartswith=request.GET.get('last_name','')) &Q(f_office__o_office_name__istartswith=request.GET.get('office_name','')) & Q(f_doc_year__exact=request.GET.get('report_year', '')) & Q(f_report_id__exact=request.GET.get('filing_type', '')) & Q(f_start_travel_date__gte=datetime.datetime.strptime(request.GET.get ('travel_begin', ''),"%m/%d/%Y").date()) & Q(f_end_travel_date__lte=datetime.datetime.strptime(request.GET.get ('travel_end', ''), "%m/%d/%Y").date()) & Q(f_date_received__gte=datetime.datetime.strptime(request.GET.get ('received_start', '1/1/1900'), "%m/%d/%Y").date()) & Q(f_date_received__lte=datetime.datetime.strptime(request.GET.get ('received_end', '1/1/1900'), "%m/%d/%Y").date()) ).values('f_filer__filer_first_name', 'f_filer__filer_last_name', 'f_office__o_office_name', 'f_date_received', 'f_start_travel_date', 'f_end_travel_date', 'f_doc_year', 'f_report__r_title') -
django-cors-header not working as expected when using Postman
I'm trying to use my DRF API in my React Web App with Axios but I'm getting CORS policy blocked. I've checked the headers using POSTMAN and seems like django-cors-header is not actually embedding the Access-Control-Allow-Origin: * This is my settings.py from Django: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'trvl', 'rest_framework', 'coreapi', 'django_filters', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False And this is what I get from POSTMAN How can I fix this so every response has the Access-Control-Allow-Origin : * -
How to change django website language from English to Urdu ? Please tell me easy method as I am new in django
I made a website in django and but it should have both English and Urdu language options. Please tell me any simple method for converting this into Urdu language with code if possible. Thanks in advance -
Working Django site breaks when deploying with Zappa
I have a working Django site that hosts locally without errors, however deploying it with Zappa gives me the following error: The SECRET_KEY setting must not be empty. Initially while getting setup with Django this error was caused by incorrectly pathed settings, but that was fixed and the SECRET_KEY is present in a base.py file. One suggestion from the zappa output is to try turning "slim_handler" to false. Doing that results in the following error instead: No module named django.core.wsgi This is another error I had experienced before, when getting the site setup locally. It meant that Django was not present in the virtualenv I had setup (I checked, and the correct version is present now). What might be the reason that a Django site would work fine when hosted locally, but would give errors (seemingly pathing related) when attempting to deploy with Zappa? -
how to apply the condition in django model
I have some model class like. class user(models.Model): Student = 's' Hostel = 'h' Pg = 'p' type_of_user = ( (Student, 'Student'), (Hostel, 'Hostel'), (Pg, 'PG') ) u_type = models.CharField(max_length=1, choices=type_of_user, default=Student) and i have another class class student(models.Model) s_id = models.ForeignKey(user, on_delete=models.CASCADE) but i apply the condition on s_id (show only that user where u_type=student) -
Call LaTeX from Python Django
Within django, I am using jinja2 to render a template into a .tex file. I then need to call 'xelatex' on this .tex file, and save the output as a django File object. I've got as far as this: tex_file = render_to_string("foo.tex", context) If I save tex_file to a file, and run xelatex on it, I get the expected output, so it works up until this point. I then tried something like this: subprocess.run(["xelatex", tex_file], capture_output=True]) The problem is that I don't actually want to capture xelatex's output to STDOUT. I want to capture the output.pdf file that it generates. I know that I could just have xelatex save this file to /tmp/, and then have python open it and deal with it, but this seems slow and messy. Is there any way of getting subprocess to actually return the output: output = subprocess.run(["xelatex", tex_file], capture_output=True]) self.file = file -
Not able to save data correctly with extended user model
Extended auth User to Profile class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) age = models.IntegerField(default=18) university = models.CharField(max_length=100, default='') department = models.CharField(max_length=50, default='') Views.py `def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): try: with transaction.atomic(): form.save() profile_form.save() except DatabaseError: pass username = form.cleaned_data.get('username') messages.success(request, f'Account Created for {username}!') return redirect('jmiforums:homepage') else: form = UserRegisterForm() profile_form = ProfileForm() return render(request, 'jmiforums/register.html', {"form":form, "profile_form": profile_form,})` Data is saved twice every time in Profile table, one with User connected but no other data from profile model, and other vice versa. -
django_python3_ldap authentication errors
I am unable to authenticate using django-python3-ldap, I am able to ldapsearch with the same credentials but cannot run python3.6 manage.py ldap_sync_users or login with the ldap configuration i am currently using: ERROR: LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - 80090308: LdapErr: DSID-0C09042A, comment: AcceptSecurityContext error, data 52e, v3839 - bindResponse - None [ AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_python3_ldap.auth.LDAPBackend', ] LOGIN_URL = '/' LOGOUT_REDIRECT_URL = '/logout' LDAP_AUTH_OBJECT_CLASS = "user" LDAP_AUTH_URL = "ldap.server.com" LDAP_AUTH_SEARCH_BASE = 'OU=Engineering,OU=group1,OU=group2,DC=company,DC=com' LDAP_AUTH_USER_FIELDS = { "mail": "mail", "name": "cn", "username": "userPrincipalName"} LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_USE_TLS = True LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_openldap" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = None LDAP_AUTH_CONNECTION_USERNAME = "CN=Engineering Dude,OU=group1,OU=group2,DC=company,DC=com" LDAP_AUTH_CONNECTION_PASSWORD = "<password>" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } Now when i run ldapsearch -LLL -h ldap.server.com -D 'CN=Engineering Dude,OU=group1,OU=group2,DC=company,DC=com' -w '<password>' -b 'OU=Engineering,OU=group1,OU=group2,DC=company,DC=com' I am able to access the ldap server and see all of the info on the search. What am i doing incorrectly in the configuration? -
Read Django urls.py, models.py, views.py file content from Database tables
I want to create an application, which need to create dynamic application, dynamic models, dynamic urls, dynamic database from web-ui. When i click on create new application button, it need to create a new database, new models, new app and add entry to the settings.py. Please provide some suggestion. -
what is the best way to start gunicorn for django application
I have an api application running with 3 workers in gunicorn. A mobile application periodically sends the location to the server. I'm getting crash complaints I'm thinking there's a lot of simonormal requests going on. If I am not mistaken I can only handle 3 simultaneous requests. my gunicorn command line gunicorn taxithe.wsgi: application -b 0.0.0.0:8000 --workers 3 --log-level = info I was wondering if there is a way to improve the performance of my command line? Remembering that my machine only has a CPU -
Bootstrap modal not updating modal content
I am trying to create a table of models with a button next to them which opens a modal and has the same model row in form view. The table is being populated correctly, but the n number of bootstrap modals being created only hold the first iterable model value. Is it because bootstrap loads the content of the modals only once when the page is rendered ? What do I do to solve the problem ? Should I run a function to update the modal content according to the model data it has ?? Feel free to ask any more clarifications. {% extends 'base.html' %} {% load static %} {% block content %} <table> {% for item in data %} <tr> <th>From</th> <th>To</th> <th>Weight</th> <th>Length</th> <th>Type</th> <th>Material Type</th> <th>Number of Trucks</th> <th>Loading Time</th> </tr> <tr> <td>{{ item.From }}</td> <td>{{ item.To }}</td> <td>{{ item.Weight }}</td> <td>{{ item.Length }}</td> <td>{{ item.Type }}</td> <td>{{ item.MaterialType }}</td> <td>{{ item.Numberoftrucks }}</td> <td>{{ item.Loadingtime }}</td> <td> <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Bid now! for id {{ item.id }} </button> </td> {# {% endfor %}#} <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> … -
module 'resume_parser.constants' has no attribute 'YEAR'
I am trying to parse a resume in Pdf. When i select the Resume i want to parse and select 'Parse' i encounter that error. Where do i need to make adjustments? def get_education_level(nlp_text): education = {} for index, text in enumerate(nlp_text): for tex in text.split(): tex = re.sub(r'[?|$|.|!|,]', r'', tex) if tex.upper() in cs.QUALIFICATION_LEVEL and tex not in cs.S_WORDS: education[tex] = text + nlp_text[index + 1] education_y = [] for key in education.keys(): year = re.search(re.compile(cs.YEAR), education[key]) if year: education_y.append((key, ''.join(year.group(0)))) else: education_y.append(key) return education_y i expect to get an output from the parsed Resume instead im getting the above error.