Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Money withdraw System got IntegrityError in OnetoOneField. All Works ok for first time then gets error
Three tables in my model.py - Account, withdraw, taxDetails. I have a filed total amount(total_amnt_WoP) in the account table. Scenario is, When I will try to withdraw an amount, it will reduce the total amount and also reduce some tax from it (10% of withdraw amount) and it will be saved in taxDetails table every time. I was trying to store total tax in the table. In my case, It works fine (save the tax in taxDetails table) for the first time withdraw. But when I was trying to withdraw in second time, it gets IntegrityError.(IntegrityError at /account_balance/withdraw/, UNIQUE constraint failed: account_balance_taxdetails.user_id) When I delete all the objects from withdraw table( withdraw.objects.all().delete() ) or taxDetails( taxDetails.objects.all().delete() ) table it works fine.But Only for the first time. So what can be the solution? here is my models.py file: class Account(models.Model): purchase_amnt=models.FloatField() ref_amnt=models.FloatField() prantic_amnt=models.FloatField() middle_amnt=models.FloatField() ehp_amnt=models.FloatField() esp_amnt=models.FloatField() incentive_amnt=models.FloatField() user=models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) total_amnt_WoP= models.FloatField() class withdraw(models.Model): account=models.ForeignKey(Account, on_delete=models.CASCADE) user=models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) prev_amnt=models.FloatField(blank=True, null=True, default=0) current_amnt=models.FloatField(blank=True, null=True, default=0) adjast_amnt=models.FloatField(blank=True, null=True, default=0) requisation_amnt=models.FloatField(blank=True, null=True, default=0) total_cashout_amnt=models.FloatField(default=0) transaction_id=models.CharField(max_length=100,blank=True, null=True) status=models.BooleanField(default=False) #purchase percentage prev_pur_tot=models.FloatField(blank=True, null=True, default=0) cashout_pur_tot=models.FloatField(default=0) current_pur_tot=models.FloatField(blank=True, null=True, default=0) created_at=models.DateTimeField(auto_now_add=True) modified_at=models.DateTimeField(auto_now=True) class taxDetails(models.Model): withdra=models.ForeignKey(withdraw, on_delete=models.CASCADE, null=True) user=models.OneToOneField(User, null=True, on_delete=models.CASCADE) tax_prev=models.FloatField(default=0) tax_curr=models.FloatField(default=0) tax_amount_tot=models.FloatField(default=0) tax_id=models.CharField(max_length=100) tax_pay_date=models.DateTimeField(auto_now=True) … -
Display all Employees with present and absent status
I Have Two models User Model and DailyPresent model with user as foreign_key in DailyPresent model. class DailyPresentReport(models.Model): PRESENT = 'present' ABSENT = 'absent' ON_LEAVE = 'on_leave' PRESENT_CHOICES = ( (PRESENT, 'Present'), (ABSENT, 'Absent'), (ON_LEAVE, 'On Leave'), ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='daily_present_report') present = models.CharField(max_length=10, choices=PRESENT_CHOICES, default=ABSENT) punch_in = models.DateTimeField(null=True, blank=True) punch_out = models.DateTimeField(null=True, blank=True) date = models.DateField(null=True, blank=True) work_time = models.DurationField(null=True, blank=True) class Meta: ordering = ['id'] def __str__(self): return f'{str(self.user)}: {self.present}' Now I want to display a table with all users with Present and Absent Fields. Please help me.. Thanks in advance -
Greater than Index in Django
In Django-3.2 class Index get a positional argument expressions which allows to create functional indexes on expressions Is it possible to create index on Integer field with expression greater? For example My model: class Product(models.Model): description = models.CharField(max_length=50) delivery_date = models.DateTimeField(null=True) quantity = models.IntegerField(validators=[MinValueValidator(0)]) Usually I have a filter (quantity>0). How to create expression index on that? -
Django: Not able to clickable url
What I have done is I have shown all models in one view. With this logic: def cylinderListView(request): cylinder=CylinderEntry.objects.all().values('cylinderId','EntryDate','gasName','Status','Availability','issuecylinder__userName','issuecylinder__issueDate','returncylinder__returnDate') return render(request,'entry/cylinderList.html',{'cylinder':cylinder}) And in my cylinderList template, I set cylinder as clickable URL which redirects me to cylinderDetailPage, it was working fine until I have added values in cylinderListview How do I get cylinderId clickable url after this query? -
getting erroe when connecting postgresql to django applicaion as User warning
C:\Users\DELL\AppData\Local\Programs\Python\Python38\lib\site-packages\environ\environ.py:637: UserWarning: Error reading C:\Treato\salon-end\django-api/.env - if you're not configuring your environment separately, check this. warnings.warn( No changes detected -
My ReactJS/Django(Rest API) prompts an Unhandled Promise rejection when I browse from a different PC on the LAN
I can see the frontend form though, but if I try to submit the console would show: "Fetch API cannot load http://localhost:8000/api/task-create/ due to access control checks." and the next line is: "Failed to load resource: Cannot establish connection with the server." This is what I see on my PC, (no problem with this every function works perfectly) And this is what I get on a different PC connected to the same LAN I think it has something to do with headers and CORS, Django REST Framework Authentication, I have tried it all but it doesn't seem to work. Any hints? This is my settings.py: Django settings for todoapp project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-whh5g$8**@u4t1m%13=c$6!k-5#o0jwhr&&7i7^d$ky%$ku+ls' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # … -
Django - 'ManyRelatedManager' object is not iterable
In this specific part of my Django project, I am trying to return a query set of objects that I have filtered through. I converted them to a query set and checked it using .type()(which returned an error saying 'QuerySet' object has no attribute 'type' so it seems to be the right data type). Below is my code: In views.py def shows_in_category(request, category_slug): category = get_object_or_404(Category, slug=category_slug) print(category_slug) shows = theShow.objects.filter(category__name=category).all() print(shows.type()) return render(request, 'show/show_list_view.html', {'shows': shows}) In models.py class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse("theshowapp:shows_in_category", args=[self.slug]) class theShow(models.Model): english_name = models.CharField(max_length=400) show_type = models.CharField(max_length=200, blank=True) category = models.ManyToManyField(Category) slug = models.SlugField(max_length=400,unique=True) class Meta: verbose_name_plural = 'Shows Series' def __str__(self): return self.english_name What can I do to make it so that I return a QuerySet that can be used in the templates that they are passed to? -
Images in Django Forms
I know the django ImageField is used to upload images in forms. I'm looking for something similar, but instead of uploading an existing file, the image comes from a new camera capture. Basically a field to display a live camera field. -
AttributeError in Django
I want to get objects from the model in views and display a form but the code is showing 'WSGIRequest' object has no attribute 'author' error.`enter image description here enter image description here -
Django restframework serializer relation get foreignkey field
How to get using DRF get another table's field using foreign field. My Model 1 class Teacher_lesson_price(models.Model): id = models.AutoField(primary_key=True) teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=False) subject_id = models.ForeignKey(Subject, related_name='subject_name_rel', on_delete=models.CASCADE, null=False) course_id = models.ForeignKey(Course, on_delete=models.CASCADE , null=False, default=None) price = models.CharField(max_length=250) Model 2 class Subject(models.Model): id = models.AutoField(primary_key=True) subject_name = models.CharField(max_length=255) course = models.ForeignKey(Course, on_delete=models.CASCADE) my serializers class getSubjectall(serializers.ModelSerializer): class Meta: model = Subject fields = '__all__' class getSubjectApi(serializers.ModelSerializer): subject_name = getSubjectall(read_only=True) class Meta: model = Teacher_lesson_price fields = ['id', 'teacher_id', 'subject_id', 'course_id', 'price', 'subject_name'] i tried like this and many others too example: using related_name to my getSubjectApi serializer with different type of serializers.fields subject_name_rel = serializers.ReadOnlyField(source='Subject.subject_name', read_only=True) still not working. View @api_view(['GET']) def subjectApiView(request): teacherLessonPrice = Teacher_lesson_price.objects.filter(teacher_id = request.user.teacher.id) serializer = getSubjectApi(teacherLessonPrice, many=True) return Response(serializer.data) Please help me where i gone wrong. I need result like this(similar). How can i do this. [ { "id": 29, "teacher_id": 14, "subject":{ "subject_id": 1, "subject_name": "Math" }, "course_id": 3, "price": "10000" }, { "id": 30, "teacher_id": 14, "subject":{ "subject_id": 2, "subject_name": "English" }, "course_id": 1, "price": "20000" }, { "id": 31, "teacher_id": 15, #if other teacher login "subject":{ "subject_id": 1, "subject_name": "Math" }, "course_id": 1, "price": "20000" }, ] sorry for … -
how can i store data created in a website dynamically to database?
I was thinking about creating a todo website were each user can create their own to-do list and when they click on save, the data should be stored in the database were they can access the history when they re-login. The Listview will contain several date where they can see past to-do data. I am not getting how i can store this data associated with each user -
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fb2bc245668>": user is no longer logged in
I am trying to make a post as a logged in user but I get this instead: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fb2bc245668>": "Post.created_by" must be a "User" instance. ```' I suppose what's happening is that the user is no longer logged in when I change to another so how can I keep the users logged so that they can post? I do get the token back when I log in but it seems like the token is not kept anywhere. THese are the serializers: class UserLoginSerializer(serializers.ModelSerializer): """ User Login Serializer """ username = serializers.CharField( required=True, write_only=True, ) token = serializers.CharField( allow_blank=True, read_only=True ) password = serializers.CharField( required=True, write_only=True, style={'input_type': 'password'} ) class Meta(object): model = User fields = ['id','username', 'password', 'token'] def validate(self, data): username = data.get('username', None) password = data.get('password', None) if username and password: user = authenticate(request=self.context.get('request'), username=username, password=password) if not user: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg, code='authorization') else: msg = "Must include username and password." raise serializers.ValidationError(msg, code='authorization') data['user'] = user return data class PostSerializer(serializers.ModelSerializer): """ Post Serializer """ replies = serializers.SerializerMethodField('get_replies') class Meta: model = Post fields = ['category','title','body','created_at','replies'] extra_kwargs = {'created_by': {'read_only':True}} def get_replies(self, obj): serializer = PostRepliesSerializer(Post.objects.filter(reply_to=obj), … -
django multi tenancy single login page
I'm working on a small project using Django / Multi Tenants package, and I would like to know how can I let all my tenants(users) to log in via one login page instead of differents subdomains like tenant1.domain.com & tenant2.domain.com -
how to send confirmation to new email when user change his email and save it - django
I have an option that allows a user to change email in his profile but without confirming a new email so when user enters a new email I want confirm the email to save it in his profile I am using UserCreationForm (my django version is 2.2) models.py : from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() my code | forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), name='emailchange'), ] html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input … -
Converting time in %H:%M:%S:%f of 83 days, 17:02:10.401369 python
I need to convert time format of '83 days, 17:02:10.401369' to %H:%M:%S:%f res_time = '83 days, 17:02:10.401369' res_formated = datetime.strptime(res_time, "%H:%M:%S.%f") Value Error: time data '83 days, 17:02:10.401369' does not match format '%H:%M:%S.%f' -
Is TechSmith Discount Code work properly?
Yeah, Sure It is real and reliable TechSmith Discount Code with one of the best features and services. In the market that software is at the pick. -
Django template update without refreshing
I am trying to print sensor reading coming from esp8266 to Django's database in a template. I need the data to be shown in the template without refreshing the page to get new values. This the views, urls and the template codes class SensorReading(ListView): model = Sensor template_name = "sensor.html" urlpatterns = [ path("", index, name="index"), path("/reading", SensorReading.as_view(), name="reading"), ] <body> <ul> {%for reading in object_list reversed%} <li><p>{{reading.SensorType}}</p></li> <li><p>{{reading.Reading}}</p></li> <li><p>{{reading.Time}}</p></li> {%endfor%} </ul> -
why Django asks for csrf_token in GET request?
I tried to send a GET request from the HTML form. But I am getting the error "CSRF verification failed.". And When I add csrf token( {% csrf_token %} ), It redirects me to the same page, But it should redirect to confirm.html. here is html code, doctor.html <form method="GET" action="{% url 'confirm' value.name %}"> {% csrf_token %} {% comment %} <h4>Appoint No: {{ value.id }}</h4> {% endcomment %} <div class="appoint_name"> <span class="appoint_spn">Name: </span> <span class="appoint_spn">{{ value.name }}</span> </div> <div class="appoint_name"> <span class="appoint_spn">Email </span> <span class="appoint_spn">{{ value.email }}</span> </div> <div class="appoint_name"> <span class="appoint_spn">Specialites</span> <span class="appoint_spn">{{ value.specialites }}</span> </div> <div class="appoint_name"> <span class="appoint_spn">Duty TIme: </span> <span class="appoint_spn">{{ value.duty_date_start }} - {{ value.duty_date_end }}</span> </div> <div class="appoint_button"> <input class="btn" type="submit" value="Make An Appointment"> </div> </div> </form> My path confiquration in url.py path('confirm/<str:name>/',views.confirmappointment, name='confirm') And here is views.py def confirmappointment(request, name): doctor_name = name userid = request.session['userid'] username = request.session['username'] value = Appointment.objects.create(patient_name=username, patient_id=userid, doctor_name= doctor_name) value.save() return render(request, 'doctor/confirm.html') -
Custom User Register Problem (NOT NULL constraint failed: mainaccount_myuser.password)
I changed the user model for a custom user model. Drop all migrations and deleted db.sqlite3 files. The model was working fine. I can register users through the admin page, but when i go to from creating the user, to change my user and finishing the registration process, this error pops up: (NOT NULL constraint failed: mainaccount_myuser.password) how can i finx this error? admin.py: from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model MyUser = get_user_model() class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('email', 'date_of_birth', 'full_name') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = MyUser fields = ('email', 'password', 'full_name', 'date_of_birth', 'is_active', 'is_admin') class UserAdmin(BaseUserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email', 'full_name', 'date_of_birth', … -
NOT NULL constraint failed: backend_post.created_by_id: logged in user not being registered
I'm getting this error when I try to make a Post. I understand that the issue seems to be that there's no user being registered in the created_by field but I did log in before trying to make a post. So how can I solve this? I don't want to create a post without a registered user writing it so how do I do this if my code is not working? These are the models: from django.db import models, transaction from django.conf import settings from django.contrib.auth.models import BaseUserManager, AbstractUser from django.utils.encoding import force_bytes class UserManager(BaseUserManager): @transaction.atomic def create_user(self, email, username, password=False): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def get_by_natural_key(self, username): return self.get(username=username) def create_superuser(self, username, password, email): user = self.create_user( username=username, email=email, password=password, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name= 'username', max_length= 50, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return str(self.username) class Category(models.Model): """ Category """ name = models.CharField('Name', max_length=200) … -
How to show my pagination bootstrap inside a div in HTML, That acts in JavaScript function?
I want to add pagination bootstrap to my show-posts Div, but because on my JavaScript function I Have document.querySelector('#show-posts').innerHTML = "" - it doesn't show my bootstrap How can I show my bootstrap pagination and also reset the innerHTML of shows-posts every time? index.js function load_posts(){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#load-profile').style.display = 'none'; document.querySelector('#posts-view').style.display = 'block'; document.querySelector('#show-posts').style.display = 'block'; document.querySelector('#post-form').onsubmit = function() { compose_post(); } fetch('/posts/all_posts') // url with that API .then(response => response.json()) .then(all_posts => { // Loop and show all the posts. console.log(all_posts) all_posts.forEach(function(post) { // loop to loop over each object build_post(post) }); }); document.querySelector('#show-posts').innerHTML = "" } HTML <div id ="show-posts"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"><a class="page-link" href="#">Previous</a></li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"><a class="page-link" href="#">Next</a></li> </ul> </nav> </div> views.py def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() paginator = Paginator(all_posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return JsonResponse([website_post.serialize() for website_post in page_obj], safe=False) -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about
error is when http://127.0.0.1:8000/about Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: The current path, about, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. projets mysite urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('mainapp.urls')), ] main app urls.py from django.urls import path,include from . import views urlpatterns = [ path('',views.home), path('about',views.about), path('contact',views.contact) ] views.py from django.shortcuts import render,HttpResponse def home(request): return render(request,"index.html") def about(request): return render(request,"about.html") def contact(request): return render(request,"contact.html") templates/about.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document1</title> </head> <body> <h1>Mahabir pun</h1> <p>he is a great person he is a doing grat</p> </body> how to solve please help me i am in trouble for 2 days -
Django Api ReadOnlyField [duplicate]
I was wondering what the source part of a ReadOnlyField actually does. Thanks poster = serializers.ReadOnlyField(source = 'poster.username') -
Requiring checking checkbox during in custom Django sign-up form
Im preparing customized Django registration form. I need adding two checkboxes that are required (RODO consent and consent for using images). How to declare in Django that this checkboxes must be checked before form could be send? Form is based on model and it looks like this: Models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'),max_length=50) last_name = models.CharField(_('last name'),max_length=150) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) RODO_consent = models.BooleanField(default=False) image_consent = models.BooleanField(default=False) marketing_consent = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email','password1','first_name','last_name','RODO_consent','image_consent','marketing_consent') -
Why this function has a TypeError?
when I want to print order detail as PDF file it give the following: The error: admin_order_pdf() got an unexpected keyword argument 'order' the function: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('orders/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order.id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + 'css/pdf.css' )]) return response