Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How TO Get live data of NSE stocks of all symbols in python/Django
How TO Get live data of NSE and BSE stocks of all symbols in python/Django? I am looking for this so that I can eventually filter it a look at what stock I need to concentrate and also to get an experience in Python Programming. It Would Be Great If I Could Know: The Best API to get Live Stock Details From NSE And BSE. Any Resources Associated Anymore Suggestions ¯_(ツ)_/¯ Thank You, You Can Contact Me Through Evan Thomas - LinkedIn -
Django Date and time issue. Server ahead of timezone
I was working on an app and I can't solve the issue of date and time. In setting.py file I have set the timezone to UTC. TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True I live in UTC+05 so when I publish a blog the date and time is 5 hours into the future so the blog can only publish after 5 hours. Is there a way to automatically detect the time zone of users to either add or subtract hours relative to UTC or anything that can automatically solve this issue. models.py class blog(models.Model): blog_text = models.CharField(max_length=1000) pub_date = models.DateTimeField("date published") def __str__(self): return self.blog_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = "pub_date" was_published_recently.boolean = True was_published_recently.short_description = "Published recently?" -
I want to create a set of buttons (answers to the questions) in Django, how should I do this?
I want to create a quiz site with a selection buttons, it should contain answer and two buttons with answers on em. When new user would open this quiz every button should be inactive, and once he would select one of answers then it should be active (and sent to the database), he could then return to this page and see his answers and change the answers whenever he wants. I want to do this without submit button (every answer should save after clicking). Here's my code: models.py class InterestQuestion(models.Model): q_id = models.AutoField(primary_key=True) question = models.CharField(max_length=255) answer1 = models.CharField(max_length=64) answer2 = models.CharField(max_length=64) class UserInterest(models.Model): q_id = models.ForeignKey(InterestQuestion, on_delete=models.CASCADE) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) selectedInterest = models.CharField(max_length=64) views.py @login_required def select_interests(request): questions_data = InterestQuestion.objects.all() if request.method == 'POST': questionnaire_form = InterestSelectionForm(request.POST, request.user) if questionnaire_form.is_valid(): new_val = questionnaire_form.cleaned_data.get("userAnswer") #answered = questionnaire_form.save() #new_entry = UserInterest.objects.create(select_interests = answered) else: questionnaire_form = InterestSelectionForm() return render(request, 'quiz/quiz_form.html', locals()) quiz.html <form action="." method="post"> {% for q in questions_data %} <ul> <li>{{ q.question }}</li> </ul> {% csrf_token %} <input type="button" class="userAnswerButton" value="{{ q.answer1 }}"> <input type="button" class="userAnswerButton" value="{{ q.answer2 }}"> {% endfor %} </form> I don't know If I should use forms.py in this case, but I'll paste it … -
Redirect URI Mismatch in django
error: redirect_uri_mismatch error_description: redirect_uri did not match any client's registered redirect_uris My redirect uri in OneLogin is 1 -
is it possible to build an app with scrapy without using command line interface?
I am building an app for scraping data from other sources, however, the URL would be entered by the user on a web page, and currently, I am using BeautifulSoup and Selenium to achieve the data and it is extremely slow. How this app will work? The user will visit the website, for example, example.com, and enter the URL in a form, which he/she wants to scrap. Now the problem is how I can achieve the desired result via Scrapy programmatically using Django views. Is it possible? thanks -
how to send OTP to phone number in Django?
I need to verify the phone number while submitting the form(no need to login and register). I am using the Twilio service. Please suggest to me How can I do this. I need to send OTP to the user by filling the number in the form afterward verify then submit the form. Thanks in advance! My Model: class Booking(models.Model): date = models.CharField(max_length=200,blank=True, db_index=True, null=True ) time = models.CharField(max_length=200,blank=True, db_index=True, null=True ) name = models.CharField(max_length=200,blank=True, db_index=True, null=True ) email = models.CharField(max_length=200,blank=True, db_index=True, null=True ) product = models.CharField(max_length=200,blank=True, db_index=True, null=True ) phone = models.IntegerField(max_length=200,blank=True, db_index=True, null=True ) address = models.TextField(max_length=200,blank=True, db_index=True, null=True ) My view import os from twilio.rest import Client from django.shortcuts import render, get_object_or_404, redirect from .models import Product,Technician,FAQ, Booking account_sid = '*******************************' auth_token = '********************************' def booking(request,slug=None,pk=None): products = get_object_or_404(Product,slug=slug) if request.method == 'POST': date = request.POST['date'] time = request.POST['time'] name = request.POST['name'] email = request.POST['email'] product = request.POST['product'] phone = request.POST['phone'] address = request.POST['address'] client = Client(account_sid, auth_token) message = client.messages \ .create( body="Join Earth's mightiest heroes. Like Kevin Bacon.", from_='+********', to=phone ) data = Booking(date=date, time=time, name=name, email=email, product=product, phone=phone, address=address,message=message) data.save() print('Booking Done') return redirect('home') else: return render(request, 'book.html', {'product' : products}) -
How to prevent Django to initialize "prod" DB before test DB
I'm using Django for the backend of my project and I'm currently writing tests. The thing is when I use the command python manage.py test, it first loads my actual DB before creating the test DB. The problem is that on DB initialization, I have some processes that do stuff with the App Registry (in my software you can install/uninstall apps while Django is running). So when I use the test command, it loads my App Registry from my local DB, then it creates the test DB but it seems to be using the same App Registry (since it uses the same settings when it starts). So I have tests that fail because things are already done in the App Registry (because of my local DB), that shouldn't be. So when I do python manage.py test, the output is : I do this : print("DB : ", connection.settings_dict['NAME']) somewhere to show you DB : my-db Creating test database for alias 'default'... System check identified no issues (0 silenced). .DB : test_my-db ..... ...tests are executed... .... Is there any setting that I could use to tell Django : "Hey, I'm using the test command, do not load my local DB … -
How to create an "login page" with Laravel or Django?
I'm starting to create a homepage-application that has a login page. I'm familiar in both Python and PHP, but have not used any frameworks. Do you recommend to use Django (Python) or Laravel (PHP)? Is there some ready code for creating Login pages? They don't have to be free. -
Pick the hidden value from the form that is clicked on - jQuery Djano Ajax
How to pick the hidden value from the form that is clicked on. I have many similar forms and all have a similar field, but values are different. I want to pick up the value numbers shown here to submit the form as a jquery ajax request. <div id="mydiv"> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="1"> </form> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="2"> </form> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="3"> </form> <form name="myForm" action="comment.php" method="post"> <input type="hidden" name="indexvalue" value="4"> </form> </div> $(document).on('click', '#mydiv form', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: "/updatedb", data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'indexvalue': $(this).parent("form value").val() }, success: renderSuccess, dataType: 'HTML', error: function (result) { $('#successdiv').empty(); alert('Verify the input, or refresh the page'); } }); }); -
How can I user ordering filter in Django rest framework 3.1~
I want to user ordering filter, so import filters. ... from rest_framework import filters But I kept getting errors. from django.db.models.sql.constants import ORDER_PATTERN ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants So I searching, then I saw this posting(https://www.gitmemory.com/issue/encode/django-rest-framework/7458/668618981) The ORDER_PATTERN has been removed in Django 3.1, But I want to use ordering filter. How can I use this? I use Djnago 3.1.4, drf 3.11.0 -
Django don't run the collectstatic command anymore when I upload an image from admin
I'm currently developing a Django application. I have a static-res folder that contains all my static data. In production I'm starting the generation of the "static" folder with the collectstatic command. So far everything works. From the admin part I come to import images manually with ImageField, so each time I have to run the collectstatic command... I'd like to be able to import an image in production, without having to run the command each time. Here is my code in the settings : MEDIA_ROOT = os.path.join(BASE_DIR, 'static-res/images') STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = 'static/images/' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static-res'), os.path.join(BASE_DIR, 'static-res/images'), os.path.join(BASE_DIR, 'static/images'), os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static-res/js'), ] and in my urls.py file : ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I really can't find a solution so if anyone can help me I thank you! -
Can a Django ManyToManyField contain multiple different Model classes? How would I order it?
I'm building a List model that I want to be able to contain and order various different other model types. class Parent(models.Model): title class Child(models.Model): parent = ForeignKey(Parent) order text class Meta: ordering = ['order',] class List(models.Model): list_items = ManyToMany??? How can I set it up so that a List can contain both Parent and Child models? (And also have a List contain other List models for that matter?) And while I can order Child models for a Parent on the Child level (i.e. child.order), how could I order Parent, Children, and List list_items for a List? -
nginx connet to .sock failed (13:Permission denied) - 502 bad gateway
I am using nginx + uwsgi + django to deploy my very first site on centos7. They worked fine separately in test but I got a 502 bad gateway trying to connet them all together. The /var/log/nginx/error.log file says 2020/12/29 15:52:05 [crit] 1150#0: *1 connect() to unix:/run/uwsgi/site.sock failed (13: Permission denied) while connecting to upstream, client: IPaddress, server: mysite.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/site.sock:", host: "IPaddress" I have tried these but none of them managed to fix the problem: 1.moving the site.sock file from my project base directory to /tmp/site.sock, or according to this tutorial, to /run/uwsgi/site.sock. 2.changing the site.sock file permission from 664 to 666. 3.chown socket file to myuser:nginx, and add myuser to nginx group. 4.running nginx and uwsgi with a www-data user by setting user = www-data in nginx.conf and uid = www-data,pid = www-data in site_uwsgi.ini. 5.turning off selinux by setenforce 0, or doing setsebool -P httpd_can_network_connect 1. ps aux | grep nginx: root 1148 0.0 0.0 39296 1972 ? Ss 15:41 0:00 nginx: master process /usr/sbin/nginx nginx 1150 0.0 0.1 39640 2056 ? S 15:41 0:00 nginx: worker process ps aux | grep uwsgi: root 1322 0.0 0.1 54680 3068 ? Ss 15:49 0:00 … -
Problems with django installation
I have a problem with installing django in my venv. When I try to run pip install django inside my venv, I get the following error: ERROR: Could not install packages due to an EnvironmentError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect data check')) -
NGINX Docker on Server with pre-existing NGINX
I am currently running into an issue with one of my projects that will be running in Docker on my Ubuntu Server with a NGINX docker container to manage the reverse proxy for the Django Project. My issue I am running into is I already have previous Django projects running on that particular Ubuntu server so port 80 is already being used by a NGINX block running on the actual server. Is there a workaround to running my Docker NGINX as well as the Ubuntu NGINX and have my docker image run as a "add on" site because the Django sites hosted there are clients websites, so I would prefer to not interfere with them if I dont have to. My project needs HTTPS because it is serving data to a React-Native app running on Android APK 28 which for some reason has a security rule that blocks non HTTPS connections from happening in the app. If anyone else has run into an issue like this I would gladly appreciate the advice on how to tackle this issue. I have tried running NGINX in Docker with port 81 instead of port 80 and that works perfectly, but I dont think … -
how to save registred users in django
here is my form.py file. from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class register_form(UserCreationForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta(): model = User fields = ('username','email') here's my models.py file: from django.db import models from django.contrib.auth.models import User # Create your models here. class profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField() bio = models.TextField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) joined_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username here's views.py file: from django.shortcuts import render,HttpResponseRedirect from .forms import register_form from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from .models import profile # Create your views here. def register(request): if request.method == "post": register = register_form(request.post) if register.is_valid(): register.save() newUser=User(username=request.POST['username'], email=request.POST['email'], password=request.POST['password']) newUser.save() new_profile = profile(user=newUser, first_name=request.POST["first_name"], last_name=request.POST["last_name"]) new_profile.save() return render(request,'users/success.html') else: register = register_form() return render(request,'users/register.html',{"register":register}) here's the urls.py file: from django.urls import path,include from . import views urlpatterns = [ path('register/',views.register,name="register"), ] and here's the register.html file: {% extends 'users/base.html' %} {% load crispy_forms_tags %} <title>register</title> {% block content %} <div class="container-fluid"> <h1>instagram clone</h1> <p>register to view images and videos fo your friends</p> <form method="post"> {% csrf_token %} {{register|crispy}} <input type="submit" value="register"> </form> </div> {% endblock %} the django … -
are there any clever ways to save files with Web socket in Django?
I have built chatting site and I'm thinking that I can add the function of sending files besides message. But it seems that web socket can't send files or images. My solution is that when file is sent, I use api and then fetched messages and files are reordered by timestamp. But if there are better ways to achieve this, I really want to know. So, my question is Is it possible to send files by web socket and get them by WebsocketConsumer? Is there any ways to combine those two processes? (ex. you send provisional link of files and store them as FileField? ) model from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Contact(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='contact_user') friends = models.ManyToManyField('self', blank=True, related_name='friends') def __str__(self): return self.user.name class Message(models.Model): contact = models.ForeignKey(Contact, related_name='message', on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.contact.user.name class File(models.Model): contact = models.ForeignKey(Contact, related_name='file', on_delete=models.CASCADE) file = models.FileField() timestamp = models.DateTimeField(auto_now_add=True) class Chat(models.Model): participants = models.ManyToManyField(Contact, related_name='chats') messages = models.ManyToManyField(Message, blank=True) files = models.ManyToManyField(File, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) def last_30_messages(self): return self.messages.order_by('-timestamp').all()[:30] def __str__(self): return "{}".format(self.pk) I don't know what information is needed to figure this out, … -
Django migrations for docker container
I have been trying to resolve an issue i am having currently, but i have not found any adequate solution neither here or elsewhere, so i was hoping someone here might have an answer. I have gotten to a point where i know what the problem is but not how to resolve it. Basically i have a website running django/postgres/nginx, it runs smoothly and i can make new models and migrate them, but if i try to add a field to the model: from django.db import models class project(models.Model): project_name = models.CharField(max_length=50) author = models.CharField(max_length=30, blank=True, null=True) date_created = models.DateField() #Added in second round of migrations #Description = models.CharField(max_length=150,blank=True, null=True) What i would normally do is initially build and spin up my container sudo docker-compose -f docker-compose.yml up --build And within my entrypoint file i run makemigrations and migrate. The first round it works well, but if i add the Description field to my model, spin down and rebuild the container to allow the new field to be included in my container, the new container is build without the initial migration, and isntead with a new migration. This results in any previous postgres tables not getting the new field added … -
How to add a field to an existing model
I would like to extend and override the fields existing in the User model, which is found in "django.contrib.auth.models" (The model is already created). I first attempted to create a Foreign-Key and a One-to-One relationship between the User model, and a Client model (in which I added the extra fields), but I don't think it is good practice. How could I directly add and override fields within the User model and not have to create another class model to extend it. from django.contrib.auth.models import User class Clients(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) #client = models.OneToOneField(User, on_delete=models.CASCADE) cell = models.PositiveIntegerField (blank=False) address = models.CharField(default = "Sandton, JHB", blank = False, max_length=132) -
Using django template variables in a JavaScript file
I want to use the template variables in javascript file which is linked to the template. For eg. <!-- The template --> <h1>{{ user.username }}</h1> <script src="{% static 'profile_page/js/index.js' %}"></script> // The script file (a different file) console.log('{{ user.username }}'); -
Django registration profile
I am new in django. I would like to create registration profile. I found some code but it doesn´t work for me. When I want to makemigrations I always get this error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.User' I read that I could fix it with User = get_user_model() but it looks it is doesn´t work for me. My models.py import random from django.contrib.auth import get_user_model from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver User = get_user_model() def code_generator(length=5): numbers = '0123456789' return ''.join(random.choice(numbers) for _ in range(length)) class RegistrationProfile(models.Model): code = models.CharField(default=code_generator, max_length=5) user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='registration_profile', primary_key=True) @receiver(post_save, sender=User) def create_registration_profile(sender, instance, **kwargs): profile, created = RegistrationProfile.objects.get_or_create(user=instance) if created: profile.save() serializer.py from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.password_validation import validate_password from .models import User class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], … -
Is there a way to check client in Django server without user authentication?
So I'm trying to build a Django application which provides each user with some contents but only limited to three times each day. For sake of convenience, I'm not thinking of creating/using any pre-existing user model or authentication. But since I have to limit the number of contents shown to each user, I have to tell if the current request is from the same person or not. I can think of enabling this in the front-end using local storage, cookie, etc. (Neglecting security issue or others, since this is just a toy project.) But I'm wondering if there is a way to do this in the back-end without using user authentication. Any ideas? Thank you very much in advance :) -
Static css in Django works unstable
I have css with following content in ecommerce/ecommerse/static/scc folder: body {background: #68951c;} h1 {color: #000000;} When i want to change the color of background, it changes in PyCharm, but it isn't changes on the web page even when i change a color in BOTH 1) ecommerce/static/scc and 2) ecommerce/ecommerse/static/scc manually. Even though command "python manage.py collectstatic" had run and server had re-run it is needlessly. Only one effect - when I ctrl+X following string in html page: <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> then background evaporates. And when i insert the upper markup and refresh page, it appears again (upper markup contained in , in it is not working for some reason) -
Serve Voice files in Django
I want to serve voice files in the Django app and let users play and have all features like youtube. Voice files are in large size, and the client should not wait for all file to play, and they can move in all voice time and play any part they want -
How to check validation on two fields in a form?
Need to add an image to the form either by entering a link to the image, or upload a file from your computer. If no options were entered when the form was submitted, or both options were entered, an error message should be displayed. And after successful loading, you should get to the image page. models.py: class Picture(models.Model): url = models.URLField(blank=True, verbose_name='Ссылка на изображение') image = models.ImageField(upload_to='pictures/%Y/%m/%d', width_field='image_width', height_field='image_height', blank=True, verbose_name='Изображение') image_width = models.IntegerField(default=0, blank=True, verbose_name='Ширина изображения') image_height = models.IntegerField(default=0, blank=True, verbose_name='Высота изображения') is_active = models.BooleanField(default=True, verbose_name='Актуальность изображения') created = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата создания записи') updated = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата ред-ия записи') views.py: def add_picture(request): picture = Picture.objects.filter(is_active=True) if request.method == 'POST': form = PictureCreateForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() return render(request, 'add_picture.html', locals()) else: messages.error(request, 'Ошибка, проверьте данные') else: form = PictureCreateForm() return render(request, 'add_picture.html', locals()) forms.py: class PictureCreateForm(forms.ModelForm): class Meta: model = Picture fields = ('url', 'image') urls.py: urlpatterns = [ path('', views.home, name='home'), path('add_picture/', views.add_picture, name='add_picture'), path('picture_detail/<int:id>/', views.picture_detail, name='picture_detail'), ]