Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to verify a coupon using django framework and sqlite?
so, my basic idea is when a student enter a coupon provided by his educational institute the system should check if the coupon exists in the database or not and display a message saying the coupon is verified if it is in the data base, but what actually happens is an "errorList" message appears saying that the coupon already exits in the database and my customized message never appears this is my views function def apply_coupon(request): if request.method == 'POST': form = ApplyCouponForm(request.POST) if form.is_valid(): # code_entered = request.POST.get('code') code_entered = form.cleaned_data['code'] is_available = Coupon.objects.get(code=code_entered).exists() is_active = Coupon.objects.get(active=True).exists() if is_available & is_active: messages.info(request, 'Your coupon is verified!') else: messages.info(request, 'Your coupon is not verified!') else: form = ApplyCouponForm() return render(request, 'app/applyCoupon.html', {'form': form}) is_available = Coupon.objects.get(code=code_entered).exists() this line checks if the coupon exists in the databese is_active = Coupon.objects.get(active=True).exists() this one checks if it is active or not if is_available & is_active: i think this condition is never true but i don't know why this is coupon model in models.py # coupons model class Coupon(models.Model): code = models.CharField(primary_key=True, max_length=50, unique=True) active = models.BooleanField() def __str__(self): return self.code this is my html template {% extends 'base_layout.html' %} {% block content %} … -
How to call a function from another py file to a model class in django
I have created a seprated py file that includes multiple functions that i want to use inside a model class in django, the file: a.py contains functions eg. """ code""" def cra_2(lower_threshold, upper_thershold, maximum_cra_payment, market_rent, weekly_income, maintenance): rent_component = weekly_income * .25 weekly_maintenance = (maintenance / 365) * 7 * .25 family_rent = rent_component + weekly_maintenance if family_rent > market_rent and market_rent > upper_thershold: rent_charged = market_rent elif family_rent <= lower_threshold: rent_charged = min(market_rent, family_rent) elif family_rent <= (lower_threshold + 0.25 * (upper_thershold - lower_threshold)): rent_charged = min(market_rent, 4 * (family_rent - 0.75 * lower_threshold)) elif family_rent <= upper_thershold and market_rent > upper_thershold: rent_charged = min(market_rent, (family_rent + maximum_cra_payment)) elif family_rent <= upper_thershold and market_rent < upper_thershold: rent_charged = min(market_rent, 4 * (family_rent - 0.75 * lower_threshold)) else: rent_charged = min(market_rent, (family_rent + maximum_cra_payment)) #Calculate CRA if rent_charged <= lower_threshold: cra_rate = 0.0 elif rent_charged >= upper_thershold: cra_rate = maximum_cra_payment else: cra_rate = (rent_charged - lower_threshold) * .75 import json report = { "rent charged": rent_charged, "cra rate: ": cra_rate, "family rent": family_rent, "given values ":[{"rent_component":rent_component}, {"weekly_maintenance ":float(weekly_maintenance) } ] } return json.dumps(report, indent=2) i want to use this function in a model class, and the input parameter values are … -
Django Error while saving avatar : expected str, bytes or os.PathLike object, not NoneType
there is an error on cleaned_data['avatar'] (in forms.py) : expected str, bytes or os.PathLike object, not NoneType this error appears when I sign in with an image for avatar. I m using Django-allauth but not used to it.... So I add an avatar field which appears in sign_in form but I've the error when submitting. this is my code: models.py from django.db import models from django.contrib.auth.models import AbstractUser def get_path_name(instance, filename): path = 'media/avatar/' name = instance.user.id + "-" + instance.user.email path = path + name return path # custom User model class CustomUser(AbstractUser): avatar = models.ImageField(upload_to= get_path_name, blank=True, null=True) my form: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.core.files.images import get_image_dimensions from django import forms class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username', 'avatar') def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) # validate dimensions max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) # validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, … -
how can i check django user groups in forms
I have a form defined from a model class. Depending from the user group of the logged in user, some fields should be remove if logged in user is not belong from certain group.i have a producer group, if logged in user is not belong form producer group then i want to remove the time_pool field from the forms. my code is showing this error 'NoneType' object has no attribute 'groups' . how can i solve this issue? class ArticleForm(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'content', 'time_pool', ] def __init__(self, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) self.user = kwargs.pop('user', None) if not self.user.groups.filter(name__iexact='producer').exists(): del self.fields['time_pool'] -
send reset password template to gmail, outlook and anothers in django
I am able to send the password reset page and reset the password normally, but only by gmail, if you put EMAIL_HOST = 'smtp-mail.outlook.com' I can send to outlook, but how can I send to all valid emails? (outlook, gmail ...) because like '' smtp-mail.outlook.com '' and 'smtp.gmail.com', I can only send to one or the other, never both EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'emailHere' EMAIL_HOST_PASSWORD = 'passwordHere' EMAIL_USE_TLS = True -
Django model fields get realigned after writing wrong data
in my Django admin panel, whenever I leave a field blank and save it the fields are realigned left to right and vice versa. Can anyone tell me what is the problem and how to fix this. In the below pics 1st pic is when there is no data in the fields. 2nd pic is when i leave a field blank and save it the field has realigned from left to right [ -
how i resolv this error python django project while deploye on heroku
Build failed -- check your build output , when i run command heroku logs then one error come multiple time "Build failed -- check your build output" -
how to count number of connected clients in flask
i need to display the number of connected clients on web page i am using flask-socketio and i write this code for checking connected and disconnected connections. app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) then i render template like this return render_template_string(TABLE_TEMPLATE, data=data, clients=len(clients)) In html part i call like this <h1>{{ clients }} </h1> but on webpage it keep showing 0 even client is connect i get output from client and it is connected it should print 1 2 depends how many clients are connected. even if i print this print(len(clients)) it return 0. this is my full app code. from flask import Flask, request, render_template_string from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app) clients = [] @socketio.on('connect', namespace='/') def connect(): clients.append(request.namespace) @socketio.on('disconnect', namespace='/') def disconnect(): clients.remove(request.namespace) TABLE_TEMPLATE = """ <h1>{{ clients }} </h1> <style> table, th, td { border: 1px solid black; } </style> <table style="width: 100%"> <thead> <th>Client</th> <th>IP</th> <th>Status</th> </thead> <tbody> {% for row in data %} <tr> <td><center>{{ row.client }}</td></center> <td><center>{{ row.ip }}</td></center> <td><center>{{ row.status }}</td></center> </tr> {% endfor %} </tbody> </table> """ @app.route("/device_add", methods=['POST']) def device_add(): name = request.args.get('name') with … -
Pass javascript variables into a {% static "..." %} pathway text
I am trying to create the following array for my server, which serves to preloading the images with given paths: var i = 0; while (face_cursor < faces_gone_through.length) { for(j=0; j<=100; j+=10) { load_images_array.push('{% static "/img/' + faces_gone_through[face_cursor] + '/' + faces_gone_through[face_cursor+1] + '/' + faces_gone_through[face_cursor] + '_' + j + 'P_' + faces_gone_through[face_cursor+1] + '.jpg" %}'); } i++; face_cursor+=3; } face_cursor=1; The code may seem weird, but what i am basically doing is trying to concatenate the given strings and try to create an array of paths. But the concatenation doesn't work and the stirng is parsed as: /static/img/&#x27;%20%2B%20faces_gone_through%5Bface_cursor%5D%20%2B%20&#x27;/&#x27;%20%2B%20faces_gone_through%5Bface_cursor%2B1%5D%20%2B%20&#x27;/&#x27;%20%2B%20faces_gone_through%5Bface_cursor%5D%20%2B%20&#x27;_&#x27;%20%2B%20j%20%2B%20&#x27;P_&#x27;%20%2B%20faces_gone_through%5Bface_cursor%2B1%5D%20%2B%20&#x27;.jpg How can one successfully concatenate this string? -
How to aggregate, that is to get querysets based on a property of a query
My model: class ClinicPermissions(models.Model): id = models.AutoField(primary_key=True, unique=True) clinicid = models.ForeignKey(Clinic, on_delete=models.CASCADE) doctorid = models.ForeignKey(doctor, on_delete=models.CASCADE) viewperm_choices = ( (0, 'Cannot view clinic details'), (1, 'Can view clinic details') ) viewperms = models.IntegerField( choices=viewperm_choices, default=0) editperms_choices = ( (0, 'Cannot edit clinic details'), (1, 'Can edit clinic details') ) editperms = models.IntegerField( choices=editperms_choices, default=0) editdocs_choices = ( (0, 'Cannot edit doctor details'), (1, 'Can edit doctor details') ) editdocs = models.IntegerField( choices=editdocs_choices, default=0) class Meta: unique_together = ["clinicid", "doctorid"] The above model describes permissions of each doctor in a clinic. I need to get a list of doctor objects associated with a Clinic object, which is stored in ClinicPermissions model, as a queryset and pass it to a form. i.e I want to get a specific Clinic. cl = Clinic.objects.get(id=10) Then, I want to get a queryset of doctors from the ClinicPermissions, where clinicid = cl: i.e Something more elegant than the following: perms = ClinicPermissions.objects.filter(clinicid = cl) docs = [] for perm in perms: docs.append(perm.doctorid) return docs Here, docs is a list, but I need a queryset, to pass to a form. -
Deal with django ImageField current value displayed in forms
I'm trying to remove the clear checkbox in Django's ImageField and remove the displayed current value of the file. Tha approach I tried is to replace the widget as proposed here How to not render django image field currently and clear stuff? but the result is that I get ValidationError : "Upload a valid image. The file you uploaded was either not an image or a corrupted image.". Though the validation error the image get's uploaded, but I do not get redirected to the success page and an error is being rendered in the form. What's the recommended way to remove the current value in the ImageField? -
API Resources Collections in Django Rest Framework
I'm wondering how to create laravel-like resources and collections for API in Django using the Django Rest Framework. <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; use App\Http\Resources\User as UserResource; class Post extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'body' => $this->body, 'user' => new UserResource($this->user), 'some-hard-coded-text' => 'Hello World', ]; } } -
Django - How to tertermine content_type in if statement?
I want to find out what content_type I'm about in my function but I'm Unable to reach the "got me" print statement no matter how I design my if statement. I also tried to use pprint to get the naming of the content_type but with no effect till now. def mark_refunded(modeladmin, request, queryset): queryset.update(status=2) transactions = queryset.all() for transaction in queryset.all(): print(transaction) transaction.sender.acc_usd_balance += float(transaction.amount) transaction.sender.save() transaction.receiver.acc_usd_balance -= float(transaction.amount) transaction.receiver.save() print(transaction.content_type) if transaction.content_type == "App | Sell Type A": print("got me") It seems that I'm unable to compare the output of print(transaction.content_type) with the if statement, why that? I would expect that the output is the same value that I ask for at the if statement. -
How to make a list with a comma separated strings?
Here I have string like this. Size:20,color:red,Size:20,color: pink,Size: 90,color:red,Size: 90,color: pink, Now I want to convert into this format [{'Size': '20','color':'red'}, {'Size': '20','color': 'pink'}, {'Size': '90','color':'red'}, {'Size': ' 90','color': 'pink'}] Can we make a list like this ? -
I try to bind the country name state name and city names in the database by using Django
enter image description here enter image description here/lpIu8.jpg -
add avatar in AbstractUser and Django-allauth
My code works fine and I do migration to add avatar to my user. But when I signup, avatar field does not show. this is my code: models.py from django.db import models from django.contrib.auth.models import AbstractUser def get_path_name(instance, filename): path = 'media/avatar/' name = instance.user.id + "-" + instance.user.email path = path + name return path # custom User model class CustomUser(AbstractUser): avatar = models.ImageField(upload_to= get_path_name, blank=True, null=True) my form: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.core.files.images import get_image_dimensions from django import forms class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username', 'avatar') def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) # validate dimensions max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) # validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') # validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are … -
Django: Problem with saving model instances with ForeignKey-relation to database
I would like to create and save model instances with Django. These are my models: class Customer(models.Model): id = models.IntegerField(primary_key=True, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) ... class Order(models.Model): id = models.IntegerField(primary_key=True, unique=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) comment = models.TextField() ... While processing a form, customer will be created: customer = Customer.objects.create( user=user, first_name=storage_space_order["customer_firstname"], last_name=storage_space_order["customer_lastname"], ) As far as I've learned, Django will save the object on calling create as well. Now, I would like to create my order object Order.objects.create( customer=customer, comment=data["customer_comments"], ... ) While saving, I get the following error message: save() prohibited to prevent data loss due to unsaved related customer What I don't get; customer is already there and saved in the database. There are no changes on the customer in between. Also, I've tried customer_id=customer.id/pk, - but both ID and PK return None. Why is this and what do I need to change? Loading the object again is not the preferred way, as I only got the ID which marks it as unique. Thanks for your input :) -
How can i, from a simple form, insert many values into the database in Django?
I have a simple form, like this: <form method="post"> {% csrf_token %} {{ add_boat.non_field_errors }} <div class="form-group"> {{ add_boat_type.name.errors }} <label for="{{ add_boat.name.id_for_label }}">Type</label> <input type="text" name="{{ add_boat.name.html_name }}" class="form-control" placeholder="Ex. Suspekt" value="{{ name.value }}" id="{{ add_boat.name.id_for_label }}"> </div> <div class="form-group"> <input type="hidden" name="{{ add_boat.added_by.html_name }}" id="{{ add_boat.added_by.id_for_label }}" value="{{ user.id }}"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Add"> </div> </form> where one of the form groups handles a name. The other one is hidden and is for adding what user added this specific entry (this can probably be done in a better way in my model or my view...). But my question is: do i need a hidden form group for every value I want to enter into the database? If i don't include the hidden form group above I get an error saying that that field can not be empty per the database definition (null = 0). I would idealy like to insert a lot of data into the database based on only the name from the form. My form class looks like this: class BoatForm(ModelForm): class Meta: model = Boat fields = [ 'name', 'added_by' ] and my iew looks like this: if(request.user.is_authenticated): add_boat_form = BoatForm(request.POST … -
NotImplementedError: `create()` must be implemented
When i pass the serializer data in postman then it's throwing this error: raise NotImplementedError('create() must be implemented.'). If anyone could figure out where i made any wrong....would be much appreciated. thank you so much in advance. serializers.py : class EditProfileSerializer(Serializer): gender = CharField(error_messages={"required": "gender key is required", "blank": "gender is required"}) profile_visibility = CharField(error_messages={"required": "profile_visibility key is required", "blank": "profile_visibility is required"}) avatar = CharField(allow_blank=True,) token = CharField(allow_blank=True, read_only=True) #some logic goes here... return data def update(self, validated_data): gender = validated_data['gender'] profile_visibility = validated_data['profile_visibility'] avatar = validated_data['avatar'] user_profile_obj = UserProfile( gender = gender, profile_visibility = profile_visibility, avatar = avatar if avatar else None, ) #user_profile_obj.create() user_profile_obj.save() payload = jwt_payload_handler(user_profile_obj) token = jwt_encode_handler(payload) validated_data['token'] = 'JWT' + str(token) return validated_data views.py : class EditProfileAPIView(UpdateAPIView): serializer_class = EditProfileSerializer model = UserProfile permission_classes = (IsAuthenticated,) def update(self, request, format=None): data = request.data profile_serializer = EditProfileSerializer(data=data) if profile_serializer.is_valid(): profile_serializer.save() new_profile = new_profile.data return Response({'success':'True','message':'Profile Updated Successfully', 'data':new_profile}, status=HTTP_200_OK) else: return Response({"message":profile_serializer.errors}, status=HTTP_400_BAD_REQUEST) -
Django Social Authentication Create New User With Custom Model
I'm trying to develop a Facebook social authentication feature on an application that uses a custom Django user model and django-rest-framework-social-oauth2 as the social authentication package. My custom user model is called 'Account' and it inherits from the AbstractBaseUser class. The Account model is shown below: class Account(AbstractBaseUser): # Account model fields: email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # The user will log in with their email instead of username: USERNAME_FIELD = 'email' # Required fields when registering, other than the email: REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] # Telling the Account object how to use the account manager: objects = MyAccountManager() The function that handles creating a new user is called 'create_user' and is defined within my custom written MyAccountManager class which extends the Django BaseUserManager class. This is given below: class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): # Checking to see if correct function parameters have been passed in: if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have … -
How to use sekizai's addtoblock tag inside a form widget template
I am writing a custom form field which has a custom widget. The widget needs some static assets. Its template looks like this: {% load sekizai_tags static %} <div id="myWidget"> ... </div> {% addtoblock "css" %} <link rel="stylesheet" href="{% static 'my_app/css/widget.css' %}">{% endaddtoblock %} {% addtoblock "js" %} <script src="{% static 'my_app/js/widget.js' %}"></script>{% endaddtoblock %} However, this doesn't work. I get: You must enable the 'sekizai.context_processors.sekizai' template context processor or use 'sekizai.context.SekizaiContext' to render your templates. I guess this is because the form (and widget) has no access to the request object?! Is there a way around this? I found in the sekizai source a mention of SekizaiContext as... An alternative context to be used instead of RequestContext in places where no request is available. ... but I can't figure out how exactly I would do that. Note that I do not want to start passing the request around. This would not be an acceptable solution, as my custom field is meant to be reusable; it should just work in any form without further modifications. -
how to design a user based DB system in django
I am working on a Django system that lets multiple individual users store the same type of files and related data. for now, I am storing the user Id in the individual related tables. (i.e) table =>User(id,name,password,email) table =>File(id,url,User.Id) but now I need to store its related data, in few other tables.(i.e) table =>FileInfo(id,File.id,desc,otherInfo) so now when I query the FileInfo table from a user's login, it is fetching info of all the files(i.e all records) since there is no hold in the table. it is also not feasible to store user.id in all the tables, (maybe in the future it may grow to tens or hundreds of table) so kindly suggest me(design change that can to retrieve the current user data alone or any django functionality that supports this use case or any Django package that helps to achieve it) how can I get the data that pertains to the current logged in user without explicitly storing the userid in every table. -
How to restrict overlapping datetimes in django model at DB level using CheckConstraint
I have the following fields in my Model: class Event(models.Model): starts = models.DateTimeField() ends = models.DateTimeField() I want to restrict overlapping dates (starts, ends). I have managed to do this in model validation, but now I want this enforced at database level such that an IntegrityError exception is thrown if an insert happens outside the model's save method. My Validation was as follows: ... def clean(self): if self.starts and self.ends: if self.__class__.objects.filter( models.Q(ends__gte=self.starts, starts__lt=self.starts) | models.Q(ends__gte=self.ends, starts__lt=self.ends) | models.Q(starts__gt=self.starts, ends__lt=self.ends) ).exists(): raise ValidationError('Event times overlap with existing record!') This works. Say an event starting 2020 Oct 11 @ 19:00, and ending 2020 Oct 11 @ 20:00, the following values will prompt an overlap: same date, starting @ 18:00, ending @ 21:00 same date, starting @ 19:30, ending @ 19:50 same date, starting @ 19:30, ending @ 20:50 But there are situations where the model's .clean() method will not be invoked, which may result in invalid data to be inserted. My question is, how can I enforce a constraint on the model, which will apply on the database itself, like unique_together does. I have used postgres specific fields like DateRangeField but in this case, their functionality is limited as they can … -
Google authentication using django-rest-auth and allauth
I am trying to create an authentication API for a flutter app that will log users in with a google authentication signup/login form. I followed this tutorial to achieve this. So far so good, except that the tutorial is based on a GitHub sign in rather than Google. I managed to get it working up till step "connecting" step. I am able to get the code from the redirect but when I access http://127.0.0.1:8000/auth/google/ I see it's asking for a two fields (access_token, code). When I try to just post with the information I do have I get the following error: "non_field_errors": [ "View is not defined, pass it as a context variable" ] -
How to user AJAX call to django DeleteView or CreatView or UpdateView?
class RegisterUser(CreateView): template_name = 'new_register.html' form_class = SignUpForm success_url = '/' def form_valid(self,form): user = form.save() password = form.cleaned_data.get('password') user.set_password(password) user.save() return JsonResponse({'url':reverse_lazy('accounts:dashboard')}) This is my CreateView and I want to return the redirection URL when the form submitted. I want to handle this URL in AJAX