Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
term 'celery' is not recognized as an external function or cmdlet
I'm using Celery in my django application and when i'm trying to start celery worker with command: 'celery -A <project_name> worker -l info --pool=solo' it shows me an error that module 'celery' is not recognized, despite i've installed all necessary packages... >: celery worker --app=demo_app.core --pool=solo --loglevel=INFO : The term 'celery' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 celery worker --app=demo_app.core --pool=solo --loglevel=INFO ~ CategoryInfo : ObjectNotFound: (celery:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException I've also tried to add celery's path to PATH variable, but it throws this error anyway. -
I have installed django-user-accounts but the templates dont seem to exist
from account.views import ( ChangePasswordView, ConfirmEmailView, DeleteView, LoginView, LogoutView, PasswordResetTokenView, PasswordResetView, SettingsView, SignupView, ) urlpatterns = [ path('admin/', admin.site.urls), path("signup/", SignupView.as_view(), name="account_signup"), path("login/", LoginView.as_view(), name="account_login"), path("logout/", LogoutView.as_view(), name="account_logout"), path("confirm_email/<str:key>/", ConfirmEmailView.as_view(), name="account_confirm_email"), path("password/", ChangePasswordView.as_view(), name="account_password"), path("password/reset/", PasswordResetView.as_view(), name="account_password_reset"), path("password/reset/<str:uidb36>/<str:token>/", PasswordResetTokenView.as_view(), name="account_password_reset_token"), path("settings/", SettingsView.as_view(), name="account_settings"), path("delete/", DeleteView.as_view(), name="account_delete"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ -
How i can use "database_sync_to_async" function for fetching multiple object
I am implementing a consumer, and y want get all productos for example: class TeamConsumer(AsyncConsumer): async def get_all_producs(): products = await database_sync_to_async(Products.objects.all)() When i try fetch all products from the above code causes the error "You cannot call this from an async context - use a thread or sync_to_async." I know that query ar lazy, but, how i can get all products? -
How does discord manages roles and permissions in database?
Users can have multiple roles, roles have multiple permissions, and roles are protected by servers. I was wondering do they use relational db for that? Is django capable of doing such thing? Because to fetch each user for server with role will be very expensive. Does discord uses django for this or any other framework? Any thoughts please? I am trying to build a similar schema but I think it will be very expensive for the db transactions and queries. I have workspace, workspace have users, users have multiple roles, roles have multiple permissions(groups in djangos). And I think this will be very expensive to call a single user to check whether he belongs to this group or not. -
How do I translate the radio selection buttons?
I can change the language of all the other forms, the problem is that I don't know how to change the language through forms.py, because it wouldn't be the same as in the template, right? html <div class="mb-3"> <label class="form-label d-block mb-3">{% trans "Country" %}:</label> <div class="custom-radio form-check form-check-inline"> {{ form.pais }} </div> </div> forms.py PAIS = ( ('United States', 'United States'), ('Canada', 'Canada'), ('Other', 'Other'), ) class ClientesForm(forms.ModelForm): pais = forms.ChoiceField( choices=PAIS, widget=forms.RadioSelect(attrs={'class':'custom-radio-list'}), ) -
What is equivalent to TestCase.client in normal script
For example with TestCase I can check login post and so on with self.client class TestMyProj(TestCase): response = self.client.login(username="user@example.com", password="qwpo1209") response = self.client.post('/cms/content/up', {'name': 'test', '_content_file': fp}, follow=True) However now I want to use this in script not in test case. because this is very useful to make initial database. I want to do like this. def run(): response = client.login(username="user@example.com", password="qwpo1209") response = client.post('/cms/content/up', {'name': 'test', '_content_file': fp}, follow=True) What is equivalent to TestCase.client in normal script?? -
Django rest serializer can't handle object - TypeError: Object of type Hero is not JSON serializable
I have the below simple rest api set up in Django. Calling the url http://127.0.0.1:8000/listheros/ returns TypeError: Object of type Hero is not JSON serializable for a reason I can't seem to figure out. # views.py from rest_framework.views import APIView from rest_framework.response import Response from .serializers import HeroSerializer from .models import Hero class ListHeros(APIView): def get(self, request, format=None): """ Return a list of all users. """ queryset = Hero.objects.all().order_by('name') serializer_class = HeroSerializer print('get') return Response(queryset) # urls.py from django.urls import include, path from applications.api.views import ListHeros urlpatterns = [ path('listheros/', ListHeros.as_view()), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] # serializers.py from rest_framework import serializers from .models import Hero class HeroSerializer(serializers.ModelSerializer): class Meta: model = Hero fields = ('name', 'alias') # models.py from django.db import models class Hero(models.Model): name = models.CharField(max_length=60) alias = models.CharField(max_length=60) def __str__(self): return self.name -
How to use Property in Django Rest Framework model?
I am newbie to Django Rest Framework. I am have problem with using Property in Django rest framework My Model class AwsConsoleAccess(TimeStampedModel): _resources = CharField(max_length=4096) @resources.setter def resources(self, resources: List[str]): self._resources = ','.join(resources) @property def resources(self) -> List[str]: if self._resources: return self._resources.split(',') return [] My serializer class AwsConsoleAccessSerializer(ModelSerializer): class Meta: model = AwsConsoleAccess fields = '__all__' My view def post(self, request, *args, **kwargs): serializer = AwsConsoleAccessSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() My curl request http://localhost:8000/access/842b1012-53ef-4e98-9a20-484e681c3789 request body: { "resources": [ { "id": "dev-atm-jr1-platformcanary-APPLICATION" } ] } Response { "_resources": [ "This field is required." ] } status code - 400 bad request If I rename the resources to _resources in request_body it does not accept the List[str] . I wanted to set the List of string -
Test tags not found in Django project with nested apps
I have a Django project with nested apps layout, i.e. created with the following commands: django-admin startapp app cd app django-admin startapp app_nested Such layout was proposed by Dan Palmer in DjangoCon US 2021 and it works great for me. I’m really content with such organization of larger projects, but I failed to find an open source examples of its implementations. This causes problems with writing the details. Right now I struggle with unit test loader not finding the tests by tags in nested apps (tags in normal apps work fine). Consider the following example: @tag('testme') class SomeTest(TestCase): def test_foo(self): self.assertTrue(False) This test can be found by python manage.py test app/app_nested command, but python manage.py test --tag=testme runs 0 tests. Given that the first command works the test construction seems fine. How to make the test runner find tags from nested apps? Also, if someone knows some open source Django projects with nested apps structure this could be helpful as well. The current project is in Django 2.2, but this question refers to all Django distributions. -
Django migrations relations
Suppose we have two models, Person and Worker. Know, I want to alter the name of Person to InterestPerson. How does Django exactly knows that the new name belongs to the old one? I was looking in the generated tables in DB and in the migrations, but I can't figure out how is he able to make the relation. Same applies with fields, datatypes, lengths... etc. -
How to use while loop for showing more items in Django view?
I am making a small Django project, but I have an issue. When I write names to one form and topics to other one and press button, I want to see list of randomly attached names and topics. In my current code I don´t get a list but just one name and one topic. How can I solve that problem? My views.py file: from django.shortcuts import render from .losovaci_zarizeni import UvodniTabulka from random import choice def losovani_view(request): form = UvodniTabulka(request.GET) spoluzaci = request.GET.get("spoluzaci") temata = request.GET.get("temata") spoluzaci_list = spoluzaci.split() temata_list = temata.split() while True: spoluzak = choice(spoluzaci_list) spoluzaci_list.remove(spoluzak) tema = choice(temata_list) temata_list.remove(tema) if len(spoluzaci_list)==0: break return render(request, "losovani.html", {"form":form, "spoluzak": spoluzak, "tema":tema}) My file with UvodniTabulka: from django import forms class UvodniTabulka(forms.Form): spoluzaci = forms.CharField(max_length=500) temata = forms.CharField(max_length=500) -
why is dynamic path not working in djnago
so i tried to make a dynamic path in django but when i pass 'frame' as argument in the view function 'details_meetups' that error show up function i got this error. error image urlpatterns = [ path('admin/', admin.site.urls), path('BookList', BookList.views.index), path('BookList/<frame>', BookList.views.Meetup_Details)] def Meetup_Details(request,frame): selected_one = {"name":"jacob", "description":"tall"} return render('request,BookList/meetup-detail.html',{ "name" : selected_one["name"], "description" : selected_one["description"] } ) -
How to follow the redirct and test again in test script
I have this test script for uploading file with open('_material/content.xlsx','rb') as fp: response = self.client.login(username="user@example.com", password="qwpo1209") response = self.client.post('/cms/content/up', {'name': 'test', 'content_file': fp,"is_all":"True"}) self.assertEqual(response.status_code,302) # it shows ok #then next, how can I follow the redirect and test the page?? self.assertContains(response, "success!") It returns the redirect 302 but I want to follow the redirect and nect check. Because there comes the message such as success! Is it possible? -
1 always not match in Django re_path regular expression
I try to create a dynamic path which accepts either null or positive integer. For example: http://127.0.0.1:8000/my_url/ http://127.0.0.1:8000/my_url/23 in url.py: from django.urls import path, re_path urlpatterns = [ re_path(r'^my_url/(\s*|[0-9]{0,})$', views.my_function, name='my_function'), ] in view.py: def my_function(request, my_id): if my_id == '': #Do somthing else: #Do another somthing Strange thing is: followings passed in my test: http://127.0.0.1:8000/my_url/ http://127.0.0.1:8000/my_url/2 http://127.0.0.1:8000/my_url/10 The only one that failed (meaning return to 404, no url found) is: http://127.0.0.1:8000/my_url/1 why only '1' does not match? Is 1 treated specially in re_path function? -
UnicodeDecodeError: 'utf-8' codec can't decode, when uploading from testscript
I am making test script to upload excel file, def test_upload(self): c = Client() with open('_material/trick.xlsx') as fp: c.post('/cms/template/up', {'name': 'fred','content_file': fp}) There comes the error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 16: invalid start byte However in html upload form, there is no error occurs. class UploadTemplateFileForm(BaseModelForm): content_file = forms.FileField(required=True) Why this difference occurs? -
DJango rest framework - API list using filter field from related models
Hi I'm new to Django and the Django rest framework so my terminology may be off. I'm trying to build an API that gives back a list of items from a model but filtered based on fields in another related model. I'll provide my current view and serializer classes and models class service(models.Model): name = models.CharField(max_length=50) vendor = models.CharField(max_length=50) version = models.CharField(max_length=10) registration_status = models.BooleanField(default=False) class service_network(models.Model): service = models.OneToOneField( service, related_name='network', on_delete=models.CASCADE, primary_key=True, ) forwarded_port = models.CharField(max_length=50) class ServiceNetworkSerializer(serializers.ModelSerializer): class Meta: model = service_network fields = '__all__' class ServiceSerializer(serializers.ModelSerializer): network = ServiceNetworkSerializer() class Meta: model = service fields = [ 'id', 'name', 'vendor', 'version', 'registration_status', 'network', ] class ServiceAPI(ModelViewSet): queryset = service.objects.all() serializer_class = ServiceSerializer filterset_fields = '__all__' Currently I can get back lists using a URL query string {{baseUrl}}/engine/service?registration_status=true What I want to do is something like this {{baseUrl}}/engine/service/network?farwarded_port=8080 Which I would expect to give back a list of services where the related network field "forwarded_port" is equal to 8080. Is there another way to query this API? Maybe using a POST with a body containing the query? If there something in the DOCS that I can read, I've tried to look through filtering and querysets but I … -
How to write unit test for deleting a model instance in django admin
I have to override def get_deleted_objects(self, objs, request): function in order to abort the deletion process in Django admin, now I want to write a unit test for the same. def get_deleted_objects(self, objs, request): if condition: self.message_user(request, "You cannot delete this instance", messages.ERROR) return [], {}, {MyModel._meta.verbose_name.title()}, [] return super().get_deleted_objects(objs, request) -
how to fetch parent table field value using queryset object in django template
I have below models - Parent table - class RoomCategory(models.Model): trust = models.ForeignKey(Trust, on_delete=models.CASCADE, blank=True, null=True) *category = models.CharField(max_length=50,db_index=True)* rate = models.FloatField() description = models.CharField(max_length=500, blank=True, null=True) num_guests = models.IntegerField(blank=True, null=True) num_bedrooms = models.IntegerField(blank=True, null=True) num_beds = models.IntegerField(blank=True, null=True) num_toilets = models.IntegerField(blank=True, null=True) child table1 having above room category pics as below class RoomCategoryAttribute(models.Model): trust = models.ForeignKey(Trust, on_delete=models.CASCADE, blank=True, null=True) category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE, blank=True, null=True) *image=models.ImageField(upload_to="room_cat_imgs/",null=True)* child table2 having booking details class Booking(models.Model): trust = models.ForeignKey(Trust, on_delete=models.CASCADE, db_index=True,blank=True, null=True) *category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE, blank=True, null=True)* user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) check_in = models.DateTimeField(db_index=True) check_out = models.DateTimeField(db_index=True) phone_no = models.IntegerField(blank=True, null=True, db_index=True) num_days = models.IntegerField(blank=True, null=True) total_cost = models.IntegerField(blank=True, null=True) when_booked = models.DateTimeField(blank=True, null=True, db_index=True) I have a below queryset in my views.py - booking = Booking.objects.all() In my template I am iterating over the above booking query set to show the bookings in cards as below {% for booking in booking_list %} Now the question is - in the cards - how do I show the first image from the child table1 i.e. RoomCategoryAttribute which has multiple rows of several images per RoomCategory - as I think there is some way to use ***_set.first.image and I … -
Ajax success function does not triggered
i have a comment system in django. I am trying to make post request with ajax, information in the form stored in database, but ajax success function doesn't work. So, this is my ajax post method $('#parentComment').submit(function(e){ e.preventDefault(); const url = $(this).attr('action'); const btn = $('.comment-btn').attr('name'); const body = $('#parentCommentText').val(); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'btn': btn, 'body': body, }, sucess: function(response){ console.log(response) }, error: function(response){ alert('error'); } }); }) So this is views.py file class Articlepage(View): def get(self, request, pk, *args, **kwargs): article = Articles.objects.get(id=pk) comments = article.messages_set.all() likes_count = article.likes.count() context = {'article': article, 'comments': comments, 'likes': likes_count} return render(request, 'base/main_article.html', context) def post(self, request, pk, *args, **kwargs): article = Articles.objects.get(id=pk) comments = article.messages_set.all() likes_count = article.likes.count() if 'parent-comment-submit' in request.POST['btn']: try: value = request.POST.get('parent') parent = Messages.objects.get(id=int(value)) except: parent = None body = request.POST.get('body') if body: comment = Messages.objects.create( user = request.user, article = article, parent = parent, body = body, ) return JsonResponse({'body': comment.body, 'user': comment.user.username, 'parent':parent}, safe=False) return JsonResponse({}, safe=False) -
Django Rest Framework - Way to make specific values within two columns in parent table a constraint to be only used together in child table as fk?
not sure I worded my question right in the title, let me try and explain better below... Let's say a parent table called Share has two columns, a ShareCode Charfield(primary key) and a ShareName unique Charfield (string). This means we'll have a unique ShareCode and ShareName paired on each row of this table. Code for this below. class Share(models.Model): ShareCode = models.CharField(max_length=100, primary_key=True, default="N/A") ShareName = models.CharField(max_length=100, unique=True, default="N/A") Now let's say we have a child table, Fund. This table will consist of a FundID Autofield(primary key), a FundCode Charfield, and a FundName CharField. It will also have two foreign keys that reference the Share table, ShareCode and Sharename. Finally, it will have two unique_together constraints, FundCode and ShareCode as the first constraint, and FundCode and ShareName as the second. Code below. class Fund(models.Model): FundID = models.AutoField(primary_key=True) FundCode = models.CharField(max_length=100, default="N/A") FundName = models.CharField(max_length=100, default="N/A") ShareCode = models.ForeignKey(Share, to_field='ShareCode', related_name='fundsShareCode', on_delete=models.CASCADE) ShareName = models.ForeignKey(Share, to_field='ShareName', related_name='fundsShareName', on_delete=models.CASCADE) class Meta: unique_together = ('FundCode', 'ShareCode'), unique_together = ('FundCode', 'ShareName') Couple of things to note at this point, let's imagine that every share that we could possibly need is already in the Share table. The fund table's data however is being manually input … -
django rest framework update user profile
how can update user object with extended profile model, i want to get fields in one object like: { username, email, [...], gender, avatar, } models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): GENDER_CHOICES = (('Male', 'Male'),('Female', 'Female')) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=6, blank=True, choices=GENDER_CHOICES) avatar = models.ImageField(upload_to=avatar_upload, default='avatars/default.png') serializers.py from .models import Profile from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='user-detail', lookup_field='pk', read_only=True) pk = serializers.IntegerField(read_only=True) class Meta: model = User fields = ('pk', 'username', 'email', 'first_name', 'last_name', 'url') class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('gender', 'avatar',) views.py class UserUpdateView(APIView): def put(self, request, *args, **kwargs): pass -
How get # fragment values from the URL in Django
In my Django website, I want to redirect to an external website, authenticate on this external website and then the external website returns an API token that I want to save. I have instructed the external website to redirect to 127.0.0.1:8000 (my home page) after I have successfully authenticated. When I'm redirected, I have a URL in this format: http://127.0.0.1:8000/#access_token={token the external website generates}&token_type=Bearer&expires_in={expiry time}. How can I get the values after the # in the URL? As I understand the values after the # is not sent back to the Django server. -
Django Model.objects.last() returning second to last instance instead of the very last instance
I'm in the process of building a Django app, which is meant to be a self updating inventory app for a hypothetical restaurant. I have a model, "Purchase", which uses another model "Register" as a ForeignKey field. I have it set the reference to the last instance created of Register so that any entree purchase is linked to the currently active register at the store. The problem is that when a Purchase instance saves, it keeps referencing the second to last Register object instead of the last. Here is the current model code for those two models: class Register(models.Model): daily_bank = models.FloatField(default=500) amount_spent = models.FloatField(default=0) amount_made = models.FloatField(default=0) date = models.DateField(default=date.today) def sales(self): lst = [] for p in self.purchase_set.all(): if p.menu_item not in lst: lst.append([p.menu_item.title, 1]) else: for entry in lst: if entry[0] == p.menu_item.title: entry[1] = entry[1] + 1 return lst def profit(self): if self.id > 1: return self.daily_bank - Register.objects.get(id=self.id-1).daily_bank else: return self.daily_bank - 500 def last(self): return self == Register.objects.last() class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=SET_NULL, null=True) time = models.DateField(default=datetime.now) item_name = models.CharField(max_length=100) register = models.ForeignKey(Register, on_delete=CASCADE, default=Register.objects.last()) def save(self, *args, **kwargs): self.item_name = self.menu_item.title if self.pk is None: for i in self.menu_item.reciperequirment_set.all(): if i.menu_item == … -
Steam API json output isn't being displayed cleanly
I've been trying to get the output from the steam API to display in my django app. My goal is to create a "portfolio" of games that I own for a project - using the information in the Steam API. I'm fairly new to Django, but know enough to be dangerous. Any help would be greatly appreciated, as I have been banging against this for a week... My question is, how does one pull specific items from the json and display the data correctly inside of the template? I cannot seem to loacte a tutorial that fits the schema of the output from this API. - any help (and a brief explanation maybe) would be greatly appreciated. For example, how can I capture the minimum system requirements from the API and display them in a div on my page? This is my views.py: def index(request): response = requests.get('https://store.steampowered.com/api/appdetails/?appids=218620').json() return render(request, 'index.html', {'response': response}) While it actually returns data, you'll notice that the data is littered with weird characters and such. Here is my index.html: {% extends 'base.html' %} {% block content %} {{response}} {% endblock %} if you add a 'safe' tag to the django template like this: {% extends … -
how to use django redirect when we have dynamic url
i have dynamic uls urlpatterns=[path('author/<str:pk>/',views.authorview,name='author')]` and i want to use it in redirect def loginview(request):` `if request.method=='POST':` `username = request.POST.get('username')` `password = request.POST.get('password')` `user = authenticate(request, username=username, password=password)` `if user is not None:` ` login(request, user)` `return redirect('profile')` # i want to use it here else: return redirect('/blogapp/signup/') #context={'username':username,'password':password} return render(request,'blogapp/loginview.html')` i am not able to use this (/str:pk/) on redirect