Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django webpack assets too big
I have a Django project which doesn't use anything "fancy" like React or Vue (yet). It just uses the native Django templating system. Until now, I've been using gulp to generate the assets for it but I thought I'd experiment with webpack, as it seems like a good idea for various reasons. However, when I use webpack, it stuffs everything I need for my entire site into a small number of files, which I have to link to on every page of the site. For instance, there is an image I use just for the front page which is managed by webpack. So it goes into the main css file and makes that file very large, considering that image is only needed on one page. There are also a variety of 3rd party JS scripts that get pulled in because they are just here and there, so the main JS file is vast too. I've looked into code splitting a bit and that does give me an extra file for the vendors' stuff but it's still massive and obviously contains tons of stuff that is not used on every page. Am I doing the wrong thing by trying to make … -
Is There a way of returning a queryset of the first instance of a specific field from a django model
Say i have a model called Workout, and its populated as such I want to return a queryset of the first instance of each new date filterd by the current user. In this case, if the current logged in user is user_id = 1, the queryset would contain the workout objects with id 1,4 and 5. Is there a way of achieving this using a Workout.objects... method? Cheers. -
Neither set() nor add() django add to database entry
I have the following problem: I have a manytomanyfield (in model Toppings) and I can't populate it. I first tried using a list and set() and then I tried using just one object and add() in views.py but neither will return anything else than none. I have been looking at documentation and other forum questions but I just can't figure it out. Any help is greatly appreciated! views.py from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.core import serializers from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import render from django.urls import reverse from orders.models import Meal, Topping, Order def order(request): # Request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": # Get IDs of meal, topping(s) and user idmeal = request.POST["idmeal"] idmeal = Meal.objects.get(pk = idmeal) # Topping[] is a list of numbers representing IDs for Topping database topping = request.POST.getlist('topping[]') for i in range(0, len(topping)): topping[i] = int(topping[i]) user = request.user userID = User.objects.get(username=user.username) topping = Topping.objects.filter(pk__in=topping) print(topping) # Create object in Order table order = Order.objects.create(customerID = userID, mealID = idmeal, price = 12, status = "pending") # Add values to ManyToManyField order.toppingsID.set(topping) print(order.toppingsID) return JsonResponse({"success": ""}, status=200) … -
Django + Jinja. Can't choose an element of dictinary
There is a dictinary of lists which I can render in Jinja template with that: {{ data.production_report.main_info }} So the Jinja template shows it: {"product_list":[{"name":"Mushroom soup","amount_got":"10"}],"decreasing_product_list":[{"name":"Chicken meat","amount_used":"6","amount_got":"3","loss_ratio":"50%"}]} The problem is that Jinja template can't render next things: {{ data.production_report.main_info.product_list }} {{ data.production_report.main_info.decreasing_product_list }} -
DRF: Best way to supply a dynamic default field value?
Our SAAS site utilizes a DRF backend with a Vue frontend. We have fields that do not require a value from the user, but do require a value in the database. I'd like to know where's the best place to supply such dynamic defaults. I've read in other posts that "save() is not always called" - though I don't yet know the circumstances where it would not be called. So, consider the following model: class Tenant(models.Model): name = models.CharField(max_length=100) subdomain = models.CharField(max_length=100, blank=True, null=True) schema_name = models.CharField(max_length=63, unique=True) In this case, only "name" is required (from the user); "schema_name", if left blank in the frontend form, can be derived from "name" (converting it to lowercase). Likewise, "subdomain" can be derived from "schema_name". "subdomain" can be blank/null because the "public" schema doesn't reference a subdomain, but its value will be required for all tenants other than "public".) So where should I put the code that populates those fields if they are blank when it comes time to create or update a Tenant? -
How can I disable a signal in a Django TestCase that uses fixtures?
How can I disable a signal for all tests within a Django TestCase when I create data using fixtures? The following approach adapted from this answer does not work unfortunately. I suppose fixtures are applied before the setUp stage. from django.db.models import signals from django.test import TestCase class MyTestCase(TestCase): fixtures = ["offers.json", "agents.json"] def setUp(self) -> None: signals.post_save.disconnect(sender=MyModel, dispatch_uid="some_signal_uid") def test_some_test(self): # do something @receiver(post_save, sender=MyModel,dispatch_uid="some_signal_uid") def some_signal(sender, instance: MyModel, created: bool, **kwargs): # do something -
How to fix Django models migrate error for image field?
I am putting an image field in a model called Students. Everything is working fine until I put an image field into the model. I am getting the following even I put blank and null as True. It should work fine. Following is the detail information. Error django.db.utils.IntegrityError: NOT NULL constraint failed: new__genius_students.image This is the model models.py class Students(models.Model): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, default=1, null=True) name = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to='images/', null=True, blank=True) dob = models.DateField(null=True, verbose_name='Date of Birth') age = models.IntegerField() I had tried many things like clearing cache and cookie. But No luck. -
How to implement like/dislike button (for logged-in users) in django using AJAX
I tried implementing Like(for those users who didn't like) and Dislike(for users who already liked the post) buttons but I could not get it to work. I tried looking some past questions but I could not solve the issue. If someone has done this before, kindly help. my blog/models.py for Post model class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def total_likes(self): return self.likes.count() my blog/views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True return render(request, 'blog/post_detail.html', {'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), }) def like_post(request): post = get_object_or_404(Post, id=request.POST.get('id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), } if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) my HTML and AJAX code (this section is present in post_detail.html) <div id="like-section"> {% include 'blog/like_section.html' %} </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="text/javascirpt"> $('#like').click(function(){ var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: "like_post", data: { 'id':pk, }, success: function(response){ $('#like-section').html(response['form']) }, }); }); </script> like-section.html is a separate template :- <p>{{ total_likes }} Like{{ … -
How to make a div appear after post request and stay same page
I am trying to register and verify number in the same page. When I send post request to register there is phone field in data. Then view sends verification code to the this number. Now I want stay same page and make the confirm div appear after register request and confirm the verification code with appeared div. https://imgur.com/f3pGkN2 https://imgur.com/bOHhXMK -
Django: When print a QuerySet gives an error
I have a table(SavedSchedules) below in the database. hall_n_time and schedule columns stores two python lists as string. +----+---------------+-------------+----------+ | id | lecturer | hall_n_time | schedule | +----+---------------+-------------+----------+ |... | ... | ... | ... | +----+---------------+-------------+----------+ I have below script in views.py: lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True) print(lec_name) This gives OUTPUT: <QuerySet ['A. B. C. Watson']> But EXPECTED OUTPUT: A. B. C. Watson Then I tried below script: lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True) schedule_data = SavedSchedules.objects.filter(lecturer=lec_name) print(schedule_data) It gives below ERROR when I execute it: Traceback (most recent call last): File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Web Projects\CIS_ALTG\altg\altg_app\views.py", line 497, in profile print(schedule_data) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 276, in __iter__ self._fetch_all() File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1124, in execute_sql sql, params = self.as_sql() File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 498, in as_sql where, w_params = self.compile(self.where) if self.where is not None else ("", []) File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 415, in compile sql, … -
Use a code executing every hour in Django
I'm using Django for developing an app for booking cars, then I need an automated code to check if a car is booked automatically every hour, I'm new in Django and I don't have idea how to do this -
How to get data from ModelViewSet in DRF without calling an API call
I'm going to convert all my APIs into gRPC calls. At the moment I was able to transfer all the ViewSet into gRPC(sample code added end of this question). But ModelViewSet, it get an error like this. Traceback (most recent call last): File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/venv/lib/python3.6/site-packages/grpc/_server.py", line 435, in _call_behavior response_or_iterator = behavior(argument, context) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/servicers/tenant/main.py", line 15, in get_tenant data = ClientViewSet().list(request=original_request, ) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/common/lib/decorators.py", line 128, in wrapper_format_response final_data = call_func(func, self, request, transaction, exception, *args, **kwargs) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/common/lib/decorators.py", line 99, in call_func return func(self, request, *args, **kwargs) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/api_v1/viewsets.py", line 471, in list data = super().list(request, *args, **kwargs).data File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/venv/lib/python3.6/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "/home/wasdkiller/PycharmProjects/ocsa/dataengine-service/venv/lib/python3.6/site-packages/rest_framework/generics.py", line 158, in filter_queryset queryset = backend().filter_queryset(self.request, queryset, self) AttributeError: 'ClientViewSet' object has no attribute 'request' So my viewsets.py look like this (format_response decorator convert it to Response object) class ClientViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ser.ClientSerializer @format_response(exception=False) def list(self, request, *args, **kwargs): data = super().list(request, *args, **kwargs).data # data = {} return data, True, HTTPStatus.OK, 'data retrieve successfully' When I call this as an API, it works perfectly. But I want to do the same thing without calling an API. Here how I was solving it, from django.http import … -
Heroku app successfully deployed, but getting application error when loading site
can someone please help to get error in log files Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Don't know what to do now -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.8.2 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 130 static files copied to '/tmp/build_b1535ec053fdba9963297a3644bcd70a/staticfiles', 410 post-processed. -----> Discovering process types -----> Compressing... Done: 55M -----> Launching... Released v8 https://hwcount.herokuapp.com/ deployed to Heroku -
Django form validation on PIN number
I have a Integerfield in my ModelForm which should contains data between 100000 & 999999. Facing issues in validation. I tried lots of combinations , but doesn't help. from django.forms import ValidationError class myForm(forms.ModelForm): pin = forms.IntegerField(label="PIN : ", required=True) def clean(self): if self.cleaned_data.get('comppin') <= 999999 & self.cleaned_data.get('comppin') >= 100000: try: return int(self.cleaned_data['comppin'].strip()) except ValueError: raise ValidationError("Invalid number") from django.core.validators import MaxValueValidator, MinValueValidator class Company(models.Model): comppin = models.PositiveIntegerField( validators=[MinValueValidator(100000), MaxValueValidator(999999)]) Maybe I am doing something wrong. Need help in this step. -
Attempted relative import beyond top-level package with Python
I have seen several questions related to this error but I think they are different cases. My Django project has 2 applications and a directory structure like this and I'm facing an issue with relative imports I don't understand the logic. Python allows me to import market from file my_app2/signals.py but it returns ValueError: attempted relative import beyond top-level package if I import portfolio from file my_app1/signals.py. What is the reason and how can I found a wordaround? /my_project /my_project /my_app1 /market.py /signals.py # From this file I'd like to import portfolio.py /my_app2 /portfolio.py /signals.py Files content: my_app1/signals.py from ..my_app2 import portfolio # doesn't work my_app2/signals.py from ..my_app1 import market # works -
How do i validate a extended user's field against a secondary (not the default) database in Django?
forms.py: class CustomUserCreationForm(forms.Form): username = forms.CharField() email = forms.EmailField() personalid = forms.IntegerField() password1 = forms.CharField() password2 = forms.CharField() def clean_username(self): username = self.cleaned_data['username'].lower() r = CustomUser.objects.filter(username=username) if r.count(): raise ValidationError("There is a user with that username already!") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = CustomUser.objects.filter(email=email) if r.count(): raise ValidationError("There is already a user with that email!") return email def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Password don't match!") return password2 def save(self, commit=True): customuser = CustomUser.objects.create_user( self.cleaned_data['username'], email = self.cleaned_data['email'], password = self.cleaned_data['password1'], personalid = self.cleaned_data['personalid'] ) return customuser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email','personalid') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields settings.py: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'default', 'USER': 'default', 'PASSWORD': 'defaultpassword', 'HOST': '127.0.0.1', 'PORT': '8243' }, 'secondary': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'secondary', 'USER': 'secondaryuser', 'PASSWORD': 'secondarypassword', 'HOST': '127.0.0.1', 'PORT': '11371' } I want to validate 'personalid' field against 'secondary', if 'personalid' exists in 'secondary', then the user can be created, else, prompt error message! Any help is well appreciated! Bless -
Django3 using MySQL - Read-and-update in single transaction
The default isolation level does not allow the following code to work; separate processes can read the same value, set the same value, and cause a miscount. def next_id(): with transaction.atomic(): db_counter = Counter.objects.filter(name=name).first() if not db_counter: # Create count if not exists db_counter = Counter.objects.create(name=name, count=0) count = db_counter.count db_counter.count = count + 1 db_counter.save() return count Some things I have looked at: Setting the isolation level to serializable works, but I fear that is too restrictive. The rest of the application is working just fine with repeatable read. The select_for_update might work, but I do not know how to apply it in the case there is no counter, and a record must be added. I have traced through the Django/MySQL code with the debugger: I am not certain transaction.atomic() does anything, I do not see it emit a START TRANSACTION. How do I ask Django to start a transaction? Thank you. -
Getting data from an API and not from Database
Morning, everybody, I'm an apprentice developer, and I have to develop a REST API with django. So far no problem. The trick is that I don't have to work from a database, but from a Python API in which I use functions that return the data I have to serialize. I put this schema here for you to better understand (the one on the right is the one used by my company) schema of API/DB/FRONT relation I have no problem to get datas and return them on endpoint, my problem is when I want to PUT, DELETE request. My DELETE request works with Postman, but when I trigger it from my forehead in sight, I get a 301 redirection error... For the other requests, I don't see how I can get the data from my form in my Vue Frontend and then pass it as an argument to the python function in Django which must insert it in the db ... Thanks in advance for your help Pixi -
Dose not appear to have any pattern in it
File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Arslan\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
ValueError: Field 'id' expected a number but got 'host'
Django returns me ValueError during migration. It expects ID. I'm new to Django btw. and it's my 3rd project. In others there is not such a problem with User Foreignkey. Can someone help me ? from django.db import models from django.contrib.auth.models import User class Room(models.Model): hosted = models.ForeignKey(User, on_delete=models.CASCADE, related_name="hosted_by") name = models.CharField(max_length=50, ) is_played = models.BooleanField(default = False) max_players = models.IntegerField(default = 4,) players_online = models.IntegerField(default = 1) players_ready = models.IntegerField(default=0) def __str__(self): return self.name -
Django form validation vs DRF serializer validation
I'm new to APIs creation in django. I checked DRF serializers and I found them useful when manipulating models in DB. My APIs don't use models they are based on forms. So my question is : what can I get more from using DRF validators then using django forms validators in my views ? maybe the content type is more convenient (application/x-www-form-urlencoded vs application/json) ? -
How can I access a Django models
I've three Django models ModelA, ModelB and ModelC. In my logic either an instance of ModelB or ModelC is associated with ModelA via a OneToOne relationship. I'd like to access the field of_interest via ModelAs backwards relationship to ModelB or ModelC. Is this possible? class ModelA(models.Model): ... class ModelB(models.Model): model_a = models.OneToOne( ModelA, related_name='%(class)s_model_a', of_interest=..., ... ) class ModelC(models.Model): model_a = models.OneToOne( ModelC, related_name='%(class)s_model_a', of_interest=..., ... ) -
Why isn't my for loop executing three times?
I expect three columns but the output gives only one column.It seems like the for loop is executing only once. This is my HTML code ''' <div class="row"> {% for head in heads %} <div class="col-lg-4"> <div class="single-bottom mb-35"> <div class="trend-bottom-img mb-30"> {% if head.latest %} <strong>Latest</strong> {% endif %} <img src="{{baseURL}}/{{head.img}}" alt=""> </div> <div class="trend-bottom-cap"> <span class="color1">{{head.head}}</span> <h4><a href="details.html">{{head.summ}}</a></h4> </div> </div> </div> {% endfor %} </div>''' This is views.py I have introduces three objects. ''' head2=News() head2.head='Coronavirus Updat' head2.summ='Deaths cross 2Lac World Wide' head2.img='2.png' head2.latest=True head2.id=False head3=News() head3.head='Coronavirus Updates' head3.summ='Deaths cross 2Lac World Wide' head3.img='2.png' head3.latest=True head3.id=False head4=News() head4.head='Coronavirus Updates' head4.summ='Deaths cross 2Lac World Wide' head4.img='3.png' head4.latest=False head4.id=False heads={head2,head3,head4} return render(request,"index.html",{'head1':head1,'heads':heads})''' The output prints only one column. I expect Three of them. -
Creation of slots at regular intervals
I need to create time-slots according to a number of songs. For example, s if my playlist has 5 songs then we create the time-interval of slots by the logic, 60/5 = 12 minutes in this example as the number of songs was 5 here. I also provide the start_time and end_time. Here if I provide start_time = 5:00 am and end_time = 6:00 am, total songs = 5 S1: 5:00 - 5:12 S2: 5:12 - 5:24 S3: 5:24 - 5:36 S4: 5:36 - 5:48 S5: 5:48 - 6:00 The Model consists of these three fields: class SlotCreate(models.Model): from_time = models.TimeField(max_length=255, blank=True, null=True) to_time = models.TimeField(max_length=255, blank=True, null=True) songs = models.ManyToManyField('Song') labelling = models.ForeignKey('Labelling',blank=True, null=True) I am checking whether the slot exists with the following query: SlotCreate.objects.filter(from_time=from_time,to_time=to_time,labelling=label).exists(): errors.append("The Slot already exists "+"\n") The problem here is if the user provides: Start_time = 5:00 End_time = 6:00 Total songs = 3 Then the slots already exist in the time interval given above as S1, S2, S3, S4, S5 are already there. The piece of code with which I check above fails to determine this case as S1: 5:00 - 5:20 S1: 5:20 - 5:40 S1: 5:40 - 6:00 Can anyone help … -
how to use name in filtered list to find their origin from model `Item`
class Item(): name=models.CharField(max_length=200) origin=models.CharField(max_length=200) class Condition1(): name=models.CharField(max_length=200) size=models.DecimalField(decimal_places=2,max_digits=1000) weight=models.DecimalField(decimal_places=2,max_digits=1000) a=Condition1.objects.filter(size__gt=20, weight__lt=10) when i print a as <table>{% for item in a%} <tr><td>{{ item.name}}</td></tr>{% endfor %}</table> it gives list as Item1, Item10, Item13 in table. so now i want to print their origin and i wrote: origin=Item.objects.filter(name__in=a) however it does not give me anything. I want to use name in filtered list a to find their origin from model Item. How to make it work. What i am missing?