Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stuck with reverse lookup for getting dates of each course in django 2.2
I am building a form that has a radio button, of course, and dropdown of dates on which course would take place. Should look like the image shown below Model.py class CourseModel(models.Model): """ Name and Id for each course conducting """ id = models.CharField( primary_key=True, max_length=10 ) name = models.CharField(max_length = 100) def __str__(self): return self.name class Meta: verbose_name = 'Course' verbose_name_plural = 'Courses' class DateModel(models.Model): """ Each Course can have many Dates """ start_date = models.DateField() end_date = models.DateField(null=True) course_id = models.ForeignKey( CourseModel, on_delete = models.SET_NULL, null = True, blank = False ) def __str__(self): return "{} - {}".format(self.start_date, self.end_date) class Meta: verbose_name = 'Date' verbose_name_plural = 'Dates' I have tried various methods in form for reverse lookup but no success. forms.py class ApplyForm(forms.Form): username = forms.CharField(required = True) .... phone_number = forms.CharField() # courses = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) # courses = forms.ModelChoiceField(widget=forms.RadioSelect, queryset = CourseModel.objects, empty_label=None ) # courses = forms.ModelChoiceField(queryset= CourseModel.objects) courses = forms.modelformset_factory(CourseModel, fields=('id', 'name',)) dates = forms.modelformset_factory(DateModel, fields=('start_date','end_date','course_id')) After reading a lot of StackOverflow forms, I found we have to use the reverse lookup to find out dates from course, therefore in forms.py I was trying to create a reverse lookup views.py def apply_page_copy(request): print(request.POST) form … -
What's the correct approach to Django css when filename functions are required?
In css, sometimes you need to reference a static file e.g: body { background-image: url("{% static 'folder/filename.jpg' %}"); } As far as I know in Django, this can't go into a .css file as the {% static '...' %} then can't be interpreted. That then causes me to write inline stylesheets within Django template files, but this seems wrong and is in practice proving very messy. What's the correct Django approach to this? -
Serializer data is not showing on the API
Hey Guys this is my first project in Django, I am trying to get my 'foreign keys' field into my API with Django Rest framework. I am trying to do a Post a product. since i cannot see input fields i am stuck here. It might be something very simpel, i might didn’t see it. Thank you in advance serializers.py from rest_framework import serializers from rest_framework.serializers import ModelSerializer from .models import * from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password':{'write_only':True,'required':True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) print(user) Token.objects.create(user=user) return user class ProductSerializer(serializers.ModelSerializer): product_id = serializers.CharField(source='product.url', read_only=True) category_name = serializers.CharField(source='category.name', read_only=True) user_id = serializers.CharField(source='user.id', read_only=True) subject = serializers.CharField(source='subject.subject', read_only=True) condition = serializers.CharField(source='condition.condition', read_only=True) major = serializers.CharField(source='major.major', read_only=True) state = serializers.CharField(source='state.state', read_only=True) school = serializers.CharField(source='school.school', read_only=True) location = serializers.CharField(source='location.location', read_only=True) class Meta: model = Product fields = '__all__' class SubjectSerializer(serializers.ModelSerializer): model = Subject fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('url', 'id', 'name') class StateSerializer(serializers.ModelSerializer): # state_count = serializers.SerializerMethodField() class Meta: model = State fields = ['id', 'url', 'state'] # def get_state_count(self, obj): # if State.objects.count() # return obj.children().count() # return 0 … -
Django generating multiple urls for the same subcategory
In my app, there's a list of categories and subcategories with a ForeignKey relationship. Say, there're: Subcategory1 related to Category1 Subcategory2 related to Category2 I expect to get the following subcategory urls: http://127.0.0.1:8000/cat1/subcat1 http://127.0.0.1:8000/cat2/subcat2 These urls work fine. However, django also generates these urls that I don't need: http://127.0.0.1:8000/cat1/subcat2 http://127.0.0.1:8000/cat2/subcat1 Why do they appear in my app? How do I get rid of them? Thanks in advance! models.py: class Category(models.Model): categoryslug = models.SlugField(max_length=200, default="",unique=True) def get_absolute_url(self): return reverse("showrooms_by_category",kwargs={'categoryslug': str(self.categoryslug)}) class Subcategory(models.Model): subcategoryslug = models.SlugField(max_length=200, default="",unique=True) category = models.ForeignKey('Category', related_name='subcategories', null=True, blank=True, on_delete = models.CASCADE) def get_absolute_url(self): return reverse("showrooms_by_subcategory", kwargs={'categoryslug': str(self.category.categoryslug), 'subcategoryslug': str(self.subcategoryslug)}) views.py: class ShowroomCategoryView(DetailView): model = Category context_object_name = 'showrooms_by_category' template_name = "website/category.html" slug_field = 'categoryslug' slug_url_kwarg = 'categoryslug' class ShowroomSubcategoryView(DetailView): model = Subcategory context_object_name = 'showrooms_by_subcategory' template_name = "website/subcategory.html" slug_field = 'subcategoryslug' slug_url_kwarg = 'subcategoryslug' urls.py: urlpatterns = [ path('<slug:categoryslug>/<slug:subcategoryslug>/', views.ShowroomSubcategoryView.as_view(), name='showrooms_by_subcategory'), path('<slug:categoryslug>/', views.ShowroomCategoryView.as_view(), name='showrooms_by_category'), ] -
get() got an unexpected keyword argument 'pk': django
i'm creating like button for my django blog i import api to use ajex from django rest frameworks but i'm getting error in that the error is get() got an unexpected keyword argument 'pk' django view.py class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post, pk=kwargs['pk']) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return url_ from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class PostLikeApiToggle(APIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): usernames = [user.username for user in User.objects.all()] return Response(usernames) def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post, pk=kwargs['pk']) url_ = obj.get_absolute_url() user = self.request.user updated = False liked =False if user.is_authenticated: if user in obj.likes.all(): liked = False obj.likes.remove(user) else: liked = True obj.likes.add(user) updated = True data = { "updated":updated, "liked":liked } return Response(data) urls.py path('blog/<int:pk>/like/', PostLikeToggle.as_view(),name='Like-Toggle'), path('blog/api/<int:pk>/like/', PostLikeApiToggle.as_view(),name='Like-Api-Toggle'), models.py class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User,on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True,related_name='post_likes') content = models.TextField() img = models.ImageField(upload_to='pics',blank=True) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('LoveTravel-Details', kwargs={'pk': self.pk}) def get_like_url(self): return reverse('Like-Toggle', kwargs={'pk':self.pk}) def get_api_like_url(self): return reverse('Like-Api-Toggle', kwargs={'pk':self.pk}) can someone please help me get() got … -
Password reset email is not received
I very new to django. I'm working in resetting password through email in django. I'm using all the 4 default class views. I can get upto PasswordResetDoneView where the page saying instructions have been sent to my mail. But I haven't received any mail. Urls.py from django.urls import path from . import views from django.contrib.auth.views import ( LoginView,LogoutView,PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView,PasswordResetCompleteView ) urlpatterns=[ path('',views.home), path('login/',LoginView.as_view(template_name='accounts/login.html'),name='login page'), path('logout/',LogoutView.as_view(template_name='accounts/logout.html'),name='logout page'), path('register/',views.registration,name='register page'), path('profile/',views.profile,name='profile'), path('profile/edit_profile/',views.edit_profile,name='edit-profile'), path('profile/change-password/',views.change_password,name='edit-profile'), path('profile/reset-password/',PasswordResetView.as_view(),name='paassword_reset_view'), path('profile/reset-password/done/',PasswordResetDoneView.as_view(),name='password_reset_done'), path('profile/reset-password/confirm/<uidb64>/<token>/',PasswordResetConfirmView.as_view(),name='password_reset_confirm'), path('profile/reset-password/complete/',PasswordResetCompleteView.as_view(),name='password_reset_complete'), ] Also I have configured the settings.py file with the necessary configurations. I have also enabled the less secure option for the mail from which I'm sending the url. setting.py EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_emails") EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'projectexample@gmail.com' EMAIL_HOST_PASSWORD = 'Password' Also tried using send_mail separately in the shell. It returns 1. Hoping for a solution Thanks in advance -
How to fix permission error when uploading photos with django admin when deployed?
I am trying to upload photos using Django admin but I get the following error [Errno 13] Permission denied: '/static'. I am trying to deploy this project to a Linode server running ubuntu 18.04 LTS. I believe this is a problem with my permissions for the apache user because if I run manage.py runserver 0.0.0.0:8000 and access the site via port 8000 I can upload photos fine. I should also mention that I can use the admin page for any models that do not require photos. I have tried anything I can find online and have even chmodded 777 -R the directory to the project. This is the path to the project: /home/jonny/estate. These are the permissions from my home dir and the estate dir: jonny@django-server:~$ ls -la total 68 drwxrwxrwx 7 jonny jonny 4096 May 4 10:01 . drwxr-xr-x 3 root root 4096 May 1 17:49 .. -rwxrwxrwx 1 jonny jonny 4795 May 2 18:13 .bash_history -rwxrwxrwx 1 jonny jonny 220 May 1 17:49 .bash_logout -rwxrwxrwx 1 jonny jonny 3771 May 1 17:49 .bashrc drwxrwxrwx 3 jonny jonny 4096 May 1 18:16 .cache drwxrwxrwx 10 www-data www-data 4096 May 4 10:10 estate -rwxrwxrwx 1 jonny jonny 29 May 2 … -
How to add ManyToMany field with 'through' relation to fixtures?
In tests (fixtures) I want to add field with ManyToMany field with 'through' relation, i.e my_field = models.ManyToManyField(SomeModel, through=AnotherModel). Tried to add like regular ManyToManyField like object.my_field.add(my_field), but it gives me this warning message: enter image description here Also, tried this: object.my_field.add(my_field, through_defaults=AnotherModel), also didn't worked -
Original exception text was: 'TUser' object has no attribute 'tpr
Error: AttributeError: Got AttributeError when attempting to get a value for field tprofile on serializer TProfileSerializerUser. The serializer field might be named incorrectly and not match any attribute or key on the TUser instance. Original exception text was: 'TUser' object has no attribute 'tpr I have following model and serializer. class TUser(AbstractBaseUser, PermissionsMixin): email username user_type class UserProfile(model.Model): id user->foreign key to TUser f_name l_name phone class PartnerProfile(Mode.Model): id user-> Foreign key to TUser partner_type /*Serializers*/ class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields='__all__' class PartnerProfileSerializer(serializers.ModelSerializer): class Meta: model = PrtnerProfile fields='__all__' class TUserProfile(serializers.ModelSerializer): password1 password2 userprofile=UserProfileSerializer(required=True) class Meta: model=TUser fields=('email','username','userprofile') def create(self, validated_data): user_profile_data = validated_data.pop('userrofile') data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2','tprofile') } data['password'] = validated_data['password1'] user = self.Meta.model.objects.create_user(**data) if user_type in ['TUSER','Tuser'] and user_profile_data is not None: TUserProfile.objects.create(user=user, **user_profile_data) return user -
Django: Creating Nested Objects with Reverse Relationship
I have a problem while trying to create Nested object with a reverse relationship. I'm trying to POST a Work but at the SAME time trying to POST a Price which is a Work child. Here is my work_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() from PIL import Image class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def save(self, *args, **kwargs): super(Work, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return "{}".format(self.id) My price_model: from django.db import models from .model_work import * from .model_taxes import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) taxes = models.ForeignKey(Taxes, null=True, on_delete=models.SET_NULL) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) And my taxes_model: from django.db import models class Taxes(models.Model): tax_percentage = models.IntegerField(null=True) tax_country = models.CharField(max_length=200, null=True) tax_region = models.CharField(max_length=200, null=True) def __str__(self): return "{}".format(self.tax_country) Here is my work_serializer: from rest_framework import serializers from ..models.model_work import Work from .serializers_user import * from .serializers_price import * class WorkIndexSerializer(serializers.ModelSerializer): """ Serializer listing all Works models from DB """ user = UserIndexSerializer() price … -
Django 'utf-8' codec can't decode byte 0xe6 in position 830: invalid continuation byte
I have a problem with polish language on production. On my local server everything is working fine, but after put my website in the live on DigitalOcean I got error, when i use polish special characters like : "Ś, Ć, Ż" etc. I set charset UTF-8 also in setting.py I used LANGUAGE_CODE = 'pl' Excatly error code you can see on dwdagency.pl Many thanks for help -
On my Blog - matching query does not exists
I have tried to learn like this. And try to develop my blog and add SLUG to the function But it is not possible to add new posts at all Do you have a solution or a way to make it work? https://tutorial.djangogirls.org/en/django_forms/ on Models like this. class Post(models.Model): id = models.AutoField author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_images = models.ImageField(default='Choose Your Images') title = models.CharField(max_length=200,unique=True) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_viewcount = models.PositiveIntegerField(default=0) slug = models.SlugField(max_length=200, default='Enter SEO URL') status = models.IntegerField(choices=STATUS , default=0) and views.py like this def create_post(request): form = Createcontent return render(request, 'blog/post_creator.html', {'form': form}) and urls.py like this urlpatterns = [ path('', views.post_list, name='post_list'), path('content/<slug:slug>/', views.post_detail, name='post_detail'), path('content/createcontent/', views.create_post, name='create_post'), and html file. {% extends 'blog/base.html' %} {% block content %} <h2>New post</h2> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} -
How to add new field in serializer data using existing boolean field?
I have two serializer classes to serialize user data. class CurrentUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'id','first_name','last_name',"is_staff","is_superuser") class userProfileSerializer(serializers.ModelSerializer): user=CurrentUserSerializer(read_only=True) class Meta: model=userProfile fields='__all__' I can get json data give in below; { "id": 1, "user": { "username": "x", "email": "x", "id": 5, "first_name": "x", "last_name": "x", "is_staff": false, "is_superuser": true }, "date_joined": "2020-04-16T16:50:38.218964+03:00", "updated_on": "2020-04-16T16:50:38.218996+03:00" } I want to control is_superuser. İf it is true ı want add new field which is "role":'ADMIN' and ı want to get json like; { "id": 1, "user": { "username": "x", "email": "x", "id": 5, "first_name": "x", "last_name": "x", "role": "ADMIN", "is_superuser": true, "is_staff": false, }, "date_joined": "2020-04-16T16:50:38.218964+03:00", "updated_on": "2020-04-16T16:50:38.218996+03:00" } -
Django - static file issue
I don't understand why the image it doesn't shows. What could be the issue? My static-folder is positioned in my core_app as you can see in the picture but I'm working on my quiz_app folder. In my settings.py it seems everything ok, for the path to display the image I followed the documentation, I think the problem is where my folder is but I'm not sure. If I just put the image using css like " background-image: url("/static/img/CHALLENGE.png"); " it works but of course it's not what I'm trying to do. So I don't understand why the img src doesn't work. quiz/quiz.html % extends "base.html" %} {% block title%} Quiz_page {% endblock %} {% block content %} {% load static %} <div class="card"> <img src= "{% static '/static/img/CHALLENGE.png'%}" alt="" > </div> piattaforma/settings.py """ Django settings for piattaforma project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in … -
Ajax-form comment create in Django with refresh <div id="comment-list">
I need to refresh comment-list on my article_detail view after create a new comment. When I press in the submit-button, my div reload, but I can't take div with id="comment-list". In data i get the html page. How can I parse the comment-list block and refresh it from it specifically? class AjaxableResponseMixin: def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super().form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) data = { 'pk': self.object.pk, } return JsonResponse(data) else: return response class CommentCreateView(CreateView, AjaxableResponseMixin): model = Comment form_class = CommentForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class ArticleDetailView(DetailView, AjaxableResponseMixin): model = Article context_object_name = 'article' def get_queryset(self): qs = super(ArticleDetailView, self).get_queryset() return qs def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) comment_list = Comment.objects.filter(article=self.object).order_by('-date') for comment in comment_list: comment._article_url = self.object.get_absolute_url() context['comment_list'] = comment_list context['comment_form'] = CommentForm(initial={'article': self.object}) return context $(document).on('submit', '#comment-form', function(event) { event.preventDefault(); $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function (data) { var doc = $.parseHTML(data.comment_list); $('#comment-list').html(doc); $('#comment-form')[0].reset(); console.log(data); console.log('success'); }, error: function (data) { console.log(data); console.log('error'); } }) }) -
How to change object through views in Django?
I'm trying to get the login_attempts number in my object to count down after unsuccessful login attempts. So every time someone sends the incorrect username and password via POST the number would go down up to 0 and then they would get error message. Thanks in advance -
Django default queryset values shorthand
I am initializing variables to None as default value. If the queryset returns no objects then the program will not fail. Is there a shorter method on this? Thanks qs_data = { 'flal_id_no' : None, 'mail_id_no' : None, 'subject_id_no':None, 'pdsbj_id_no':None, } qs = vFileAllocation.objects.values().filter(track_id_no=get_track_id_no)[0] if qs: qs_data['flal_id_no'] = qs['flal_id_no'] qs_data['mail_id_no'] = qs['mlal_id_no'] qs_data['subject_id_no'] = qs['subject_id_no'] qs_data['pdsbj_id_no'] = qs['pdsbj_id_no'] -
Retrieving the actual file from a http request (for os.stat)
I'd like to retrieve the meta data of an uploaded file by use of: st = os.stat(file_path) However I'm not sure how to parse the file_path attribute from the http request. For example, I've used: request.FILES but then get: TypeError: stat: path should be string, bytes, os.PathLike or integer, not MultiValueDict I also serialize the request, like so: serializer = FileSerializer(data=request.data) How do I get the actual uploaded file in the http reques? -
Http Referer header changed after first load
So I have a django application and it's acting weirdly as for the first call the http_referer is correct but from the next call even for the static files the referer is changed to the current domain. -
How to compare date field with None in django ORM?
I have a model where there is a Date field. I'm trying to query the model by passing date object or a null value. The query should behave in different ways based on the input provided in ORM query. I'll be passing two variables to ORM query st_date and exp_date. exp_date can be None sometimes. I need to query the model and fetch all the records which has the expiration_date greater than provided exp_date if there is some value in exp_date. If not, it should not consider the filter at all. models.py: class DtModel(models.Model): scheduled_start_date = DateField() scheduled_end_date = DateField() ORM query: st_date="2020-05-01" exp_date=None DtModel.objects.filter(scheduled_start_date__gte=st_date, scheduled_end_date__lte=exp_date) It's throwing an error when the exp_date is null when it tries to compare None and date field? ValueError: Cannot use None as a query value -
unable to retrive data in crud operation
{%for x in read%} {%if request.user == user%} <div class="card " > <h5> <div class="card-header bg-info"> Dr.{{i.name}} </div> </h5> <div class="card-body"> <h6 class="card-title ">Appointment Date : {{x.appoinment_date}}</h6> <h6 class="card-title">Age : {{x.age}}</h6> <h6 class="card-title">Digree : {{x.disease}}</h6> <h6 class="card-title">Email : {{x.email}}</h6> </div> </div> {%endif%} {%endfor%} i am using code below but i am getting data of all users instead of current user -
Direct assignment to the forward side of a many-to-many set is prohibited. Use fieldname.set() instead
Custom User Model from django.db import models # from roles_tasks.models import mst_org_roles # from organizations.models import config_orgs # from projects.models import mst_projects from django.contrib.auth.models import AbstractBaseUser,BaseUserManager class UserManager(BaseUserManager): def create_user(self,email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None, is_admin=False, is_staff=False): if not email: raise ValueError("email id is required") if not password: raise ValueError("password must required") if not first_name: raise ValueError("first_name is required") if not last_name: raise ValueError("last_name is required") if not role_id: raise ValueError("role_id is required") if not org_id: raise ValueError("org_id is required") if not status: raise ValueError("status is required") if not created_by: raise ValueError("created_by is required") if not modified_by: raise ValueError("modified_by is required") user_obj=self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name=first_name user_obj.last_name=last_name user_obj.role_id=role_id user_obj.org_id=org_id user_obj.project_id=project_id user_obj.status=status user_obj.created_by=created_by user_obj.modified_by=modified_by user_obj.admin=is_admin user_obj.staff=is_staff user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=password, is_admin=False, is_staff=True ) return user def create_superuser(self,email,first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=password, is_admin=True, is_staff=True ) return user Status = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ('Deleted', 'Deleted') ] class User(AbstractBaseUser): username = None last_login = None email=models.EmailField(max_length=255,unique=True) admin=models.BooleanField(default=False) staff=models.BooleanField(default=False) first_name=models.CharField(max_length=200) last_name=models.CharField(max_length=200) role_id = models.ForeignKey('roles_tasks.mst_org_roles', … -
Half Hours choice fields for TimeField in Django model
I want to have field choice in form that user can pick hours with half hours choice. I have this model and this TimeField: class Sample: start_time = models.TimeField(choices=global_vars.TIME_MAP_HALF_HOURS_CHOICES,) I want to show half hours time to customer. This is my Choices: TIME_MAP_HALF_HOURS_CHOICES = ( (datetime.time(00, 00, 00), '00:00'), (datetime.time(00, 30, 00), '00:30'), (datetime.time(1, 00, 00), '01:00'), (datetime.time(1, 30, 00), '01:30'), (datetime.time(2, 00, 00), '02:00'), (datetime.time(2, 30, 00), '02:30'), (datetime.time(3, 00, 00), '03:00'), (datetime.time(3, 30, 00), '03:30'), (datetime.time(4, 00, 00), '04:00'), (datetime.time(4, 30, 00), '04:30'), (datetime.time(5, 00, 00), '05:00'), (datetime.time(5, 30, 00), '05:30'), (datetime.time(6, 00, 00), '06:00'), (datetime.time(6, 30, 00), '06:30'), (datetime.time(7, 00, 00), '07:00'), (datetime.time(7, 30, 00), '07:30'), (datetime.time(8, 00, 00), '08:00'), (datetime.time(8, 30, 00), '08:30'), (datetime.time(9, 00, 00), '09:00'), (datetime.time(9, 30, 00), '09:30'), (datetime.time(10, 00, 00), '10:00'), (datetime.time(10, 30, 00), '10:30'), (datetime.time(11, 00, 00), '11:00'), (datetime.time(11, 30, 00), '11:30'), (datetime.time(12, 00, 00), '12:00'), ) But When I want to save object, the form not validate and raise error: Choose a valid option. How can I fix this error? -
get() returned more than one Post : return 2
i was trying to make like button for my django blog but i'm getting error while hitting like the error is get() returned more than one Post -- it returned 2! here is my code views.py class PostLikeRedirect(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): obj.likes.add(user) return url_ models.py class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User,on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True,related_name='post_likes') content = models.TextField() img = models.ImageField(upload_to='pics',blank=True) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('LoveTravel-Details', kwargs={'pk': self.pk}) urls.py path('blog/<int:pk>/like/', PostLikeRedirect.as_view(),name='Like'), -
Python Django Model Commit behaviour?
My model class is Document as below. I want to update all status to 'Superseded' for every new or update record based 'DocumentNo' field to database. I succeeded to achieve this goal, But Please explain me if any error occurred on save will commit to database or not ? will these save method behave like database transaction ? class Document(models.Model): DocumentNo = models.CharField(max_length=100) Rev = models.CharField(max_length=10) Description = models.TextField(max_length=500) Area = models.CharField(max_length=100,blank=True,null=True) ReceivedDate = models.DateField() Status = models.CharField(max_length=20,choices=[('Current','Current'),('Superseded','Superseded')],default='Current') class Meta: constraints=[ models.UniqueConstraint(fields=['DocumentNo', 'Rev'], name='unique_document'), ] indexes=[ models.Index(fields=['Area','Status']) ] ordering=[ 'DocumentNo', 'Rev' ] def __str__(self): return self.DocumentNo + ' (' + self.Rev +')-Status: ' + self.Status def save(self, *args, **kwargs): existing_documents=Document.objects.all().filter(DocumentNo=self.DocumentNo) for doc in existing_documents: doc.Status='Superseded' doc.saveIndividual() super().save(*args, **kwargs) def saveIndividual(self, *args, **kwargs): super().save(*args, **kwargs) ```