Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make django wizard forms using different templates
I am trying to split one django form to two forms with two different templates. So after googling I found that the solution is using wizard form. Here is my code: in view.py: FORMS = [("0", postform_1stpage), ("1", postform_2ndpage)] TEMPLATES = {"0": "myapp/postform_1stpage.html", "1": "myapp/postform_2ndpage.html"} class ExampleWizard(SessionWizardView): instance = None file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'image')) def get_template_names(self): return [TEMPLATES[self.steps.current]] def get_form_instance( self, step ): if self.instance is None: self.instance = Post() #model instance return self.instance def done(self, form_list, **kwargs): """ Save info to the DB """ post = self.instance post.save() return HttpResponseRedirect('home') def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.method == 'POST': secondform = postform_2ndpage(self.request.POST or None, self.request.FILES or None) firstform = {} if secondform.is_valid(): post = secondform.save(commit=False) post.author = self.request.user post.save() messages.success(self.request, f'Post created!') return redirect('home') else: firstform = postform_1stpage() secondform = postform_2ndpage() context = {'firstform':firstform, 'secondform': secondform} return context and in url.py: `path('create/post/new', login_required(ExampleWizard.as_view([ postform_1stpage, postform_2ndpage])), name='new-post')` and finally in templates: {% block content %} <form method="POST" action="create/post/new#details" enctype="multipart/form-data"> <fieldset class="form-group"> {% csrf_token %} {{ firstform.management_form }} <div class="row justify-content-center"> <div class="card-body"> {{ firstform.categories_one }} </div> <div class="card-body"> {{ firstform.categories_two }} </div> <input class="btn btn-xs … -
Can a single django class inherit/extend both ListView and DetailView
Consider following scenario: I have a multi vendor ecommerce website. I want to render three pages: a vendor list, then product list by each vendor, and then details of each of those products So the first Vendors List is a ListView Second, products by each vendors is a DetailView for previous Vendor ListView, but it is a ListView for next product details DetailView Third view renders product details so is obviously a DetailView Now, my question is, Can number 2 extend both the ListView and DetailView? If yes, how? -
Jquery submit event not firing
I am trying to submit a form using jquery. I am running a Django server. The JS Code and HTML are as follows: document.addEventListener('DOMContentLoaded', function() { // Submit comment form document.querySelector('#comment-form').addEventListener("submit", function(event){event.preventDefault()}); document.querySelector('#comment-form').addEventListener('submit', () => save_comment()); }); function save_comment() { console.log('Save function triggered'); frm = document.querySelector('#comment-form'); data_submit = { updated_comment: frm.querySelector('#comment-editbox').value, month: frm.querySelector('#comment-mth').value, gl_code: frm.querySelector('#comment-gl').value, csrfmiddlewaretoken: jQuery("[name=csrfmiddlewaretoken]").val(), }; console.log('Save function triggered 2'); frm.submit(function (e) { console.log('Submit triggered'); e.preventDefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: data_submit, success: function (data) { console.log("successful"); }, error: function(data) { console.log("failed"); } }); console.log('save ended'); return false; }); } <!-- The Modal --> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <label id="comment-heading">Comments <span id="comment-subheading"></span></label> <form action="{% url 'comment' %}" method="post" id='comment-form'> {% csrf_token %} <textarea id="comment-editbox" name="comment-editbox"></textarea><br> <input type="hidden" id="comment-mth" name="comment-mth" value=""> <input type="hidden" id="comment-gl" name="comment-gl" value=""> <input class="btn btn-primary" type="submit" value="Save" id='comment-save'> </form> </div> </div> "Save function triggered" and "Save function triggered 2" get logged onto the console when I submit the form. But "Submit triggered" does not. The form does get submitted to the server which returns a json response and causes the form to navigate to the response route. I do not want the form to redirect to the response route … -
How does django really handle multiple requests on development server?
I am making a little django app to serve translations for my react frontend. The way it works is as follows: The frontend tries to find a translation using a key. If the translation for that key is not found, It sends a request to the backend with the missing key On the backend, the missing key is appended to a json file Everything works just fine when the requests are sent one at a time (when one finishes, the other is sent). But when multiple requests are sent at the same time, everything breaks. The json file gets corrupted. It's like all the requests are changing the file at the same time which causes this to happen. I am not sure if that's the case because I think that the file can not be edited by two processes at the same time(correct me if I am wrong) but I don't receive such an error which indicates that the requests are handled one at a time according to this and this Also, I tried something, which to my surprise worked, that is to add time.sleep(1) to the top of my api view. When I did this, everything worked as expected. … -
Django datetime field compered to now
Please help. I have this in my models.py class Notificator(models.Model): headline = models.CharField(max_length=255, default='') vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() bought_from = models.ManyToManyField(VigneteSeller, blank=True) start_alert = models.DateTimeField() start_notifying_me = models.IntegerField(default=20) def save(self): d = timedelta(days=self.start_notifying_me) if not self.id: self.start_alert = self.end_date - d super(Notificator, self).save() @classmethod def starter(cls): ready = [] if timezone.now() >= cls.start_alert: ready.append(cls.headline) return ready def __str__(self): return self.headline All I want is to collect all instanceses from "start_alert" field compare it with timezone.now and return it with the starter function, and I am stuck. -
create_user: Unknown Error In Django View
create_user: Unknown error when i use create_user in my user_registery model. my view : def User_Register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['UserName'] Email = form.cleaned_data['Email'] Password = form.cleaned_data['Password'] User.objects.create_user(username, Email, Password) else: form = UserRegisterForm() context = { 'register_form' : form } return render(request, 'accounts/register.html', context) def UserLogOut(request): logout(request) messages.success(request,'You Are Log Out', extra_tags='success') return redirect('accounts:user_login_url') my form : class UserRegisterForm(forms.Form): UserName = forms.CharField(label='', max_length=50, error_messages=messages, widget=forms.TextInput(attrs={ 'class' : 'form-group col-md-0.5', 'placeholder' : 'User Name' })) Email = forms.EmailField(label='', max_length=50, error_messages=messages, widget=forms.EmailInput(attrs={ 'class' : 'form-group col-md-0.5', 'placeholder' : 'Email' })) Password = forms.CharField(label='', max_length=50, error_messages=messages, widget=forms.PasswordInput(attrs={ 'class' : 'form-group col-md-0.5', 'placeholder' : 'Password' })) def clean_email(self): email = self.cleaned_data['Email'] user = User.objects.filter(email=email) if user.exists(): raise forms.ValidationError('your email is correct') else: return email and i use clean_email for use valid email addres. -
Using the URLconf defined in fifteen.urls, Django tried these URL patterns
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ I got error. Using the URLconf defined in vidly.urls, Django tried these URL patterns, in this order: I am getting this error while running manage.py file using command python3 manage.py runserver. Error Using the URLconf defined in fifteen.urls, Django tried these URL patterns, in this order: ^home/$ ^home/search$ admin/ The empty path didn't match any of these. admin.py from django.contrib import admin # Register your models here. apps.py from django.apps import AppConfig class Covid19Config(AppConfig): name = 'covid_19' models.py from django.db import models # Create your models here. tests.py from django.test import TestCase # Create your tests here. urls.py from django.conf.urls import url from covid_19 import views urlpatterns = [ url(r'^home/$',views.greetings), url(r'^home/search$',views.search), ] views.py from django.shortcuts import render from django.http import HttpResponse from selenium import webdriver from selenium.webdriver.common.by import By import matplotlib.pyplot as plt # %matplotlib inline import pandas as pd import time # Create your views here. def greetings(request): res = render(request,'covid_19/home.html') return res def search(request): if request.method == 'POST': state_name = request.POST['search_text'].capitalize() state_code_data = pd.read_csv("state_code.csv") print(state_code_data.head()) state_code = state_code_data.loc[state_code_data['State'] == state_name, 'State_code'].iloc[0] url = "https://www.covid19india.org/state/"+state_code print("state name :",state_name) print("state code :",state_code) print("url :",url) driver = webdriver.Chrome() driver.maximize_window() driver.get(url) time.sleep(6) … -
Setting dynamic label in form field
I have a questionnaire which comprises a list of forms. Each form has only one boolean field. class ModifierForm(forms.Form): applied = forms.BooleanField(label='Trait A', required=True, initial=False) Each time I create a form, I would like to modify the label. In the case above, Trait A is hardcoded. Can this be passed into the form as an argument somehow? Note that the intention is to change the displayed label only. The field name applied remains the same for all form instances. -
TypeError at /admin/auth/user/add/ : __init__() got an unexpected keyword argument 'min_lenght' Django
i have no idea what did i do wrong, I didn't do anything except adding class Userdata(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1) is_voted = models.BooleanField(default=False) def __str__(self):return self.user.username in models. then when i tried to add a new user, that error shows everytime -
API access to user's Google data stored in user's Django profile
I'm trying to build a Django where each user has their own profile page. In their profile page, a user can choose to share Google Postmaster data with my website (see https://developers.google.com/gmail/postmaster/reference/rest). Their choice then gets stored in their profile page. I have been playing around with social-auth-app-django but this does not seem able to only function as an extension (with api access) to an existing django profile - it only seems intended to replace the django profile with a social profile. Does anyone have an idea of how to approach this problem? I guess i'm not looking for exact code, but mainly for some steps and perhaps references to tools that are more fitting for my purpose than social-auth-app-django. Thank you, Jon -
Website without https displays file browser
If I visit my website with https:// it works just fine. However, I noticed if I click on the link I put on Github which doesn't have https:// I am taken to a page that says the following: Index of /  Name Last modified Size Description Apache/2.4.38 (Debian) Server at example.com Port 80 I noticed this is an empty directory which I suspected might be /var/www/html so I added a file to it and confirmed this is showing me /var/www/html. This is strange because I have my Django app under /srv -
Ensure field is unique for another field in Django Models
I want a field in a model to be unique based on another field, but not vice versa. For example: class Shipment(models.Model): supplier = models.ForeignKey("Supplier", on_delete=models.PROTECT, related_name='shipments') external_id = models.CharField(max_length=128) I want that two shipments cannot have same supplier and same external_id, but can have same external_id and different supplier, or same supplier and different external_id. I know unique_together. But it makes a supplier to only have one external_id. However, I want a supplier to have multiple external_ids while all of them are unique. I can check this constraint in save() method, but I want a database constraint, or something wiser. -
formset in django gives extra forms rather than specified?
forms.py class PermissionForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(PermissionForm, self).__init__(*args, **kwargs) roles = forms.Emailfield() views.py def privileges(request): user=request.user count = 4 PermissionFormSet = formset_factory(PermissionForm, extra=count)) inti = [{'roles':'123@gmail.com'},{'roles':'abc@gmail.com'}] forms = PermissionFormSet(form_kwargs={'user':user}, initial=[x for x in inti]) print(len(forms)) I need to create multiple instance of same form,for that I am using formset.I specified extra=2 and I need to pass different initials for different form instances.So practically,it should give me 2 forms but rather it gives 4 forms.Why? -
Random URL with an expiration date (Django)
The idea is to generate a time limited random URL and send it to an unregistered person. what is the proper way to do it? I'm using Django for a few weeks now and have no clue how to perform it. Thanks -
How can implement YouTube auto quality functionality in Reactjs webapp
I want to implement Youtube like auto quality functionality in my web app. I want to break the videos into chunks and deliver it over HTTPS according to the bandwidth of the user like Youtube. I have searched for it and the terms that I encountered are HLS,MPEG-DASH,ffmpeg.What are the ways in which this can be achieved? For example, I found that Video.js can be used to deliver hls but I don't know how to create a .m3u8 file. Also, my backend is made using Django so I can configure my backend too.But here also I don't know how to use ffmpeg. Can I do it with Nginx or apache server? I don't require anything related to the configuration(although it would be helpful if you can provide some).I know the answer can be lengthy but just provide me the path that I can follow to achieve it and not the implementation. The resources that I found relevant to my case are: https://www.youtube.com/watch?v=t8ebB9Pxb2s https://stackoverflow.com/a/41289535/11559079 videojs: Download/stream video in chunks with quality selecton -
Django creating models for multiple stock instruments
I am working on a stock market app for which I am creating models in django Here is an Instrument model class Instrument(models.Model): name = models.CharField(max_length=50) symbol = models.CharField(max_length=10) description = models.TextField() exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) ltp = models.FloatField() ltp_pre = models.FloatField() Now there are total 5000 instruments and each instrument will have ohlc (open, high, low, close) data. Since ohlc data count are large (> 10^7) I decided to create separate table for each instrument, but now in djnago I have to create 5000 models. class Instrument1(models.Model): timestamp = models.DateTimeField(primary_key=True) open = models.FloatField() high = models.FloatField() low = models.FloatField() close = models.FloatField() volume = models.IntegerField() Is there any other way to do it. Also open to the idea of using different databse. -
how to upload products from Django admin?
Hi I am somewhat intermediate in django and I had a really important question regarding my project (don't have code because I need guidance regarding its development). I want to be able to upload products from django admin and make it show up on the user's side, now I know how to do that but how do I make it dynamic so that each product can be purchased using stripe (automatically assign price to stripe, etc...user can press buy etc.. I really need guidance and code and any help is greatly appreciated thank you -
How to display a model object only for a specific time on the webpage in Django?
I am trying to build a webapp using django framework . Below is my code for the "models.py". from django.db import models class Client(models.Model): SEX_CHOICES = [('M', 'Male'), ('F', 'Female')] fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) mailid = models.EmailField(max_length=100) sex = models.CharField(max_length=1, choices=SEX_CHOICES, blank=True) age = models.IntegerField() items_onsale = models.ManyToManyField('Sinfo', blank=True) def __str__(self): # for displaying the variable correctly. return self.fname, self.lname , self.mailid, self.sex, self.age, self.items_onsale class Sinfo(models.Model): # data of items put on sale by clients iname = models.CharField(max_length=100) idesc = models.TextField(max_length=300, null=True) def __str__(self): # for displaying the variable correctly. return self.iname What I am trying to achieve is , display a specific instance from the object from the model , say "iname" from Sinfo , for 1 min and then display next one . Like display item name BOOK for a min and then display next item CYCLE . I am able to display a single item but without any timer. I have been looking for possible options , like using Javascript or importing timer specific libs for django BUT I am trying to achieve it using just python logic but not quite sure how things will work among the views , forms , urls scripts … -
How to integrate mixpanel to django backend
I am new with integrating mixpanel to Django backend to track events,As i try to track, it gives me empty brackets anyone with ideas or resources please help me am quite stack views.py from django.shortcuts import render from django.views import View from rest_framework.generics import ListCreateAPIView from rest_framework.views import APIView from rest_framework.response import Response from .serialize import UserSerializer, TweakSerializer, ChannelSerializer, SubscriberSerializer from tweaks.models import Tweak from accounts.models import User from channels.models import Channel, Subscriber from mixpanel import Mixpanel import json # Create your views here. mp = Mixpanel('TOKEN') class userApi(ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer def get(self, request): queryset = self.get_queryset() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) apiuser=userApi() point = json.dumps(apiuser.__dict__) mp.track(point, 'users') serializers.py from rest_framework import routers, serializers, viewsets from django.urls import path, include from accounts.models import User from tweaks.models import Tweak from channels.models import Channel, Subscriber class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = 'username', 'email', 'first_name', 'last_name', 'date_joined' -
Nginx server returns 404 when refreshing my Django-React-Docker Application
I dockerized my react-django application. The react code is being turned into a static folder and that folder is being served by a nginx server. Everything is working perfectly except for when I reload the page. If I reload the page, I am shown an 404 page. Also, react is not displaying the 404 page when something goes wrong. I am guessing it has something to do with my server configuration. default.config server { listen 80; location / { proxy_pass http://frontend:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /api { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /admin { proxy_pass http://backend:8000/admin; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /nginx-health-check { access_log off; return 200; } } My docker-compose version: "3" services: backend: build: context: ./backend dockerfile: Dockerfile ports: - 8000:8000 volumes: - ./backend:/app - ./backend/media:/app/media - ./backend/static:/app/static frontend: build: context: ./frontend dockerfile: Dockerfile-prod ports: - 3000:80 volumes: - ./frontend/src:/app/src nginx: build: context: ./nginx dockerfile: Dockerfile ports: - 80:80 I got this code from this repo: https://github.com/kasper190/django_k8s/tree/master/code -
Django STATIC FILES location CONFUSION
I've been learning Django for a while now, but the static files topic makes me doubt about WHERE and HOW they should be placed and it's configuration in settings.py. Lets say I start a Django project called "WEBSITE" and create an app called "BLOG". From what I've seen and read, people use 2 different "ways" to place/save their static files (css, images, javascript) and templates. Method #1 (the asterix means "Directory" and dash means its a "file"): In my base.html template I use: {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}" type="text/css"> And on the other templates I used: {% extends 'BLOG/base.html'%} {% load static %} Here is my file structure from what I have read in the documentation: *WEBSITE *BLOG *Migrations *static *BLOG *images -image_01.png -image_02.png *css -style.css *js *templates *BLOG -base.html -index.html -contact.html -about.html -__init__.py -admin.py -apps.py -forms.py -models.py -tests.py -urls.py -views.py *WEBSITE -__init__.py -asgi.py -settings.py -urls.py -wsgi.py -db.sqlite3 -manage.py In the setting.py app, theres only: STATIC_URL = '/static/' and it loads the images and css just fine... That was the method I learned when reading the documentation, but when I watched some youtube tutorials, they used something else, which is the other method#2: Method#2(the asterix … -
how can i get id of one class object, in another class and store in the database - Django
** urls.py file ** from django.urls import path from main import views app_name = 'main' urlpatterns = [ path('', views.home, name='home'), path('submit/', views.submit, name='submit'), path('error-log/', views.error_log, name='error_log'), ] ** views.py file ** from django.shortcuts import render, get_object_or_404, redirect import socket from main.models import Paragraphs, Store_user_para from main.forms import Store_user_para_forms import random global paragraph def home(request): ''' to get the ip of user''' hostname = socket.gethostname() ip_address = socket.gethostbyname(hostname) '''code to pass the pre defined paragraphs to the user ''' paragraphs = Paragraphs.objects.filter(active=True) ''' code to generate random paragraph ''' len_paragraphs = len(paragraphs) number = random.randint(1, len_paragraphs-1) paragraph = get_object_or_404(Paragraphs, id=number) form = Store_user_para_forms() return render(request, 'main/home.html', {'ip_address':ip_address, 'paragraph':paragraph, 'form':form}) def submit(request): if request.method == "POST": try: global paragraph form = Store_user_para_forms(request.POST) data = form.save(commit=False) data.paragraph_Id = request.POST.get('hidden_value', '') data.user = request.user data.save() return redirect('main:submit') except (ValueError): form = Store_user_para_forms(request.POST) print(form) return render(request, 'main/submit.html', {'error':'Bad data passed in. Try again.'}) else: data = Store_user_para.objects.filter() return render(request, 'main/submit.html', {'data':data}) def error_log(request ): return render(request, 'main/error_log.html') ** model.py file ** from django.db import models from django.contrib.auth.models import User # Create your models here. class Paragraphs(models.Model): ''' this class will store the pre defined paragraphs in backend ''' objects = models.Manager() paragraph = models.TextField(blank=False, … -
queryset passes null in django
I am building my first ecom on django, i have a Item model with a category field on the DetailsView i would like to show relate items to the perticular item, for that i tried this. class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) related_items = Item.objects.filter(category=Item.category).order_by('category') context['related_items'] = related_items print(related_items) return context but this does not works it prints: <QuerySet []> can someone please tell me what am doing wrong. -
Field 'id' expected a number but got 'null'. Django
When i tried to run python manage.py migrate to migrate, the terminal show this error : "Field 'id' expected a number but got 'null'." I didn't do anything to the user, all I do I just follow some instruction on the internet and this what happen to my terminal. Here's my model : from django.db import models from django.contrib.auth.models import User # Create your models here. class Fakultas(models.Model): fakul = models.CharField(max_length=50) def __str__(self):return self.fakul class Userdata(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) faculty = models.CharField(Fakultas.fakul,max_length=50) is_voted = models.BooleanField(default=False) def __str__(self):return self.user.username Here is my Form : from django import forms from django.core import validators from django.contrib.auth.models import User from voting_system.models import Userdata class UserForm(forms.ModelForm): class Meta: model = User widgets = { 'username' : forms.CharField(attrs = {'class' : 'form-group'}), 'password' : forms.PasswordInput(attrs = {'class' : 'form-group'}), 'email' : forms.CharField(attrs = {'class' : 'form-group'}), } fields = ('username', 'email', 'password') -
GeoDjango: Getting accurate device location with geoip2
I am trying to get the users device location. But the geoip2 returns a location far away from users location (almost 20km-25km). When I connect my device through a mobile network it shows a different location when I connect my device with the wifi First I am getting the users ip def get_ip(request): xff = request.META.get('HTTP_X_FORWARDED_FOR') if xff: ip = xff.split(',')[0] else: ip = request.META.get('REMOTE_ADDR', None) return ip But this gets the users private ip and the private ip is not in the country or city datasets so the geoip2 throws an error. So I try to get the public ip address through a website def get_ip(request): from requests import get ip = get('https://api.ipify.org').text if ip: return ip Now i use geoip2 to get the users location data def home(request,): .... .... .... .... from django.contrib.gis.geoip2 import GeoIP2 g = GeoIP2() ip = get_ip(request) print(ip) country = g.country(ip) city = g.city(ip) print(country, city) lat, long = g.lat_lon(ip) print(lat, long) ... ... ... Can you please suggest a better way or proper way to get the accurate location of the user?