Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
I had an error when I wanted to install Django Didocker, this is what the error says :
error while fetching server api version: (2, 'createfile', 'the system cannot find the file specified.') [2196] failed to execute script docker-compose -
How to implement folder like path on web using django
Currently I'm trying to implement path like on this screen,but I have no idea how to do this. What is the best approach to create this path using django? screen -
Using a middleware in Django make my path not accessible
I got an app, that ref to two installed app, one is api, another is webapp. the webapp got a middleware. to avoid the middleware discard my /api request, I use self.get_response to handle it, if the request path is start with /api. Here is my urls.py in api and it is my views.py in api I call localhost:3000/api/foo, it returns me a 404 not found error. I tried to update the api/urls.py to api/foo, but it is not success. -
Send money to multiple accounts via PayPal SDK or API
A website where users can buy digital products from other users and the host takes a cut out of those transactions. How to implement this system using the PayPal SDK or API? Scenario: One buyer with a personal PayPal account One receiver with a personal PayPal account The host with a business PayPal account I wonder if it's possible that the buyer's money to be split and sent to the receiver and host account simultaneously. -
how to style django-select2 dropdown field with bootstrap
I am using django-filter, django-select2 and crispy forms to create a selectable dropdown but the django-filter field looks like bootstrap but I cannot change to style to match the other input fields. This is my crispy forms layout: self.helper.layout = Layout( FieldWithButtons( Field( "original_filename", placeholder=SEARCH_TEXT, css_class="rounded" ), StrictButton( '<i class="fas fa-search"></i>', type="", css_class="no-spinner", ), css_class="mb-0 ml-5 input-group-sm input-icon input-icon-right rounded", ), Div( Field( "location", css_class="form-control my-0", wrapper_class="my-0 mx-1 w-200px" ), css_class="d-flex h-100 " ), Div( Div( HTML(SEARCH_TEXT), css_class="btn btn-secondary ml-1", onClick="$(this).closest('form').submit();", ) ), Div( Div( Div( HTML(mark_safe('<div class="fas fa-sort-amount-down"></div>')), css_class="mx-2", ), css_class="d-flex align-items-center", ), Field( "o", css_class="mb-0 input-group-xs", wrapper_class="mb-0 input-group-xs", onChange="$(this).closest('form').submit();", ), css_class="d-flex flex-row ml-5", ), Div(css_class="ml-5 spinner spinner-primary d-none"), ) This is the current result. I tried using bootstraps classes like form-control, input-group but it did not change the outcome. As you can see is the second input field different from the others. -
Django using id to write foreign key fields
I need to have a CRUD interface for interconnected django models. Can i use _id fields to fill in ForeignKey fields? i.e. will this work: class MyModel(models.Model): foreign_key = ForeignKey('AnotherModel') class MyModelSerializer(serializers.ModelSerializer): foreign_key_id = serializers.IntegerField(write_only=True) foreign_key = AnotherModelSerializer(read_only=True) class Meta: model = MyModel fields = ('foreign_key', 'foreign_key_id') -
Django standalone apps with one app depending on another app - django.db.migrations.exceptions.NodeNotFoundError
I am using Django 4.0 I have written two standalone apps. Foo and FooBar. Application Foo uses package django_nyt. Application FooBar uses functionality from application Foo. I am able to makemigrations and migrate models in application Foo, however, when working with application FooBar, when I attempt to makemigrations, I get the following error trace: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 100, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/loader.py", line 276, in build_graph self.graph.validate_consistency() File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 198, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 198, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 60, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration foo.0001_initial dependencies reference nonexistent parent node ('django_nyt', '0010_auto_20220802_2211') Since these are standalone apps, I am using the design pattern advocated for in Django Standalone Reusable Libraries. common.py (foo … -
Avoiding the unique_together constraint when updating a Django Model instance with request.POST
Model: class myModel(models.Model): project_id = models.IntegerField( null=False, blank=False, default=0, ), field_1 = models.CharField( max_length=250, null=False, blank=False ), field_2 = models.CharField( max_length=250, null=False, blank=False ) class Meta: unique_together = ('project_id', 'field_1', 'field_2') views.py: model_instance = myModel.objects.get(pk=id) if request.method == 'POST': form = NewMyModelForm(request.POST, instance=model_instance) form.save() forms.py: class NewMyModelForm(ModelForm): class Meta: model = myModel fields = '__all__' Problem: When I edit something in the front-end and I submit the changes (via POST), this code is basically creating a 'new object' so the unique_together constraint can't be satisfied. Is there a way to update the instance bypassing the constraint? -
Django how to override the HttpResponse 404 instead of raise exception
Currently I am implementing the custom error page for my Django Project. I have faced problem where when my project return the HttpResponse (404), the custom error page is not shown instead of, it shows the debug page. #in the views.py (i define 4 functions for error 400,403,404,500) but not for Http404 from django.shortcuts import render def page_not_found_view(request, exception): return render(request, 'error.html',status = 404,context = { 'status_code' : 404, 'message' : "The page you were looking for doesn't exist anymore.", 'title' : "Page Not Found" }) def internal_server_error_view(request, *args, **argv): return render(request, 'error.html',status = 500,context = { 'status_code' : 500, 'message' : "500 Internal Server Error.", 'title' : "Internal Server Error" }) def forbidden_error_view(request, exception): return render(request, 'error.html',status = 403,context = { 'status_code' : 403, 'message' : "403 Forbidden Error.", 'title' : "Forbidden Error" }) def bad_request_error_view(request, exception): return render(request, 'error.html',status = 400,context = { 'status_code' : 400, 'message' : "400 Bad Request Error.", 'title' : "Bad Request" }) #in the urls.py (link 4 error handler) hanlder400 = "gotani.views.bad_request_error_view" handler404 = "gotani.views.page_not_found_view" handler403 = "gotani.views.forbidden_error_view" handler500 = "gotani.views.internal_server_error_view" So my problem is, when the project return HttpResponse404, the custom error page is not shown normally. How can i override the … -
Can I get some help to fix the error I'm getting in my hosted Django app on Heroku?
here is the link to my Django app on Heroku where you can review the error : https://get-udemy.herokuapp.com/ how can i fix it please? -
does Laravel have choices in model? like Django
I'm wondering does Laravel have something like Django choices in models? for example in Django: Django document class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) -
What's the best way to store multi-select checkboxes (with the same values each time) in Django (PostgreSQL)?
I've got and Item and each Item should be able to select options from 3 checkboxes, and these checkboxes have the same values between all of them. I'm not sure on the best way to organise/store this. It will come back as an array from the browser, request.POST.getlist('options[]') so I had been thinking of using a JSONField: options = models.JSONField() But was also wondering if it's better as a ManyToManyField? The only thing stopping me there is that it's always the same 3 values, so they'd need to be populated into the database manually. Any opinions? -
Django queryset : I have a Employee model with below fields
Class Employee(models.Model): name = models.CharField(max_length=100) age = models.CharField(max_length=100) salary = models.CharField(max_length=100) I need to write a queryset to fetch all the details with an additional field called Group. So Group will set "A" if salary is grater than 10000 else "B". -
type object 'Case' has no attribute '_meta'
I keep getting the above error when i try to access the following URL. What am i doing wrong here? http://127.0.0.1:8000/case_portal/cases/ Model Class: (models.py) class Case(models.Model): id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=255, null=True) status = models.CharField(max_length=255) receipt_number = models.CharField(max_length=255) description = models.TextField() Serializer Class: (serializers.py) class CaseSerializer(serializers.ModelSerializer): class Meta: model = Case fields = ['id', 'name', 'status', 'receipt_number', 'description'] View Class: (views.py) class CaseViewSet(ModelViewSet): queryset = Case.objects.all() serializer_class = CaseSerializer def get_serializer_context(self): return {'request': self.request} -
Running Background task with possibility to check the current state?
I'm currently looking for an easy way to run a function that performs a shell command in the background and check if the task is still running or already completed. Short explanation of the goal: user calls a view the background function is triggered if the user calls the view again, instead of triggering a new background job, the user is told that the job is already running. I have already read about celery, django-background-tasks and django-cronjobs. Celery feels like overkill for my task. django-background-tasks seems perfect but has no way to check the current progress of the task or? What is a simple way to achieve the goal?