Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to render image: net::ERR_CERT_AUTHORITY_INVALID
There is an app which uses many technologies for its front/back-end. In the end there is a compiled version which can be installed on premise. One page allows user to upload the logo image, which will be displayed on the page. Problem The browsers (Chrome, Firefox, Edge) would not render the uploaded image: Browser console: Failed to load resource: net::ERR_CERT_AUTHORITY_INVALID The broken path leads to the url defined in Django urls.py: case 'get_logo': return base_url + '/logo/'; Important This code worked perfectly fine for many year with the different setup. The current failed setup: - The app is installed and ran on a VM Is it possible that user is trying to upload the image from the HOST system inside the VM (VM Ware ESXI) and the browsers/smth else blocks this kind of cross-domain uploaded image inside a VM? -
How to import one module to another in Django/Python?
I am just getting started with Python and Django. So within my Django application I created a new module and within that I want to import some variable defined in the parent module. However I am getting certain errors while I tried various combinations. Below is how my directory structure looks like Now in my kafka_producer.py I am trying to import constants.py. kafka_producer.py from confluent_kafka import Producer import sys import logging import json from my_app.constants import KAFKA_BROKER_URL logging.basicConfig() #Assign Configuration conf = {'bootstrap.servers': KAFKA_BROKER_URL} print(conf) However I am getting no module found error. What is the correct way of importing modules in python? -
Django: Get Months since a certain datetime
I'm trying to get the number of months since a model is created. My Model looks like this: class Plan(models.Model): title = models.CharField(max_length=50) date_created = models.DateTimeField(default=timezone.now) plan_type = models.IntegerField() owner = models.ForeignKey(User, on_delete=models.CASCADE) Now i want to make a method that returns the number of months since the date_created. Tanks for any help :D -
How to make the button works when my navbar is collapsed?
For a personal Django project, i'm setting up a responsive navbar. When my navbar is collapsed, the button doesn't work. How to make it works ? I know we need js or jquery (I never know) but I never did js or jquery before. I already tried to put some code in static files of my Django project etc... But nothing worked. I also checked on the Internet but I didn't find something that I understand well. My navbar : <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Tournament Manager</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#topNavBar" aria-controls="topNavBar" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="topNavBar" style> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item "> <a class="nav-link" href="{% url 'contact' %}">Contact</a> </li> <li class="nav-item "> <a class="nav-link" href="{% url 'about' %}">About</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> {% if user.is_authenticated %} <P>Hi {{ user.username }}!</p> <p><a href="{% url 'logout' %}" class="btn btn-dark">logout</a></p> {% else %} <a href="{% url 'login' %}" class="btn btn-outline-primary btn-sm">login</a> | <a href="{% url 'signup' %}" class="btn btn-outline-success btn-sm">signup</a> {% endif %} </form> </div> </nav> And my base.html : {% load static %} <!DOCTYPE html> <html> <head> <link … -
django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6:
I am getting error while making migrate on django 2.1 application from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('sawy', '0005_auto_20190418_0607'), ] operations = [ migrations.AlterField( model_name='response', name='action', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='response', to='sawy.Action'), ), ] Error: Applying sawy.0006_auto_20190418_0608...Traceback .... .... .... django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: Python Version : 3.6 django Version : 2.1.4 DB: Postgres -
Exception Type: NoReverseMatch
Exception Type:NoReverseMatch this error is occurring during clicking the cancel button on web site. this cancel button is for canceling the delete process of post. searched every where but unable to understand the error. also made some changes some in code but didn't worked. '''path("by///",views.post_detail,name='post_detail'),''' views.py ` def post_detail(request,pk): post = Post.object.get(pk=pk) comments = Comment.objects.filter(post=post) context = { 'post':post, 'comments':comments, } return render(request,'posts/post_detail.html',context) class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ("user", "group") success_url = reverse_lazy("posts:all") def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Post Deleted") return super().delete(*args, **kwargs) ` moels.py class Post(models.Model): title = models.CharField(max_length=255,default='') user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:post_detail", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] post_confirm_delete.html and _post.html {% extends "posts/post_base.html" %} {% block post_content %} <h3>Are you sure you want to delete this post?</h3> <div class="posts"> {% include "posts/_post.html" with post=object hide_delete=True %} </div> <form method="POST"> {% csrf_token %} <input type="submit" value="Confirm Delete" class="btn btn-danger btn-large"> <a href="{% url 'posts:post_detail' username=self.user.username pk=object.pk %}" class="btn … -
Not able to upload file
I am beginner in Django. I am trying to upload file using Django form but file is not upload except file other detail is upload in Database successfully. i read the document but can't find any error , also saw many videos but it not helping for me. please help me. thank you. model.py class certificateDb(models.Model): D = 1 Q = 2 U = 3 Production = 4 environment_TYPES = ( (D, 'D'), (Q, 'Q'), (U, 'U'), (Production, 'Production'), ) application = models.CharField(db_column='Application', max_length=255, blank=True, null=True) # Field name made lowercase. startdate = models.DateField(null=True) expiredate = models.DateField(null=True) environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES) file=models.FileField(null=True,blank = True) view.py def list(request): certificatedata = certificateDb.objects.all() context = { 'certificatedata': certificatedata } return render(request, 'list.html',context) def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True certificatedata = certificateDb.objects.all() data['list'] = render_to_string('list_2.html',{'certificatedata':certificatedata}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) def certificate_create(request): if request.method == 'POST': form = CertificateForm(request.POST, request.FILES or None) else: form = CertificateForm() return save_all(request,form,'certificate_create.html') form.py from django import forms from SharedApps_Application.models import certificateDb from SharedApps_Application.models import serviceDb from django.contrib.admin.widgets import AdminDateWidget from django.forms.fields import DateField class CertificateForm(forms.ModelForm): startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) … -
What kind of error is this 'Reverse for 'Bl' not found '
I was trying to create login web application then I got this error in django: /django/urls/resolvers.py", line 660, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'Bl' not found. 'Bl' is not a valid view function or pattern name. I searched over the internet but I did not found any error like this.Please help. -
Django: change default label content in views.py or other methods
class SchoolUpdateView(UpdateView): model = models.School fields = ('name', 'principal') labels = {'name': '學校名稱:', 'principal': '學校校長', 'location': '學校地址'} It won't work, still showed name, principal, location; not the language I want. And I have tried to use jQuery to modify it. But it is <label for="id_age">Age:</label> as default set in html without given id. -
Celery task calling itself after task succeed without celerybeat
I want to call my celery task occasionally like every 30minutes after current task done, But sometimes task takes longer than expected because of task is downloading file from remote server. So i dont want to use celeryBeat. Also using self.retry is only for when error occurred i suppose. Here is my task: @shared_task(name="download_big", bind=True, acks_late=true, autoretry_for=(Exception, requests.exceptiosn.RequestException), retry_kwargs={"max_retries": 4, "countdown": 3}): def download_big(self): my_file = session.get('example.com/hello.mp4') if my_file.status_code == requests.codes["OK"]: open("hello.mp4", "wb").write(my_file.content) else: self.retry() -
Django Datatables - Cannot Find Good Examples
I'm trying to get editable tables on my Django budget website. The purpose of these editable tables is to show the budget for each category on its page and be able to directly update the sub budgets for that category in one page, kinda like a spreadsheet. Just like I always do for a given problem, I searched for a solution online. Surprisingly to me, the results weren't that helpful. But the most common answer I found was django-datatables based on https://datatables.net/. After determining this was the best solution for me, I went and researched the tool. Again, the results I found weren't great, but I tried them out anyway. I found this GitHub repo that seemed to have exactly what I wanted, but when I tried to run the code, I immediately ran into some errors. It's using virtualenvs which I'm not totally familiar with, but I still found it strange I got an error right away. Seems like it might not be maintained well? Or maybe I made an error. I also found this website which seemed it might be a good resource too, but again, it looks abandoned. Probably the best resource I found was given in … -
TypeError: string indices must be integers in django
I am trying to store json into bigchainDB. But problem is when I am hard coding the json object and broadcasting among other nodes Its getting successful. But when I am sending the same json object from the postman I am getting an error string indices must be integers This is my func def index(request): root = settings.BIGCHAINDB bdb = BigchainDB(root) alice, bob = generate_keypair(), generate_keypair() insertDB = json.dumps(request.body.decode("utf-8")) jsonDict = json.loads(insertDB) prepared_token_tx = bdb.transactions.prepare( operation='CREATE', signers=alice.public_key, recipients=[([bob.public_key], 10)], asset=jsonDict) fulfilled_token_tx = bdb.transactions.fulfill( prepared_token_tx, private_keys=alice.private_key) bdb.transactions.send_commit(fulfilled_token_tx) txid = fulfilled_token_tx['id'] return HttpResponse(txid) Any suggestion is most welcome. Thanks in advance. -
Is there a way we can render more than one view in same template in Django? If there is what are the best practices to do it? Thanks in advance
I'm starting a data analysis project in django and want to show text data and graph data in single tamplate which are generated from different views. Is it a good practice to do this way or I should rander two different template for text data and graph data? -
Docker Container runs fine locally, SSL Nginx instance can't Locate App
I'm migrating my personal website to a a docker-chain, and have built out the docker-compose to integrate Django, Postgres, Gunicorn and Nginx. I also have an Nginx instance running on my Digital Ocean droplet to allow for SSL on the server. My problem is that I've added SSL to the Nginx instance on my DO Droplet and I can't put my Django site to the internet. I believe this is a simple issue but I'm not understanding where the host Nginx can find the application's Nginx container. The following is the Nginx docker-compose section # Nginx Configurations nginx: build: context: ./nginx dockerfile: Dockerfile_Nginx volumes: - static_volume:/usr/src/personal_website/static ports: - 2019:80 - 443:443 depends_on: - django When the container runs on my local machine, I can have the web application display to http://localhost:2019, which is what I want. However, I want the Nginx instance on my Droplet to display it. Below is the configuration file for the website: upstream personal_website { server django:2019 } server { server_name example.com www.example.com; listen 80; location / { proxy_pass http://personal_website; } } I believe this is all I needed, correct? What happens when I run the container on the server is that I have the base … -
Reverse for 'profile_update' with arguments '(1,)' not found. Issue
I have a base url link to access a profile edtting screen but it seems to break my application. Ive tried so many things that i am getting confused by the different views. I was able to get the form appearing previously but have somehow broken it. from my base.html(if i remove this line the app start to work again). Im not sure about this user.id parameter im passing in this - is it needed? <li class="nav-item"> <a class="nav-link" href="{% url 'accounts:profile_update' user.id %}">Edit Profile</a> </li> my urls file: path('profile/edit/', views.ProfileCreate.as_view(), name='profile_update'), my model: class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='userprofile') houseNumber = models.CharField(max_length=150, default='') street = models.CharField(max_length=150, default='') suberb = models.CharField(max_length=150, default='') city = models.CharField(max_length=150, default='') phone = models.CharField(max_length=150, default='') def __unicode__(self): return self.user.get_full_name() def __str__(self): return self.user def get_absolute_url(self): return reverse('account:profile', kwargs=[self.pk]) my form: class ProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) class Meta: model = Profile fields = ['user', 'houseNumber', 'street', 'suberb', 'city', 'phone'] the html for the form: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor … -
How to fix, PostgreSQL BEFORE UPDATE Trigger on selected columns executed from Django side on the columns not associated with the Trigger?
Basically, I am creating a Django app with a PostgreSQL database, now for a given table on a database I have to use Triggers for preventing update on selected columns, Trigger is working properly from the database side doing what it is made to do, preventing update on selected columns and allowing to update non-associated column with trigger. Now from the Django side, whenever I try to update the table's fields/columns which are not associated with the trigger, it invokes/executes the trigger preventing the update operation for those not associated fields/columns and this trigger is even being executed when trying to add new record or data from Django side preventing insertion of new record. Can anyone please help? Thank you -
Database Design for application specific analytics
I am designing an analytics dashboard for one of my application. The application deals with Bookings data. Below are the parameters on the basis of which I want to represent an overall view of the system. Booking Title Booking Status (as in New, Active, OnHold, Assigned, Cancelled, etc) Client (as in Samsung, EY, WU, Adobe, etc) Booking Type (as in Product Demo, Interview etc) Date Location Total Cost (in $) There would be about a million rows. I wanted to show the following things on my dashboard: Total Bookings Monthly Bookings Monthly revenue Most Active Clients Most Active Locations # of Bookings in each state and types %increase/decrease in number of bookings from past month %increase/decrease in revenue from past month My approach is to first gather this data from multiple tables into a separate analytics table, keep updating it via scripts and django signals, and then perform analytics on this table. For performing analytics, I wanted to load the data from the above analytics table into a numpy arrays/pandas DFs, perform all kinds of operations on it and send the arrays to frontend for creating dynamic charts. I'm using Django rest framework on backend and React's recharts library on … -
Geonode-project not assuming changes in css
I created a Geonode project following the instructions of geonode-project GitHub repo. After running the instance for development using the respective docker-compose files I tried to apply changes to site_index.html and site_base.css files. The changes on the html file are ok however the css changes are not assumed, only if I run the collectstatic command. Since I'm running it in dev I was expecting that the collectstatic would not be necessary. Doing developments and run the collectstatic at every css change is annoying. Am I doing something wrong? Thanks -
django returning or posting wrong template html?
I developed a django project named "dms" and an app which name is "add_excel" last month. The app receieves excel files from web page and store the data into mysql database. Today I added another two apps, "add_struc" and "homepage", which should be another function app and the homepage app. But something odd shows up. After I clicked the "upload" button in "add_excel" app, instead of it's original functions, it redirects to "homepage" without doing anything to the database. The VS Code shows: [18/Apr/2019 11:08:00] "GET / HTTP/1.1" 200 317 # I opened the homepage [18/Apr/2019 11:08:02] "GET /addexcel/index/ HTTP/1.1" 200 1341 # I clicked to the "add_excel" app hyperlink [18/Apr/2019 11:08:20] "POST /homepage/index/ HTTP/1.1" 200 317 # I clicked "upload" but it redirected me to homepage again. If I delete the homepage url in the urls.py for the whole project, and click the upload button again, it says: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/homepage/index/ Using the URLconf defined in dms.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='index'] ^addexcel/ ^addstruc/ The current path, homepage/index/, didn't match any of these. The urls.py in dms project: from django.contrib import admin from django.conf.urls import url, … -
Django Allauth creates account on invalid signup form
I am using Django Allauth v0.36 and the signup form will create the account even when the form is invalid. It does not redirect or log in the user when it is an invalid form, it stays on the signup page and shows the from invalid message. When I try to sign up with the same credentials it says that account already exists, database shows the account created. Any idea why this is happening? Here is a list of my settings: ACCOUNT_ADAPTER = 'allauth.account.adapter.DefaultAccountAdapter' #ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True # By changing this setting to False, logged in users will not be redirected when they access login/signup pages. ACCOUNT_AUTHENTICATION_METHOD = 'username_email' # User can login with username or email ACCOUNT_USERNAME_REQUIRED = False # TODO: What about HOS Users?? ACCOUNT_CONFIRM_EMAIL_ON_GET = False ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 180 ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 # Determines the expiration date of email confirmation mails (# of days). ACCOUNT_EMAIL_CONFIRMATION_HMAC = True # In order to verify an email address a key is mailed identifying the email address to be verified. In previous versions, a record was stored in the database for each ongoing email confirmation, keeping track of these keys. Current versions use HMAC based … -
How to fix 'Permission matching query does not exist.' in Django
I'm creating a web system for a school in Django, for that I decided that I would use Django-Gurdian for object based permissions, and also I set up a signal after migration to create default groups like: all-students, all-teachers, etc... And I am running tests with Pytest, but when I run them for some reason all the permissions seams to disappear. This is the very first project of this scale that I do, and I'm creating it to learn a little bit more. This is also my first question in this site. I'm sorry, but lots of the comments and variables, etc... are in portuguese, or some mix with english. I can provide a translation if you need it. And I know that most of the code is probably poorly written, as I said I am still learning. I've tried the normal server, but nothing seams wrong. When I migrate from terminal all is OK. I'm running it in a Windows 10, using PyCharm to run it. I'm using Python 3.7, Django 2.1.8, django-guardian 1.5.0, pytest 4.2.0. apps.py - Registering the signal class EscolaConfig(AppConfig): name = 'escola' def ready(self): from django.db.models.signals import post_migrate from .signals import populate_models post_migrate.connect(populate_models, sender=self) signals.py … -
How to list my categories and forums related to it? Django
Model class Category(models.Model): class Meta(): verbose_name_plural = "Categories" cat_name = models.CharField(max_length=50) description = models.TextField() def get_forums(self): get_forum = Forum.objects.filter(category=self) return get_forum def __str__(self): return f"{self.cat_name}" class Forum(models.Model): class Meta(): verbose_name_plural = "Forums" category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="forums") parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) forum_name = models.CharField(max_length=50) description = models.TextField() def __str__(self): return f"{self.forum_name}" Views class Home(ListView): model = Category template_name = 'forums/index.html' context_object_name = 'category' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cat'] = Category.objects.all() return context I am trying to get a homepage where I would be able to list my categories and show the forums in those categories. The template I have is running a for loop which is looping through all Categories. In the shell i am able to get the forums with the: Category.objects.get(pk=2).get_forums() command. But this limits it to one category. -
How to use different field as label for modelformset?
I'm creating an inventory management system using django as a framework. I have a simple model with a product column and an order_amount column. The only part I want users being able to update using the modelformset is the order_amount column. Django automatically labels each form with the field name "Order Amount". What I would like it to do is to label each form as the instance it is updating from the Product field. models.py class Sysco_Products(models.Model): Products = models.CharField(max_length = 200) order_amount = models.IntegerField(blank=True, null=True) def __str__(self): return self.Products class meta: managed = True db_table = 'sysco_products' forms.py from django import forms from .models import Sysco_Products class orderform(forms.ModelForm): class Meta: model = Sysco_Products fields = ('order_amount',) views.py class SyscoOrder(TemplateView): template_name= "SyscoOrder.html" def get(self, request): OrderFormSet = modelformset_factory(Sysco_Products, fields=('order_amount',)) context = { 'OrderFormSet' : OrderFormSet, } return render(request, self.template_name, context) def post(self, request): OrderFormSet = modelformset_factory(Sysco_Products, fields=('order_amount',)) formset = OrderFormSet(request.POST,) if formset.is_valid(): formset.save() return redirect('Order') context ={ 'formset' : formset, } return render(request, self.template_name, context) -
Why I cannot use @action decorator on ModelViewSet in Django Rest Framework
I build a very basic ViewSet on User model to CRUD a user. I want to use ModelViewSet and @action decorator to make codes clean. Set a permission(Just use IsAuthenticated as example) required on the list function. so that only who are signed can do this. This is the code sample. from rest_framework.decorators import action, list_route from rest_framework.permissions import IsAuthenticated class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @action(detail=False, permission_classes=[IsAuthenticated]) def list(self, request, *args, **kwargs): return super(UserViewSet, self).list(request, *args, **kwargs) But I got an error Cannot use the @action decorator on the following methods, as they are existing routes: list If I remove @action, it works well. My question is why I cannot use @action decorator on an existing routes list? -
In Django, how do I take a file from views.py and set it as a JS array variable?
I am creating a spelling test website. The spellings are in a file in my Django home folder (path 'home/quiz.txt') and I have written the necessary code in views.py to read the file from this location and set it as the variable "file" within the 'Quiz' view. However, when I go into the quiz.html or quiz.js, I do not know how to use this file in the actual code. What do I do? views.py: class Quiz(TemplateView): template_name='quiz.html' file = open(os.path.join(settings.BASE_DIR, 'home/quiz.txt')) quiz.js: function load(played, mistake, score){ document.getElementById("clear").removeAttribute("hidden"); document.getElementById("load").hidden=true; var x = file; var step; var spellList = document.getElementById("spellList"); for (var xStep = 0; xStep < x.length; xStep++){ if(x[xStep].match(mistake)){ mistList.push(x[xStep]); } } }