Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a filesystem path using Django and JavaScript
I have a server built with Django listening on 127.0.0.1, everything is local and on the same machine (same file system). My client needs to communicate a folder’s path to the server so that the server can launch a script to manipulate what is in that folder. How would I go on about making a GUI in the browser to get that path? I have seen a similar question asked here and the answer suggests that the server exposes the file system in some way so that the client can choose a folder. I understand that this is pretty much the only way to go on about this, but I fail to find a simple implementation of this idea. What I have in mind requires many interactions between the client and the server to update the path as the user progresses in the fs hierarchy. -
Python+Django : I cannot see my rendered data in checkout but I am able to see it in other pages
I have this code: {% for items in items%} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>${{item.product.price}}</p></div> <div style="flex:1"><p>x {{item.quantity}}</p></div> </div> {% endfor %} checkout.html I do not seem to be able to render out the information in checkout.html, but I did so in cart.html using the same code. Views.py: from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_Cart_total' : 0, 'get_cart_items' : 0} context = {'items' : items, 'order' : order} return render(request, 'store/cart.html', context) def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_Cart_total' : 0, 'get_cart_items' : 0} context = {'items' : items, 'order' : order} return render(request, 'store/checkout.html', context) models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete = models.CASCADE) name = models.CharField(max_length = 200, null = True) email = models.CharField(max_length = 200, null=True) def __str__(self): return self.name class … -
Saving data after non-Django Form submission
I have a payment form that is made up of various elements. Here my problem is that the card for a new stripe user isn't registered until after form submission. I know that if my form has a newly added Address, I can use form.is_valid() but that doesn't apply if my address is one that is saved already. But is there a way I can set the card using stripe.PaymentMethod.list after the form is submitted, regardless of if the Django form is part of it? form <form method="POST" id="subscription-form" data-secret="{{client_secret}}"> {% csrf_token %} <label class="block uppercase text-gray-600 text-xs font-bold mb-2">Payment Details</label> {% if payment_methods %} <div class="form-check my-3 bg-gray-200 p-2 rounded-md"> <input class="form-check-input" type="radio" name="payment-methods" id="add-new-card" value="add-new-card" onclick="addCard()" {%if payment_methods %} {%else%}checked="checked" {%endif%} required> <label class="form-check-label" for="add-new-card"> Add new payment method </label> <div id="new-card" style="display: none;"> <label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name"> Name on Card </label> <input id="cardholder-name" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150" value="{{customer.name}}" detype="text"> <!-- placeholder for Elements --> <label class="block uppercase text-gray-600 text-xs mb-2" for="card-element"> Card Details </label> <div id="card-element" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"> … -
How do I merge data of two objects in Django REST Framework
So let's say I have this 2 models Poll: class Poll(models.Model): title = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Options: class Option(models.Model): title = models.CharField(max_length=255) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) def __str__(self): return f'{self.poll.title} - {self.title}' These two objects are connected with ForeignKey. Now let's say I have a frontend that renders both options and the question (title of the poll) but I only want make a single API call to the backend. Basically I need the API to looked like this: { "title": "Which is the best frontend framework?", "options":[ { "id": 1, "title": "React" }, { "id": 2, "title": "Vue" }, { "id": 3, "title": "Angular" } ] } How what method/technique should I use to merge two objects like this? -
Registered User can't login with credentials django rest framework
The issue i've got is my login endpoint wont permit me to login with authenticated users for unkown reasons Here is my serializers.py file class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id','first_name','last_name','email','is_seller','date_joined'] extra_kwargs ={ 'password':{'write_only':True} } def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance Here is my views.py for Login class LoginAPIView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] print(email) print(password) # since email is unique use first() user = User.objects.filter(email=email).first() print(user) if user is None: raise exceptions.AuthenticationFailed(f'User {email} not found') if not user.check_password(password): raise exceptions.AuthenticationFailed(f'Incorrect Password') return Response(UserSerializer(user).data) Now when i do try to login the and given user i get this error below from post man { "detail": "Incorrect Password" } And these are my logs below Forbidden: /api/sellers/login/ [15/Jul/2021 21:50:30] "POST /api/sellers/login/ HTTP/1.1" 403 31 I've been unable for hours to figure out why exactly register users can't sign in and also i am using a Custom user model and in my settings.py file the Rest_Framework is set to AllowAny...Thanks in advance for any help... -
Faster Django filter querying for very large database
I am creating a geospatial web app and have a very large database, at the moment it is 7.5 million entries long and will be almost 60 million entries long by the time all the data is uploaded. I want to display all the points from a certain date and am simply using Model.objects.filter(datetime__date=requested_date) at the moment. Each date request takes ~8s to load. How can I filter in a more efficient way? If there are better ways to store geospatial data points, I would greatly appreciate any advice! -
django-admin-tools-stats : Reverse for 'admin-charts' not found. 'admin-charts' is not a valid view function or pattern name
just installed django-admin-tools-stats. gives me the following error: Reverse for 'admin-charts' not found. 'admin-charts' is not a valid view function or pattern name. what do I do? -
NOT NULL constraint failed: core_question.poll_id error
I'm stack on problem with POST method in Django. Core Idea of the project to make Polls, in polls add questions, and for each question to add Answers. I did make all of that. And i have few APIs working: GET: http://127.0.0.1:8000/poll/ Showing all created polls in database GET: http://127.0.0.1:8000/poll/{poll_name}/ // poll_name -> Weather (for example) Showing all questions, all answers and correct answer POST: http://127.0.0.1:8000/api/token/ Providing authorization Token if admin credentials are correct. (username: Admin, password: admin) But now I need APIs for add, remove, update Polls, Questions and Answers. I did try it for Questions first: class Questions(APIView): def get(self, request, format=None, **kwargs): question = Question.objects.filter(poll__title=kwargs['topic']) serializer = QuestionSerializer(question, many=True) return Response(serializer.data) def post(self, request, format=None, **kwargs): serializer = QuestionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) But i'm getting error: NOT NULL constraint failed: core_question.poll_id error I did try to search it in Internet and its says that i'm not requesting proper parameter's. I did try 100 variations and still cant find what is the problem. This is Github link for project: https://github.com/NeoVic2006/Polls_with_questions_answers Please check it and let me know where is the problem. PLEASE be specific since i'm not really experienced in Django. Thank … -
Problems with marking djangoo option select labels
I'm a student who is learning how to do a funeral. We are having a hard time in the process of indicating the option value of the product. What I want is for one option label to pop up and the option_value to come underneath it in order, but it's showing up like this. There are currently two options: green, blue, and red under the color, and S, M, and L under the size. How can we solve this? option.html <form method="get" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row"> <label for="value_code" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-5" style="margin-left: -56px"> <select type="text" class="form-control" name="value_code" id="value_code" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <optgroup label="{{option.name}}"> <option value="{{value.value_code}}">{{value.name}} (+원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> </div> models.py # 옵션(옵션코드, 옵션명, 상품코드(fk)) class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name # 옵션값(옵션값코드, 옵션값명, 옵션코드(fk), 상품코드(fk)) class Value(models.Model): value_code … -
I am using DRF, My view returns an empty response but my blog is adding successfully i want my serializer data
I am using DRF, My view returns an empty response but my blog is adding successfully i want my serializer.data. My models.py file: from django.db import models from django.utils import timezone from datetime import datetime from .validators import validate_allfile_extension from restfapp.models import User class Blog(models.Model): title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.DateTimeField(default=datetime.now) image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title My serializers.py file class AddBlogSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=128, write_only=True, required=True, error_messages={'blank': "Please provide title"} ) author = serializers.CharField(max_length=128, write_only=True, required=True, error_messages={'blank': "Please provide author"}) description = serializers.CharField(max_length=128, write_only=True, required=True, error_messages={'blank': "Please provide description"}) image = serializers.FileField(write_only=True, required=True, error_messages={'invalid': "Please upload image, video or audio file"}) class Meta: model = Blog fields = ["title","author","description","image",] My views.py file @api_view(['GET', 'POST']) # @parser_classes([MultiPartParser, FormParser]) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def add_blog(request): if request.method == 'POST': serializer = AddBlogSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id=request.user.id) data = {'result': 'success', 'message': serializer.data} return Response(data=data, status=201) elif not serializer.is_valid(): data = { 'result': 'error', 'message':serializer.errors} return Response(data=data) My json response: { "result": "success", "message": {} } I want to get serializer.data I know if i assign like this blog=serializer.save(user_id=request.user.id) then print(blog.id) it … -
Why not use "runserver" for production at Django?
Everywhere i see that uWSGI and Gunicorn are recommended for production mode from everyone. However, there is a lot more suffering to operate with it, the python manage.py runserver is more faster, simpler, and the logging is also more visible if something goes wrong. Still, why not recommend the "python manage.py runserver" command for live production? -
Django Filter by date and status
my first question here, I've been looking around but couldn't find a solution. I am building a reservation system, my models are class Room(models.Model): number = models.IntegerField() beds = models.IntegerField() capacity = models.IntegerField() category = models.ForeignKey( RoomCategory, on_delete=models.CASCADE, blank=True, null=True) class Booking(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, blank=True, null=True) check_in = models.DateField() check_out = models.DateField() status = models.IntegerField(blank=True, null=True) if request.method == 'POST': no_disponible = "No hay habitaciones disponibles, selecciona otras fechas" if form.is_valid(): room_list = Room.objects.filter(category=1).exclude(booking__check_in__lt=form.cleaned_data['check_out'], booking__check_out__gt=form.cleaned_data['check_in'], booking__status__gt=0) I am changing status when the customer confirms so I want to check if dates are available when status is not 1 (I change status to 1 once the payment is approved. However booking__status__gt=0 doesn't seem to work here, any help is welcome! -
how do i sum the userinput
give me the erro in that pic all i want is when people input the Macros i wantit sum all of that make a total count def index(request): macros = Macros.objects.all() goals = Goals.objects.filter(user=request.user) count = Macros.objects.values('calories', 'protein','carbohydrates','fats') sum = 0 for c in count: sum += count[c] print(sum) return render(request, 'macro/index.html', {'macros': macros,'goals':goals,}) class Macros(models.Model): name= models.CharField(max_length=100) calories= models.FloatField(max_length=10) protein=models.FloatField(max_length= 4) carbohydrates= models.FloatField(max_length= 4) fats= models.FloatField(max_length=4) goals = models.ForeignKey(Goals, on_delete=models.CASCADE) [enter image description here][1] -
On Popup on Folium marker, how to define a push button to show some data about that point
So, I have hundreds of marker points on a Folium map. By clicking, I open the popup. On the popup, there is a push button that marked more info!. By clicking the more info, I would like to see the data related to that specific point in that URL down the map box. I am using Django, Folium and MongoDB. Can you help me or give any keyword in this regard? Thank you -
How to build a path in my templates file for Django
right now in my Django settings file for my project i am trying to build a path to so I can display my templates/projects/index.html file. Can I get help solving this? # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent and in my TEMPLATES dictionary I have this is DIRS `TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'projects/templates'), ],` -
why my cli give an error when I pushing my app?
I'm deploying an app on Heroku. I have created a heroku account I have installed heroku CLI I have created a requirements.txt file I have specified the Python Runtime. I have modified settings.py for Heroku I have made the procfile to start processes. I'm using git to track the project's files. I have done the committing the project. And when I want to do the pushing to heroku with the command git push heroku master I have this error in the terminal: error: src refsoec master: no concuerda con ninguno error: falló el push de algunas referencias a 'https://git.heroku.com/quiet-wildwood-34710.git' Someone knows the solution? Thanks -
ModuleNotFoundError: No module named 'rest_framework.authentications'
When I run python manage.py migrate command, I am having the following error: ImportError: Could not import 'rest_framework.authentications.SessionAuthentiation' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'rest_framework.authentications'. Rest-framework-related parts of my code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd party 'rest_framework', 'rest_framework.authtoken', # Local 'posts.apps.PostsConfig', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentications.SessionAuthentiation', 'rest_framework.authentications.TokenAuthentication', ], } I am reading and going along with Django for APIs by W. S. Vincent. -
How to calculate Future date in django using another column data?
I have a column that has different dates, and I wanna make a new column with this column value + some period and get the future date in another column for each object How can I write that in Django models? -
Cant install python packages SSL certificate issue
Hi I have python version 3.9.6 installed and pip version 21.1.3. And I'm trying to run py -m pip install Django and I get the following errors: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)'))': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)'))': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)'))': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)'))': /simple/django/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)'))': /simple/django/ Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)'))) - skipping ERROR: Could not find a version that satisfies the requirement … -
How to change the display format of date in a DateTime field in Django?
Im using the django date picker widget with this in forms.py: class DateInput(forms.DateInput): input_type = 'date' and using this on the meta class in the modelForm: widgets = { 'birthdate': DateInput(format=('%Y-%m-%d'),) } at first without the format argument on the DateInput widget it just didnt work, now it works but the date is shown in the field with the format 'mm/dd/YYYY' and I want it to be shown with the format 'dd/mm/YYYY'. Ive tried with the different localization variables on settings.py, this is my current configuration: LANGUAGE_CODE = 'es-MX' TIME_ZONE = 'America/Hermosillo' USE_I18N = True USE_L10N = True USE_TZ = True DATE_INPUT_FORMATS = ('%d/%m/%Y', '%d-%m-%Y') the widget works right and the date value is correctly read and saved but i cant get it to be shown with the correct format on the input -
Updating account info error in UserUpdateForm
I am having a hard time figuring out what's wrong with my UserUpdateForm, I am not able to update the first_name and last_name field, but when i take out the those fields and then leave username and email it works well and uses can actually update their username and email, but somehow the firstname and lastname wouldn't just allow for me to make update to it. Can someone help me please ? class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ( 'username','email', 'first_name','last_name', 'profile_pic','hide_email', ) #widgets ={ # 'gender':forms.Select( #attrs={'class':'custom-select md-form'}), # } def clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.exclude(pk=self.instance.pk).get(email=email) except User.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_username(self): username = self.cleaned_data['username'] try: account = User.objects.exclude(pk=self.instance.pk).get(username=username) except User.DoesNotExist: return username raise forms.ValidationError('Username "%s" is already in use.' % username) def clean_first_name(self): first_name = self.cleaned_data["first_name"] try: account = User.objects.exclude(pk=self.instance.pk).get(first_name=first_name) except User.DoesNotExist: return first_name raise forms.ValidationError('UserFirstname "%s is already in use.' % first_name ) def save(self, commit=True): account = super(UserUpdateForm, self).save(commit=False) account.username = self.cleaned_data['username'] account.first_name = self.cleaned_data['first_name'] account.email = self.cleaned_data['email'].lower() account.profile_pic = self.cleaned_data['profile_pic'] if commit: account.save() return account My account edit view. def edit_account_view(request, *args, **kwargs): if not request.user.is_authenticated: return redirect("login") user_id = … -
how to add string to primary key in django model
i want my id to be "ssid"+ (autoimcrement id) example: ssid001 this is my user model class User(models.Model): id = models.CharField(primary_key=True, editable=False, unique=True, max_length=99999) phone = models.CharField(max_length=12, unique=True,default="") name = models.CharField(max_length=50,default="") email = models.EmailField(max_length=50,default="") -
Run a .ipynb file on clicking a web page button
I have written a python code that converts pixel values from a thermal camera to thermal image. I need this process to happen on clicking a button on a web page( just a button saying "start converting" or so). Please help! -
getting manager isn't available , auth.user has been swapped error in Django?
Note Tried everything available on stackoverflow for solution but my error is not resolved my models.py class User(AbstractUser): is_student = models.BooleanField('student status', default=False) is_creator = models.BooleanField('content creator status', default=False) class Classroom(models.Model): name = models.CharField(max_length=31) standard = models.PositiveSmallIntegerField( choices=STUDENT_STD, null=True, blank=True) division = models.CharField(max_length=3, null=True, blank=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # ExamSlot = models.ForeignKey(ExamSlot, on_delete=models.CASCADE) name = models.CharField(max_length=40) my view from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ObjectDoesNotExist from django.db import IntegrityError from django.shortcuts import get_object_or_404, render, redirect from rest_framework import exceptions, generics, permissions, status from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.views import APIView from .serializers import * from .models import Student from .forms import SignUpForm from rest_framework_simplejwt.tokens import RefreshToken, AccessToken from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from django.contrib.auth import get_user_model User = get_user_model() def user_register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm # from django.contrib.auth.models import User from django.contrib.auth import get_user_model User = get_user_model() class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, … -
How to send data from React Js to Django without using Django Rest API
Is it possible to send data from ReactJs to Django without using Rest API ? I have an app through which I've sent form data for registrations and got data from the database using the Django REST API but this time, I need to send some data that are not related to the database meaning I shouldn't need a serializer but is it possible ? Data (Json) from ReactJs { payment_data: { command_id: order._id, price: order.TotalPrice }, data: { return_url: "xxxxxxxxxx", cancel_url: "oooooooooo", shop_code: 1, }, } On Click (of a button on the front-end) I would like to send this data to django for further processing but I don't know how I could possibly do that without using Django Rest API