Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to display registered values in profile page - django
I have a member table, I want to fetch and display some of the fields like fullname , email and phone number in the profile page. this is my member table class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') this is my profile table class Profile(models.Model): fullname=models.CharField(max_length=60) contactno=models.CharField(max_length=10) worknumber=models.CharField(max_length=10) email=models.CharField(max_length=30) company=models.CharField(max_length=20) i want to display fullname email and phone number from member table.. -
how to connect one field value to sencond field value in django?
i amnot understanding how to one session to another session users that why i did table in one user sending mail in that he will get some link he register again that is second session statred i am understand how to connect both see in that table if some in same name then its showing status one .. but i want if some select one first user skale9173@gmail second user kale.sandhya07@gma enter image description here -
How to use variable in for loop using DJango
I can do this in regular python, but can't seem to do this in the template. So here are my variables: PropertyID = ['A1','A2','A3'] filePaths = {A1:'['file1.jpg','file2.jpg','file3.jpg',]', A2:'['file1.jpg','file2.jpg','file3.jpg']'} My template: {% for properties in PropertyID %} {% for filePaths in imageFiles %} {% for singleFiles in filePaths %} {% endfor %} {% endfor %} {% endfor %} I want to be able to iterate through filePaths dynamically, but when I try: {% for singleFiles in filePaths.{{properties}} %} I get an error: Could not parse the remainder: '{{properties}}' from 'filePaths.{{properties}}' I have tried filePaths['properties'] and filePaths[properties] and pretty much every combination. I just can't figure out why this isn't working. If I do filePaths.A1 it works fine, but I can't iterate over the rest of the paths this way. Any help would be much appreciated, probably something really dumb I missed. -
Unable to create a django project with 2 apps in it
When I run the server it shows this error: and my code link https://github.com/ARGAMERX/django-problem -
My CSS Navigation Bar's Background color property isn't working,please help me
I am trying to create a navigation bar with a search box. When I insert the elements in the navbar and set the display to inline-block in css, the navigation bar's background color is not being displayed, I am trying to get around this problem for a while now, please help me. My HTML navbar, *{ box-sizing: border-box; font-family: 'Lato', sans-serif; font-weight: normal; color: white; background-color: rgba(0,0,0); margin:0; } .main_nav{ background-color: rgba(255,255,255.1); } .main_nav li{ display: inline-block; padding: 0 10px; } {%load static%} <!DOCTYPE html> <html> <head> <title></title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{%static 'css/styles.css'%}"> </head> <body> <header> <nav class="main_nav"> <ul> <li><img width="80" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/IMDB_Logo_2016.svg/1200px-IMDB_Logo_2016.svg.png"></li> <li>Menu</li> <li> <form method="GET" action="{%url 'search-view'%}"> <input type="search" name="query" id="query" placeholder="search movie"> <button type="submit">Search</button> </form> </li> </ul> </nav> </header> <section> {%block content%} {%endblock%} </section> <footer></footer> </body> </html> the .main_nav background color doesn't seem to be working. If you have a better way to give the same output with the background color, please do tell me that also. Excuse the bad code, I'm kinda new to this! Thanks in advance! -
I have this Error - jquery.min.js: 2 Uncaught TypeError: Illegal invocation django
I am trying to save the order details data, however I get this error. jquery.min.js: 2 Uncaught TypeError: Illegal invocation I am still in the process of sending that data to the database, I just want to see if it is working correctly with this line of code: vents = request.POST['ventas'] JS $('form').on('submit', function (e) { e.preventDefault(); var parametros = new FormData(); parametros.append('action', $('input[name="action"]').val()); parametros.append('ventas', JSON.stringify(ventas.items)); submit(window.location.pathname, parametros, function(){ location.href = "{% url 'Venta' %}"; }); }); VIEWS def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'autocomplete': productos = Producto.objects.filter(nombre__icontains=request.POST['term'])[0:10] for i in productos: data = [] item = i.toJSON() item['value'] = i.nombre data.append(item) elif action == 'add': vents = request.POST['ventas'] else: data['error'] = 'No ha ingresado a ninguna opción' except Exception as e: data['error'] = str(e) return JsonResponse(data,safe=False) -
How to display registered person details in profile page - Django
i have a member table, I want to display some of the fields like fullname , email and phone number in the profile page. this is my member table class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') this is my profile table class Profile(models.Model): fullname=models.CharField(max_length=60) contactno=models.CharField(max_length=10) worknumber=models.CharField(max_length=10) email=models.CharField(max_length=30) company=models.CharField(max_length=20) i want to display fullname contactno email automatically from member table -
why this error is showing [Errno 61] Connection refused in django
why i'm getting this [Errno 61] Connection refused error after doing and adding required things in django can anyone fEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' settings.py ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_HOAT='smtp.gmail.com' EMAIL_HOST_USER= 'xyz@gmail.com' EMAIL_HOST_PASSWORD ='*****' EMAIL_PORT = 587 EMAIL_USE_TLS = True views.py i also have on less secure app in gmail account def signup(request): if not request.user.is_authenticated: fm=signUpForm() if request.method == 'POST': fm = signUpForm(request.POST) if fm.is_valid(): fm.save() from_email = settings.EMAIL_HOST_USER em = fm.cleaned_data['email'] to_list = [em] send_mail('Subject here','Here is the message.',from_email,to_list,fail_silently=False,) print(send_mail) return redirect('home') else: fm = signUpForm() return render(request,"signup.html" ,{'signupforms':fm}) -
Sorting with 'Date' Django template filter
I use date_value|date:'d M, Y' date filters when presenting my data in a jQuery datatable. However, the table is unable to sort the rows correctly. eg. 28 DEC is indeed an older date than 30 DEC but it is considered older than 29 NOV as well since the sorting does not compare the time but the literal strings instead. -
I am having a problem with Reverse method on comment section for a blog post
I am having a problem with Reverse method on comment section for a blog post. Posting part works fine but its the redirect view which is not working. It greets me with the message: Not Found: /article/17/ [18/Jan/2021 03:38:33] "POST /article/17/ HTTP/1.1" 404 1747 May be it has something to do with the id or i am redirecting in a wrong way .. Here's what i've done: views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect from .models import Article from comments.models import ArticleComment from comments.forms import ArticleCommentForm from django.views.generic import ( ListView, DetailView ) class ArticleListView(ListView): model = Article template_name = 'articles/home.html' context_object_name = 'articles' ordering = ['-date_published'] paginate_by = 5 class ArticleDetailView(DetailView): model = Article form_class = ArticleCommentForm template_name = 'articles/article_detail.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) comments = ArticleComment.objects.filter( article =self.get_object() ).order_by('created_on') data['comments'] = comments if self.request.user.is_authenticated: data['comment_form'] = ArticleCommentForm(instance=self.request.user) return data def post(self, request, pk, **kwargs): article = get_object_or_404(Article, id=request.POST.get('object_id')) if request.method == 'POST': form = ArticleCommentForm(request.POST) if form.is_valid: new_comment = form.save(commit=False) new_comment = ArticleComment(comment= request.POST.get('comment'), user = self.request.user, article = self.get_object()) new_comment.save() messages.success(request, f'Your comment has been posted') return reverse(request, 'article-detail', kwargs={id: self.id}) else: context … -
Django models AutoFeild countinuously incrementing. Not starting from last deleted record number
I am working on a project in Django and using Autofield as primary key in models. Here in Django when I delete any record it is deleted successfully and then when I enter a new record using Django forms the primary key of the new record is next value of the previous record. **Example: ** Suppose I have a table and I've set its primary key as AutoField in Django models and then I enter records so the primary key will be " 1 " and " 2 " respectively, And now suppose I have deleted the second record from the database and then insert the new record then the database sets its Primary key "3" but I want that after deleting a record the database starts incrementing from previous value like if i deleted the record which has primary key "2" and then I insert a new record its Primary Key should be " 2 ". Is it possible ? If the above situation is possible please guide me how to do it. My model is something like given below: models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, … -
Reverse for '<QuerySet [<ShortURL: https://google.com>]>' not found
I'm trying to create a url shortener and I'm creating the redirect part of it. I have a view that triggers when a user searches the short url that they generated. # views.py def page_redirect(request, url): get_url = ShortURL.objects.filter(short_url=url)[:1] return redirect(get_url) get_url returns <QuerySet [<ShortURL: https://google.com>]>. Does anyone know how I would filter https://google.com so I can put that url into redirect() to redirect the user to the original long url? Other Code: # models.py class ShortURL(models.Model): long_url = models.URLField(max_length=700) short_url = models.CharField(max_length=100) time_date_created = models.DateTimeField() def __str__(self): return self.long_url # urls.py urlpatterns = [ path('<str:url>', page_redirect, name='redirect'), ] -
how serve css on djago sub domain (on cpanel)
I would like to know how to run django in a sub domain in cpanel currently I did it using cpanel like this url 'www.domail / test / app' the application loads fine but the css and js points to the source as for example (www.domail.com/statics ..) in turn the admin panel does not load any css or js U_U If anyone has an idea or doc that can give me some insight, I would be very grateful -
Django: Cannot save data from Form in Database (MySql)
I've been following a tutorial for Django, but making small changes, doesn't allow me to save the form in Database. views.py: def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] contact = Contact(email=email, subject=subject, message=message).save() return render(request, 'contact.html', {'form': form}) else: form = ContactForm() return render(request, 'contact.html', {'form': form}) models.py class Contact(models.Model): email = models.EmailField(max_length=200) subject = models.CharField(max_length=200) message = models.TextField(max_length=500) forms.py class ContactForm(forms.Form): email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) -
why CSRF verification failed. Request aborted. becuae i added {% csrf_token %} in my template
i have added {% csrf_token %} inside form but it is still showing csrf verification fail can anyone help me to find whats going wrong in my code my signup.py file {% extends 'home.html' %} {% load static %} {% block body %} <div class="container-fluid mt-5 mb-4 col-lg-8 text-center text-secondary"> <h4 class="text-secondary"><b>Login using your credentials </b></h4> </div> <div class="container-fluid p-3 mt-1 mb-5 col-lg-8 signupf"> <form action="" autocomplete="on" method="POST" novalidate> {% csrf_token %} {% for fm in signupforms %} <div class="form-group mt-0 m-0"> {{fm.label_tag}} {{fm}} <small class="text-danger">{{fm.errors|striptags}}</small><br /> </div> {% endfor %} <input class="btn btn-primary mb-4" type="submit" value="Submit" /> </form> </div> {% endblock body %} views.py file and also showing errno 61] connection refused def signup(request): if not request.user.is_authenticated: fm=signUpForm() if request.method == 'POST': fm = signUpForm(request.POST) if fm.is_valid(): fm.save() from_email = settings.EMAIL_HOST_USER em = fm.cleaned_data['email'] to_list = [em] send_mail('Subject here','Here is the message.',from_email,to_list,fail_silently=False,) print(send_mail) return redirect('home') else: fm = signUpForm() return render(request,"signup.html" ,{'signupforms':fm}) -
An operational error when making django AJAX likes
This is the error that I got. django.db.utils.OperationalError: no such table: photos_post_likes I was following this video to create a like button. https://youtu.be/pkPRtQf6oQ8 By then I had already created the model (Post). Just when I added a new line (likes) in models.py and ran makemigrations, it migrated without any problem. But, when I ran migrate this error appeared. Here is the models.py file from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from PIL import Image class Post(models.Model): date_shared = models.DateTimeField(default=timezone.now) caption = models.TextField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') # this line made the error occur image = models.ImageField(upload_to='post_images') def __str__(self): return self.caption def save(self): super().save() img = Image.open(self.image.path) if img.height > 800 or img.width > 800: output_size = (800, 800) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('home') -
Django setdefault, NoMouduleError
(first of all, sorry for my bad English) import os import django import csv import sys os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bangolaf.settings') django.setup() from product.models import Category, Subcategory, Product CSV_PATH_PRODUCTS = './category.csv' with open(CSV_PATH_PRODUCTS) as in_file: data_reader = csv.reader(in_file) next(data_reader, None) for row in data_reader: if row[0]: print(row) ModuleNotFoundError: No module named 'bangolaf' I'm trying to make csv reader which connect my django project and csv file. The csv file is in out of django project, so I made 'setdefault' of my django, and same virtual env is also activated. but I got ModuleNotFoundError message when I checked manage.py of django project, the setdefualt is exactly same like csv reader's one I made. def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bangoraf.settings') looking for someone to help -
How can I create persistent server-side objects in Django?
I am creating a website in Django to display the results of a calculation on a large csv file. I have this function in my views.py: def results(request, input=""): from calculations import calculate from calculations import datamanager data = datamanager(); return render(request, template, {"res":calculate(data.data, data.cov_table, input)} Unfortunately, because the input varies quite a bit I run calculate every time and caching will not decrease loading times that much. However, datamanger's init() method takes a long time because it has to read two large csv files, so only running it once will save time. Is there a way to only load datamanager when the server starts up and just access it from within the view? I have tried creating an app out of the object but then I read that "There’s no such thing as an Application object" on the Django webpage. I would also like to avoid creating a Database. The csvs definitely could be a database, but the datamanager class does a reasonable amount of processing on init. This is for finance, so the datamanager class loads a list of securities: [ISIN, Return, STD, Volume, dict(key: time, value: price)] and a table of correlations. -
Django: align models to a configuration (e.g. a text file, or API)
The specific problem I face is that I have an API interface which defines tables in a kind of domain specific language (the target is Zoho Analytics). The django code prepares data and sends it to Zoho. Now I want to add an additional backend: I want to write this data to postgres. It would be nice to have the full use of the Django ORM. However, when I change the tables for the Zoho implementation, I want the "associated" Django models to update to, taking advantage of schema migration and all the other good things. The Django models are not really "dynamic", the schema won't change during runtime, the schema only needs to be discovered at start up (or when manage.py makemigrations is run) but it seems that attempts to do dynamic models are the closest fit. Discussions like this are typical: Django dynamic model fields They are typically quite old and seem like there is no solution which is not hackish. It's almost like I would be better off generating a .py file :) -
In Django, how do I generate a welcome message for the user?
Something like: Welcome {user that is logged in}! It should appear when the user logs in. Thank you! -
Unable to create the django-migrations table
I am very new at this and am trying to connect my django project with my mongodb using djongo. I've set up mongo atlas and give myself the admin role. to create a new project: django-admin startproject mysite I've created a database with nothing in it called demo_db that has no data written Then I change the settings.py database session into: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'demo_db', 'HOST': 'mongodb+srv://louisa:<password>@cluster0.ya1jd.mongodb.net/demo_db?retryWrites=true&w=majority', 'USER': 'louisa', 'PASSWORD': '<password>', } } I am running atlas version 4.2. When I save the settings.py and run python manage.py migrate I run into this giant error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Traceback (most recent call last): File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 897, in _create query = CreateQuery(self.db, self.connection_properties, sm, self._params) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 645, in __init__ super().__init__(*args) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 729, in parse self._create_table(statement) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 649, in _create_table self.db.create_collection('__schema__') File "/opt/anaconda3/lib/python3.7/site-packages/pymongo/database.py", line 418, in create_collection read_concern, session=s, **kwargs) File "/opt/anaconda3/lib/python3.7/site-packages/pymongo/collection.py", line 187, in __init__ self.__create(kwargs, collation, session) File "/opt/anaconda3/lib/python3.7/site-packages/pymongo/collection.py", line 267, in __create collation=collation, session=session) File … -
Restricting Drop Downs populated by a query to the active user's inventory
I have nearly completed a collectables inventory system for users to populate their own/inventories and filter through them. I have been able to restrict the user to only viewing their records, but the drop downs for filtering records are based on the full user population e.g. A user can only see their book titles but the drop down will show all book titles populated in the database for all users. I have tried some functions in Forms.py in the choice filters to initialize them with restrictions by the user id, similar to how I have restricted the users to see their own records but this has not worked. Models.py class ComicInput(models.Model): Publisher = models.CharField(max_length=20, default='Marvel', choices=Publisher_Choices, null=True, blank=True ) Title = models.CharField(max_length=50,default='', blank=False) Series = models.CharField(max_length=8,default='1st', choices=Series_Choices, null=True, blank=True) Type = models.CharField(max_length=30, choices=Type_Choices, null=True, blank=True ) #default='Reg' Number = models.IntegerField(default='', blank=False) Category = models.CharField( max_length=12,default="Hold",choices=Category_Choices,blank=True, null=True) uid = models.ForeignKey(User,on_delete=models.CASCADE, editable=False) #default=False, null=True) def __unicode__(self): return '%s %s %s' % (self.uid,self.Title, self.Number, self.Grade, self.Series, self.CoverPic, self.Category) class Meta: ordering = ('Title', 'Series', 'Number') Forms.py ##############Comic Input Forms############### class ComicInputForm(forms.ModelForm): class Meta: model = ComicInput fields = '__all__' ###################### Collection View Filters ####################### # ***** I THINK THE PROBLEM CAN BE FIXED … -
GET /static/bootstrap.min.css HTTP/1.1" 404 68
Im getting this error "GET /static/bootstrap.min.css.css HTTP/1.1" 404 68 in my terminal whenever I update my page with prod.py I build. I think it's my code in my settings.py that is wrong and with the static files also. there are my codes 1. B_F1 #project name 2-1. B_F1 3. settings 4-1. base.py 4-2. dev.py 4-3. prod.py # i use it when i publish 2-2. B_F_user # app name 2-3. static 3. bootstap.min.css this is base.py code from pathlib import Path import os import json from django.core.exceptions import ImproperlyConfigured BASE_DIR = Path(__file__).resolve().parent.parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'B_F_user', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'B_F1.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, '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', ], }, }, ] and this is prod.py code from .base import * DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') and it my base.html <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <meta name = "viewport" content = "width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/bootstrap.min.css"/> i used manage.py collectstaic but … -
How to handle datetimes for users in different locations django?
I have an application that is being built with Django and Django REST Framework. Users can add certain objects to the database and set expiry dates on them. Other users will retrieve those added items from the database and it will be displayed client-side. Both the users creating the objects and the users retrieving them could be in different places of the world. I plan to store the datetimes in UTC format. How do I make sure that the datetime is in UTC format before storing and when a user tries to retrieve one of these items, it is correctly displayed in their Timezone? What I am thinking I am thinking that I should convert it to UTC (client-side) and save that to the database and then when a user retrieves that object I will return it in UTC (from the database) and change the time to the user's local time client-side. Is this a good approach? -
Django: How to properly use two forms in one template for two models that are connected by a foreign key
I have 2 models: Applicant and Application. Application is connected by foreign key to Applicant. For any applicant there can be many applications. models.py class Applicant(models.Model): first_name = models.CharField(max_length=150, null=False, blank=False) last_name = models.CharField(max_length=150, null=False, blank=False) email = models.EmailField(blank=False, null=True) ... class Application(models.Model): applicant = models.ForeignKey(Applicant, null=False, blank=False, on_delete=models.CASCADE) ... I cannot figure out how to have 2 forms, for the 2 models, display in 1 template such that upon submission both Applicant and Application can be completely populated and saved. I've tried inlineformsets but I kept on getting errors that essentially Application must have an applicant instance. I then tried just having two separate forms and saving them separately, but I got the same error. How can I correct this? forms.py class ApplicantForm(ModelForm): veterinaryContactPermission = forms.BooleanField(widget=forms.CheckboxInput) class Meta: model= Applicant fields = '__all__' class ApplicationForm(ModelForm): class Meta: model = Application exclude = ['applicant'] <!-- Excluding so that applicant drop down showing all possible applicants is not displayed in the template. I don't want other applicants to be visible to current applicant. ApplicantFormset = inlineformset_factory( Applicant, Application, form=ApplicationForm, fields=['applicant'], can_delete=False ) views.py class ApplicantApplication(CreateView): model = Applicant # form1 = ApplicantForm # form2 = ApplicationForm form_class = ApplicantForm template_name = …