Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django getting NoneType error when querying tags using TaggableManager
I am creating a blog with Django and using TaggableManager to fetch similar posts. I get int() argument must be a string, a bytes-like object or a number, not 'NoneType' when I request a post (PostDetail view) which has only one tag that has not been used in other posts. If the post has a tag which was used before or two tags, one new and one used before, all is fine. The issue might be because I'm querying a reverse foreign key, so 'None' appears for tags not having any post (source Django documentation on values_list) models.py class Post(models.Model): tags = TaggableManager( help_text="We suggest to use no more than 3 tags to improve search results") views.py class PostDetail(View): def get(self, request, slug, *args, **kwargs): # fetch post by similarity post_tags_ids = post.tags.values_list('id', flat=False) similar_posts = Post.objects.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags') I'm following the example shown in the book Django by Example here's the repository. I'd like my detailed view of the post to be shown anyways, how can I avoid getting 'NoneType'? Thanks in advance for any help. -
How to save url <str:> part in Django Class Based View context
I am struggling to get the value uuid_contrat in my url into my views' context. This is what I have got so far: urls.py from django.contrib import admin from django.urls import path, include from applications.views import * from . import views urlpatterns = [ path('<str:uuid_contrat>/', ApplicationListView.as_view(), name="applications") , ] views.py class ApplicationListView(ListView): model = ViewDevpermissionapplicationuser template_name = 'applications/applications.html' def get_context_data(self, *args, **kwargs): kwargs.update( user= self.request.session.get('user', {'is_authenticated' : False}) ) context['uuid_contrat'] = self.request.GET.get('uuid_contrat') return context I tried using request.GET.get but it isn't working, any suggestions ? -
DjangoRestFramework - pass partial flag to nested serializer
How do I pass partial flag to nested serializers ? for example , serializers.py class ASerializer(serializers.Serializer): name = serializers.CharField() def validate(self, data): print("A", self.partial) return data class BSerializer(serializers.Serializer): a = ASerializer(read_only=False) def validate(self, data): print("B", self.partial) return data views.py class TestView(APIView): def get(self, request, format=None): content = {} return Response(content) def post(self, request, format=None): bsr = BSerializer(data=request.data, partial=True) # <- I want to pass the partial flag to the nested serializer as well if bsr.is_valid(raise_exception=True): return Response(bsr.data) else: return Response(bsr.error) passing {"a":{"name":"test"}} to TestView prints A False B True In this example how do I pass the partial flag to ASerializer from BSerializer ? -
Django channels websocket "Sending and Receiving Messages" fails
I am following the course Developing a Real-Time Taxi App with Django Channels and Angular . I cannot proceed as the test in Part 1 of the course, and in particular the websocket "Sending and Receiving Messages" fails. Please find in the following the error message:FAILED trips/tests/test_websocket.py::TestWebSocket::test_can_send_and_receive_messages - concurrent.futures._base.TimeoutError Here the complete failure log: _____________________________________________________ TestWebSocket.test_can_send_and_receive_messages _______________________________________________________ *self = <channels.testing.websocket.WebsocketCommunicator object at 0x7f31d75e64e0>, timeout = 1 async def receive_output(self, timeout=1): """ Receives a single message from the application, with optional timeout. """ # Make sure there's not an exception to raise from the task if self.future.done(): self.future.result() # Wait and receive the message try: async with async_timeout(timeout): > return await self.output_queue.get() env/lib64/python3.6/site-packages/asgiref/testing.py:74: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <Queue at 0x7f31d75e6550 maxsize=0 tasks=1> @coroutine … -
Django form.is_valid returning False where request.POST contains data from two forms
I am using the Django Provided User Model and along with that, I have also made a second model by the name of Account, in which I am storing the User's Profile Picture and Name. All this data is provided in a Single Form in the HTML file and both forms are dealt in a single View Function. This is my models.py file, from django.db import models from django.contrib.auth.models import User # Create your models here. class Account(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) profile_pic = models.ImageField(null=True, blank=True) ratings = models.FloatField(default=1000) date_joined = models.DateTimeField(auto_now_add=True, null=True) This is my forms.py file, from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Account class UserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class AccountForm(ModelForm): class Meta: model = Account fields = ['name', 'profile_pic'] Here's the complete register.html Template file, {% load static %} <!DOCTYPE html> <html> <head> <title>Register Account</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: … -
What is the proper way to change custom user password?
I am working on my Django (DRF) application. A have a CustomUser model class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): ... def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) # Full name phone_number = models.CharField(max_length=20, unique=True) ... I have created a custom way to change password. I am sending current_password, new_password_verify and new_password_verify in body parameter. What is the proper way to implement password change in Django? class CustomUserViewSet(viewsets.ModelViewSet): def update(self, request: Request, *args, **kwargs): instance: CustomUser = self.get_object() serializer = self.get_serializer( instance, data=request.data, partial=True ) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, "_prefetched_objects_cache", None): instance._prefetched_objects_cache = {} return Response({ "is_password_updated": self.update_password(request, instance), # <-------UPDATE "result": serializer.data }) def update_password(self, request, instance): """update password if 'new_password_verify' and 'new_password' are in request""" if "current_password" in request.data and instance.check_password(request.data["current_password"]) and \ "new_password" in request.data and "new_password_verify" in request.data and \ request.data["new_password"] == request.data["new_password_verify"]: instance.set_password(request.data["new_password"]) instance.save() return True return False -
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, .... Django
I currently develop a Django project and want to send email for email verification. Here is My Code settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'co******@gmail.com' EMAIL_HOST_PASSWORD = '***********' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'co******@gmail.com' SERVER_EMAIL = 'co******@gmail.com' views.py template = render_to_string('mail.html', {'email': email, 'code': temp_code}) send_mail( 'Email Verification', '', settings.EMAIL_HOST_USER, [email], fail_silently=False, html_message=template ) -
Pass Django's "to_field" argumento in model, two fields that have a UniqueConstraint
What I'm trying to accomplish is to have the "dependencia" field on Puesto model as Charfield, in order to use the natural keys and pass for example this "[NTRA. SRA. DE LA ASUNCION,Capital]" and that can be mapped to the Dependencia Model. I'm passing this arguments from a JSON fixture. Because the "descripcion" and "departamento" fields in "Dependencia" can't have the argument unique= True, I can't use them to point to those fields and finally get "dependencia" on Puesto model converted from int (because is pointing to the id field in dependencia which is the PK), to Charfield. Is there a way of use the constraint "unico_nombre_pordpto", or pass the field descripcion and departamento to "to_field"? What suggestions do you have? Thanks in advance. MODEL DEPENDENCIA class DependenciaManager(models.Manager): def get_by_natural_key(self, descripcion, departamento): return self.get(descripcion=descripcion, departamento=departamento) class Dependencia(models.Model): descripcion = models.CharField(max_length=300, blank=False, null=False) cod_institucion = models.PositiveIntegerField( blank=True, null=True, ) departamento = models.ForeignKey( Departamento, on_delete=models.PROTECT, blank=False, null=True, to_field="descripcion", ) objects = DependenciaManager() class Meta: constraints = [ models.UniqueConstraint( fields=["descripcion", "departamento"], name="unico_nombre_pordpto" ) ] def natural_key(self): return (self.descripcion, self.departamento) def __str__(self): return f"{self.descripcion}" MODEL PUESTO class Puesto(models.Model): numero = models.PositiveIntegerField(blank=False, null=False, primary_key=True) cargo = models.ForeignKey( Cargo, on_delete=models.PROTECT, blank=False, null=True, to_field="descripcion_cargo", ) dependencia = … -
how can I add sum rows in django import-export library?
How can I add sum row on the bottom of my table in exported xlsx file? I don't see anything like that in their doc but maybe you did something similar. I'd like to summarize only the total_price column. My resource looks like this: class CERequestResource(resources.ModelResource): related_component__service = Field(attribute='related_component__service') related_product__title = Field(attribute='related_product__title'') related_component__component_name = Field(attribute='related_component__component_name') related_component__task_description = Field(attribute='related_component__task_description') related_component__position = Field(attribute='related_component__position') number_of_units = Field(attribute='number_of_units', column_name='# of Units') related_component__margin = Field(attribute='related_component__margin') total_price = Field(attribute="total_price") model = CERequest fields = ('id', 'related_component', 'related_product', 'number_of_units', 'total_price', 'margin') -
updated cash page in Django
When is changed a record in the database , how to identify all the pages (url) related to this change, so that we can remove these cached pages from the server's cache with a signal. -
Django kubernetes connection Max retries exceeded with url
I'm trying to create a kubernetes job inside google cloud using django and when I call my rest_api view I'm getting this error: ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fc745e58580>: Failed to establish a new connection: [Errno 111] Connection refused During handling of the above exception, another exception occurred: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=80): Max retries exceeded with url: /apis/batch/v1/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fc745e58580>: Failed to establish a new connection: [Errno 111] Connection refused')) Here is my kubec-config.yaml: apiVersion: v1 kind: Config clusters: - cluster: certificate-authority-data: DATA+OMITTED server: --- name: gke_---_europe-west1_cluster-1 users: - name: cluster-1 current-context: gke_---_europe-west1_cluster-1 contexts: - context: cluster: gke_---_europe-west1_cluster-1 user: gke_---_europe-west1_cluster-1 name: gke_---_europe-west1_cluster-1 spec: jobTemplate: spec: template: spec: containers: - name: cluster-1 image: cluster-1:v5 env: imagePullPolicy: IfNotPresent command: ['./Renderer'] args: ['project.json'] restartPolicy: OnFailure I got many of the information here by running kubectl config view inside google cloud and just copy and pasted them here. And this is my APIview: class ProjectExportView(APIView): def get(self, request, uuid): jobs = ["", "", ""] try: project = Project.objects.get(uuid=uuid) from utils.gke import kube_test_credentials, kube_cleanup_finished_jobs, kube_delete_empty_pods, kube_create_job import os # Testing Credentials kube_test_credentials() # We try to cleanup dead jobs … -
Django - CreateView form_valid() how can I access foreign key objects
I think I complicate this more because what I am using for the Foreign Key has a Choice setting and I have the Foreign Key set to show the human readable choice. Which seems to be what it is searching on. Strikes me as strange though because when I look at the return data it appears to be passing the primary key. Anyways maybe some code will help so: (as a caveat this is the 9 millionth view iteration and at this point I was at least kind of experimenting with different thing) views.py model = Ship fields = ['hull', 'name', 'debt'] template_name = 'crew/ship.html' success_url = reverse_lazy('crew_app:ship_list') def form_valid(self, form): hul = form.instance.hull hp = get_object_or_404(ShipHull, hull=hul) form.instance.hull_points_max = hp.hull_points form.instance.hull_points_cur = hp.hull_points return super().form_valid(form) models.py class ShipHull(models.Model): SHIP_TYPE = ( ('WF', 'Worn Freighter'), ('RTT', 'Retired Troop Transport'), ('SAV', 'Strange Alien Vessel'), ('UPS', 'Upgraded Shuttle'), ('RSS', 'Retired Scout Ship'), ('RSV', 'Repurposed Science Vessel'), ('BMV', 'Battered Mining Ship'), ('UMC', 'Unreliable Merchant Cruiser'), ('FDV', 'Former Diplomatic Vessel'), ('ALC', 'Ancient Low-Tech Craft'), ('BSW', 'Built from Salvaged Wrecks'), ('RMS', 'Retired Military Patrol Ship'), ) hull = models.CharField(max_length=200, choices=SHIP_TYPE) traits = ArrayField(models.CharField(max_length=200), blank=True) hull_points = models.IntegerField() debt = models.CharField(max_length=200) roll = IntegerRangeField(null=True) def __str__(self): … -
Display of Django ModelForm field validation errors in crispy forms
I am using the following ModelForm: class ListingQuoteForm(forms.ModelForm): author_phone = forms.CharField(validators=[validate_phone_number]) content = forms.CharField( label='Your message', min_length=50, widget=forms.Textarea(attrs={'rows': 4}), help_text='Please provide a few details about your race and your requirements', ) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user.is_authenticated: self.fields['author_name'].initial = user.full_name(strict=True) self.fields['author_email'].initial = user.email self.fields['author_email'].disabled = True class Meta: model = QuoteRequest fields = ('author_name', 'author_email', 'author_phone', 'content') labels = { 'author_name': 'Your name', 'author_email': 'Your email', 'author_phone': 'Your phone number', } and rendering it in the following template: {% load crispy_forms_tags %} <div class="listing-section" id="quote-form"> <div class="listing-section-header"> {% if primary_category.quote_request_type == 'quote' %} <h2>Request a quote</h2> {% elif primary_category.quote_request_type == 'info' %} <h2>Request more info</h2> {% endif %} </div> <div class="listing-section-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ quote_form.author_name|as_crispy_field }} {{ quote_form.author_email|as_crispy_field }} {{ quote_form.author_phone|as_crispy_field }} {{ quote_form.content|as_crispy_field }} <div class="form-group"> <button class="standard-button standard-button--submit" type="submit">Send</button> </div> </form> </div> </div> When the content field min length validation fails, a message is displayed like so: But when my custom phone number validation fails, the error displays under the field like so: How can I get my phone number validation error to display the same way the in-built min length validation does for the CharField? -
Serializing model queryset showing empty [OrderedDict()]
I am building a blog app with React and Django and I am serializing model's instances saved by particular user, First I am just trying to test with .all() then I am planning to filter by specific user But when I serialize queryset with Serializer like :- class BlogSerializerApiView(viewsets.ModelViewSet): serializer_class = BlogSerializer def get_queryset(self, *args, **kwargs): queryset = Blog.objects.all() output_serializer = BlogSerializer(queryset, many=True) print(output_serializer.data) return "Testing" it is showing in console :- [OrderedDict(), OrderedDict()] and when I access it like print(output_serializer) then it is showing BlogSerializer(<QuerySet [<Blog: user_1 - Blog_title>, <Blog: user_2 - second_blog_title>]>, many=True): serializer.py class BlogSerializer(serializers.Serializer): class Meta: model = Blog fields = ['title'] models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') def __str__(self): return f"{self.user} - {self.title}" What I am trying to do I am trying to serialize queryset to show on page in react frontend, I will relate with specific user later. I have tried many times by changing CBV serialization method by generics.ListAPIView instead of viewsets.ModelViewSet but still same thing. Any help would be much Appreciated. Thank You in Advance -
django channels store unsent messages
let's say I'm building a chat app, and ever user has his own channel group,now if user still in the app, but websockets disconnected for some time but if someone sent messages, surely messages won't be received but when user reconnect, I want him to receive the new messages. Can I store messages on redis and when user connects from the connect method I send it back or there's a better approach for this? -
Django Models auto_now saving same time as auto_now_add
Django models issue. I add these 2 fields in almost every model to store created (auto_now_add=True) and updated datetime (auto_now=True). created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, null=True) Problem Problem is when I create a new row in a table using Django, created_at field gets populated with current datetime (which is fine) but its updated_at field also gets populated on first time creation. Does that make sense? From an end user's point of view, I only created a record but never updated it but in database its updated time is also updated since data is inserted first time in a row (happens whenever you insert a new row). So, when a user views the record, system will show created_at and updated_at exactly same. -
How to make a one form for multiple models with one-to-many relationship in django?
I have one model which name is Post. It has two one-two-many relationship with model "PostImages" and "PostFiles". I want to create only one form to handle this. Also I want files and images upload to be not required. And I did it but my code doesn't run validation process on "PostImagesForm" and "PostFilesForm", but it validate the "PostForm". models.py (i am using FileTypeValidator form uload_validator package which works fine for thumbnail so there isn't problem with it) class Post(models.Model): title = models.CharField(max_length=60) content = tinymce_models.HTMLField('content') date = models.DateTimeField(default=timezone.now) slug = AutoSlugField(populate_from='title', unique_with='date') thumbnail_big = models.ImageField(upload_to='thumbnails/', validators=[FileTypeValidator(allowed_types=[VIEL])]) thumbnail_small = models.ImageField(upload_to='thumbnails/', blank=False, default=thumbnail_big) def description(self): return HTMLtoString(self.content) def save(self, *args, **kwargs): #THUMBNAIL COMPRESSION #small thumbnail if SizeOfImageGreaterThan(self.thumbnail_big, TQS.SMALL_THUMBNAIL_RESOLUTION): thumbnail_compressed_small = Compress(self.thumbnail_big, TQS.SMALL_THUMBNAIL_RESOLUTION, TQS.SMALL_THUMBNAIL_QUALITY) self.thumbnail_small = thumbnail_compressed_small #big thumbnail if SizeOfImageGreaterThan(self.thumbnail_big, TQS.BIG_THUMBNAIL_RESOLUTION): thumbnail_compressed_big = Compress(self.thumbnail_big, TQS.BIG_THUMBNAIL_RESOLUTION, TQS.BIG_THUMBNAIL_QUALITY) self.thumbnail_big = thumbnail_compressed_big super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("EatWell:Post", args=[self.slug]) class PostImages(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) big_image = models.ImageField(upload_to='images/', blank=True, null=True, validators=[FileTypeValidator(allowed_types=[VIEL])]) small_image = models.ImageField(upload_to='images/', blank=False, default=big_image) def save(self, *args, **kwargs): #IMAGE COMPRESSION #small image if SizeOfImageGreaterThan(self.big_image, IQS.SMALL_IMAGE_RESOLUTION): small_image_compressed = Compress(self.big_image, IQS.SMALL_IMAGE_RESOLUTION, IQS.SMALL_IMAGE_QUALITY) self.small_image = small_image_compressed #big image if SizeOfImageGreaterThan(self.big_image, IQS.BIG_IMAGE_RESOLUTION): big_image_compressed = Compress(self.big_image, IQS.BIG_IMAGE_RESOLUTION, IQS.BIG_IMAGE_QUALITY) self.big_image = big_image_compressed super(PostImages, self).save(*args, **kwargs) class PostFiles(models.Model): … -
add the full URL in rich text embed image src in Wagtail API V2
Hope you all are doing well. Is there any way to add the full URL in embed image src in API? Here is the API sample "content": [ { "type": "full_richtext", "value": "<p data-block-key=\"11dr5\"> Example: The database consists of information about a set of</p><p data-block-key=\"4l7vp\"></p><img alt=\"image-325682-1594637051\" class=\"richtext-image full-width\" height=\"410\" src=\"/media/images/image-325682-1594637051.width-800.jpg\" width=\"728\"><p data-block-key=\"b41bt\"></p><p data-block-key=\"eorjk\"> customers and accounts and the relationship between them) </p>", "id": "f21e7928-f81c-477a-ab42-ba3bc2cd9226" } ] how I can add this type of URL like in that src=\"example.com/media/images/imagename\"? Here is my models.py file. """Blog listing and blog detail pages.""" from django.db import models from modelcluster.fields import ParentalManyToManyField from django import forms from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel, InlinePanel from wagtail.core.fields import StreamField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.core.models import Page from wagtail.snippets.models import register_snippet # from . import blocks from . import blocks from .blocks import InlineVideoBlock from rest_framework import fields, serializers from modelcluster.fields import ParentalKey from wagtail.api import APIField from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from django.shortcuts import render from wagtail.contrib.routable_page.models import RoutablePageMixin, route #added by fathi from rest_framework.fields import Field @register_snippet class BlogCategory(models.Model): """Blog category for a snippet.""" name = models.CharField(max_length=255) slug = models.SlugField( verbose_name="slug", allow_unicode=True, max_length=255, help_text='A slug to identify posts by this category', ) … -
How to make url inaccessiable for other users with something like uuid in django? [closed]
I'm creating django app with authentication and I have a problem 'cause every user could manually enter path and access login or signup page. I saw facebook solved this problem by adding some kind of code to their url. Now I would want to know how to do that. Thanks for help:) -
How to show parameter (request body ) for swagger in rest Framework in django?
[enter image description here][1] [1]: https://i.stack.imgur.com/uhJNK.png -
I need help understanding the cause of this NoReverseMatch error
I think I am passing in the right parameters into the template link so i dont know where to check for the problem. Any help and explanation will be appreciated. Here's the template code: <p>Click here to borrow <a href="{% url 'borrow-book' book_copy.book.id book_copy.copy_num %}">this</a>.</p> Here's the url: path( "hub/book/<int:pk>/<uuid:copy_num>", views.borrow_book, name="borrow-book", ) Here's the view: def borrow_book(request, copy_num): book_copy = get_object_or_404( BookCopy, copy_num=copy_num ) # Returns object based on pk and raises 404 if not found if request.method == "POST": form = BorrowDateForm(request.POST) if form.is_valid(): book_copy.borrow_date = form.cleaned_data["borrow_date"] book_copy.save() return HttpResponseRedirect(reverse("book-detail")) else: proposed_borrow_date = datetime.datetime.today() + datetime.timedelta(days=1) form = BorrowDateForm(initial={"borrow_date": proposed_borrow_date}) context = { "form": form, "book_copy": book_copy, } return render(request, "librarianinterface/borrow_date.html", context) Here's the form: class BorrowDateForm(forms.Form): borrow_date = forms.DateTimeField( help_text="Enter a date two or less days from now.", required=True ) # Period in which they will pick up the book, book will be marked as reserved before pickup # return_date = borrow_date + datetime.timedelta(days=7) # They have to return the book within 7 days def clean_borrow_date(self): # Checks if entered data is valid data = self.cleaned_data["borrow_date"] if data < datetime.datetime.today(): raise ValidationError(_("Invalid date - past date or time entered")) if data > (datetime.datetime.today() + datetime.timedelta(days=2)): raise ValidationError( … -
How do I get rating from book model according to this model in django?
book model [review model][2] [how do i get rating in line 15?][3] views.py -
Django increment value on submitting form
class Project(models.Model): dept= models.ForeignKey(Department, on_delete=models.SET_NULL, null=True) count = count = models.IntegerField(blank=True,null=True) What i am trying to do is everytime i add project increase the project count of Department. For example 'x' has no project and i add a new project and count will be = 1 then count will be 2. Then department 'y' will add project count will be = 1 for 'y' but stays 2 for 'x' department. -
Django filters with conditional field
I have a User modal and UserAddress model. I am trying to sort users based on UserAddress.city field. #models class User(AbstractUser): ... class UserAddress(TimeStampedModel): ... city = models.CharField(max_length=50, null=True) ... primary = models.BooleanField(default=False) #User can only have 1 primary record active = models.BooleanField(default=True) #viewset class UserViewset(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = serializers.UserSerializer ordering_fields = [ ... 'useraddress__city' ] #serializers class UserBasicSerializer(serializers.ModelSerializer): user_city = serializers.SerializerMethodField() def get_user_city(self, obj): try: address = models.UserAddress.objects.filter( primary=True, active-True, user=obj ).first() return address.city except: return None class Meta(object): model = User fields = ( ... "user_city", ... ) If it use domain?sort=London it works, however, it does not take active and primary fields into account. So i get sorting with gaps of null in the result. I want to treat those gaps as real null values, bit not sure how. P.S. I am using JSON API hence sort and not ordering in url. -
Django Static css and js file not found but image show | Itry all method of stackoverflow solution but not work
Add path in setting path is correct also port change no solve change static file location from app to project and project apply documentation code not solve I totally frustrated now STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR,'static')] STATIC_ROOT=os.path.join(BASE_DIR,"/static/") # ``` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/gbHfU.png