Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Image not uploading in Django Form
I'm trying to create form with an image upload functionality, but it doesn't seem to work. When I select the upload button, it actually selects the image. But when I try to submit the form, it keeps asking me to upload an image. Please, I need someone to help me as soon as possible. Thanks. This is my models.py file. # models.py company_logo = models.ImageField(upload_to='logos/') This is my views.py file. # views.py from django.shortcuts import render, redirect from .models import Opening from .forms import CreateOpeningForm def create(request): form = CreateOpeningForm(request.POST, request.FILES) next = request.GET.get if form.is_valid(): form.save() if next: return redirect(next) return redirect('/') context = {'form': form} return render(request, 'openings/create.html', context) This is my forms.py from django import forms from .models import Opening class CreateOpeningForm(forms.ModelForm): class Meta: model = Opening fields = ( 'title', 'category', 'type', 'restriction', 'application_link', 'description', 'company_name', 'company_hq', 'company_statement', 'company_logo', 'company_website', 'company_email', 'company_description', 'plan' ) This is my create.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mt-8"> <h1 class="text-gray-700 mb-2">Logo <span class="text-red-500">*</span></h1> {{ form.company_logo }} </div> </form> This is my urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('op/', include('openings.urls')), … -
Can not use "import os "in settings.py(Django3)
I know Django changed import os configuration to path system. but I need to import os configuration in Django 3 based project.so I try to import import os in the settings.py file but I got an error. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: In Django 3 from pathlib import Path BASE_DIR = Path(file).resolve().parent.parent in Django 2 import os ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) -
AbiWord: [file path/ test] is not a valid file name?
Working on document conversion from docx, doc to pdf. Get to know about Abiword which can convert documents from one file format to others. Using python with the os module which supposes to execute my command. This is working properly files with no spaces files but whenever there is a file with spaces it is giving this error. Tried to print command and checked is it right or wrong, But the command is right. def saveDocx(files, user): destination = Path.joinpath(MEDIA_ROOT, user, "trash") current_doc_files = list() for file in files: fs = FileSystemStorage(location=destination) filename = fs.save(file.name, file) filename = os.path.join(destination, filename) current_doc_files.append(filename) print("doc files---->", current_doc_files) return current_doc_files, destination def convToPdf(current_doc_files, user): current_pdf_files = list() for file in current_doc_files: cmd = "abiword --to=pdf {}".format(file) print("----cmd----", cmd) try: os.system(cmd) pdf_file_name = os.path.splitext(file)[0] + '.pdf' print("converted ", pdf_file_name) current_pdf_files.append(pdf_file_name) except Exception as ex: print("--------Exception--------") print(ex) return current_pdf_files creating web app on pythonanywhere, They have provided Abiword word processor. Have a look to output on When a file with no space doc files----> ['/home/trash/test.docx'] **2020-11-08 06:10:20 ----cmd---- abiword --to=pdf /home/trash/test.docx** 2020-11-08 06:10:21 Failed to connect to Mir: Failed to connect to server socket: No such file or directory 2020-11-08 06:10:21 Unable to init server: Could … -
ModuleNotFoundError ModuleNotFoundError: No module named 'account'
I have added facebook authentication to my django app, but when I click on the Login with Facebook button, I get this error: ModuleNotFoundError: No module named 'account' I have an app called accounts, and it is in my INSTALLED_APPS section of the settings.py Here is my login.html template: {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% else %} <p>Please, use the following form to log-in. If you don't have an account <a href="{% url "register" %}">register here</a></p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Log-in"></p> </form> <p><a href="{% url "password_reset" %}">Forgotten your password?</a></p> </div> <div class="social"> <ul> <li class="facebook"> <a href="{% url "social:begin" "facebook" %}">Sign in with Facebook</a> </li> <li class="twitter"> <a href="#">Login with Twitter</a> </li> <li class="google"> <a href="#">Login with Google</a> </li> </ul> </div> {% endblock %} I am using the default django login view. Where is the error? -
Check if model instance exists
This thread here describes how to assign None if Model.objects.get() does not exist, using from django.core.exceptions import ObjectDoesNotExist If I want just want to check if some_instance exists in the below code, what is the best way (without importing the librabry ObjectDoesNotExist)? Thanks. some_instance=SomeModel.objects.get(name=some_name) -
NoReverseMatch at /blogs/ 'post' is not a registered namespace
I have started a project with an app called Post with the purpose of making a Blog and after finishing it, I understood the importance of choosing an accurate name for each app so I decided to start a new application and call it blog but now I am trying to fix the errors of name changing. So I fixed all errors except on which I don't know its source: NoReverseMatch at /blogs/ 'post' is not a registered namespace I am not sure if it has to do with the Project's url urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), .............] Blog app urls.py app_name = 'blog' urlpatterns = [ path('', views.home, name='home'), path('blogs/', PostListView.as_view(), name='post-list'), path('blog/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('new_blog/', PostCreateView.as_view(), name='post-create'), ] views.py def home(request): return render(request, 'blog/directions.html') class PostListView(ListView): model = Post template_name = "blog/post_list.html" ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 5 class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" class PostCreateView(CreateView): model = Post fields = ['title', 'content'] success_url = '/' template_name = 'blog/post_form.html' # <app>/<model>_<viewtype>.html def form_valid(self, form): return super().form_valid(form) Models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) ........................................ def __str__(self): return self.title What have I done wrong? -
Save creator for objects created in the Django admin panel
I want to create a few objects directly in Django's admin panel, and in that object automatically save the username of the administrator that have been creating it. Any suggestions of how to do this in the easiest way? Cheers, Peter -
Django - Creating and update interval of function after which function executes
Problem - In a django project of PIZZA cafe. After user ordered pizza , I scheduled a function which will execute after certain interval (say x seconds) to inform user that pizza is now ready to be delivered. But if pizza is ready to be delivered at less than x seconds, How do I update the interval of scheduled function?? I need to identify each and every timer object uniquely so that I can edit or delete a timer object and schedule a function with new interval