Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"'str' object is not callable" after I tried to break the circular import (Django)
I have been trying to solve this circular import issue in order to implement unit testing without failure. If I may show you the short version of the previous solution I got: This.... serializer_class = serializers.CompanyMappingSerializer should be changed to This: serializer_class = "serializers.CompanyMappingSerializer" After doing this, the unit tests run fine. However, when I run the api with POSTMAN, it shows this error: TypeError at /api/v1/company/ 'str' object is not callable What should I do in this situation? -
No Icons Shown in the Django admin with DO Spaces
After moving my static files to DigitalOcean Spaces. I can't see Django admin icons. But I can see those image files in the Object Storage. What is the reason for that -
Writing serializer errors to the logger. Django rest
I have a logger that records actions in a view. I successfully record all completed requests, but I cannot figure out how to write validation errors of the serializer, for example, if I entered a date out of format, I want to write to the logger logger.warning('Error Incorrectly entered data {}'.format(Output serializer error here) Where and how should I log my message to the logger? my code views.py logger = logging.getLogger(__name__) class EventView(viewsets.ModelViewSet): queryset = Event.objects.all() lookup_field = 'pk' serializer_class = EventSerializer permission_classes = [ProjectPermission.IsPartner | ProjectPermission.IsAdmin] def perform_create(self, serializer): serializer.save(partnerId=self.request.user.user) @action(detail=True, methods=['get']) def getEvent(self, request, *args, **kwargs): response = self.retrieve(request, *args, **kwargs) logger.debug('Event {} name was get'.format(response.data)) return response @action(detail=True, methods=['put']) def putEvent(self, request, *args, **kwargs): response = self.update(request, *args, **kwargs) logger.debug('Event {} was change'.format(response.data)) return response @action(detail=True, methods=['delete']) def deleteEvent(self, request, *args, **kwargs): response = self.destroy(request, *args, **kwargs) logger.debug('Event {} was delete'.format(response.data)) return response @action(detail=True, methods=['post']) def postEvent(self, request, *args, **kwargs): response = self.create(request, *args, **kwargs) logger.debug('Event {} was delete'.format(response.data)) return response serializers.py class EventSerializer(serializers.ModelSerializer): start_date = serializers.DateTimeField(format='%d-%m-%YT%H:%M:%SZ') end_date = serializers.DateTimeField(format='%d-%m-%YT%H:%M:%SZ') class Meta: model = Event fields = ('id', 'title', 'description', 'start_date', 'end_date', 'cover_page_url', 'address', 'city', 'sportType', 'participantLimit', 'generalInformation', 'enabled', 'partnerId' ) extra_kwargs = {"partnerId": {'read_only': True}} -
Better way to query from multiple tables using django ORM
I have the following models: class Client(BaseModel): #other fields engineers = models.ManyToManyField(Engineer, null = True, blank = True, related_name='clients') class OrganizationMember(MPTTModel): designation = models.CharField(max_length = 100, blank = True) user = models.OneToOneField(User, on_delete=models.CASCADE) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.SET_NULL) Now I would like to get all engineers of a client instance and check if each engineer has an organizationmember instance or not. Then if they belong to some organization then I should get_ancestors of that organizationmember and then the users. If they do not have any organizationmember then just get the user of that engineer instance. For this I have written a method in Client model as below: class Client(BaseModel): def get_users_from_engineers(self): users_in_organization = [] users_outside_organization = [] engineers = self.engineers.all() if engineers: for engineer in engineers: user = engineer.user if hasattr(user, "organizationmember"): users_in_organization += [orgmember.user for orgmember in user.organizationmember.get_ancestors(include_self=True)] else: users_outside_organization.append(user) Now this code is working correctly but I am sure that I can use django filters here instead of two for loops and optimize this code. But I do not know how. For eg: OrganizationMember.objects.filter(user__engineer__in=self.engineers.all()) can be used to get all the organizationmembers of the engineers of that particular client instance. But I need the users of … -
I want to update a boolean field in a different model using a foreign key
I have a unit model and a tenant model. ` class Unit(models.Model): property_name = models.ForeignKey('Property', on_delete=models.CASCADE) unit_name = models.CharField(max_length=300) floor = models.IntegerField() unit_type = models.CharField(max_length=300) rent_value = models.IntegerField() occupied = models.BooleanField(default=False) def __str__(self): return '%s' % (self.unit_name) class Tenant(models.Model): property_occupied = models.ForeignKey('Property', blank=True, default=None, on_delete=models.CASCADE) unit_occupied = models.OneToOneField('Unit', unique=True, on_delete=models.CASCADE, related_name='tenant') first_name = models.CharField(max_length=300) last_name = models.CharField(max_length=300) id_number = models.IntegerField(unique=True) phone_number = models.IntegerField(unique=True) date_occupied = models.DateField(auto_now_add=True) def __str__(self): return '%s, %s, %s' % (self.unit_occupied, self.first_name, self.last_name)` I want to update the unit.occupied field to true whenever I add a tenant and false whenever I delete a tenant.I want to do it automatically. I'm using a onetoone field on the tenant model to assign a unit to a tenant because a unit can only have one tenant I am using a tenant_form to add tenants and a unit_form to add a unit. How can I update the specific unit_occupied field for the tenant i'm adding automatically when i add/delete a tenant? This is my views.py: ` def add_tenant(request): form = AddTenantForm if request.method == 'POST': form = AddTenantForm(request.POST) if form.is_valid(): form.save(commit=True) messages.success(request, 'Tenant added successfully') # units = Tenant._meta.get_field('unit_occupied').remote_field.model # for unit in units: # ou = unit # if ou.occupied … -
matplot with click event to webserver
I have seen many cases where matplot is imaged and rendered on a website. However, is it possible to show a plot with a click event on the website and make the click event work on the website? python - plot with click event import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set(xlim=[-2, 2], ylim=[-2, 2]) ax.set_aspect('equal', adjustable='box') line, = ax.plot([], [], color='k', linewidth=2) def move_cursor(event): if event.inaxes != ax: return x = event.xdata y = event.ydata line.set_data([0, x], [0, y]) plt.draw() plt.connect('motion_notify_event', move_cursor) -
How to update multiple records of the same model in django at once?
Good day everyone. I have a model called Members, which includes students and courses and their associated data. One of which is the Exam_Score. For Entering the Exam_Score, first the user Should query the database using a form to get the right set of students and then enter the scores. I got the first part but I don't know how to solve the last part which is entering the students scores. This is the form: forms.py class CourseMemberForm(forms.Form): course = forms.CharField(max_length=50) department = forms.CharField(max_length=10) year = forms.IntegerField() semester = forms.IntegerField() This is the view: def ent_exmscr(request): form_fields = ['course', 'department', 'semester', 'year'] form = CourseMembersForm() if request.method == 'POST': form = CourseMembersForm(request.POST) if form.is_valid(): course = form.cleaned_data["course"] dep = form.cleaned_data["department"] smstr = form.cleaned_data["semester"] yr = form.cleaned_data["year"] crs = Course.objects.get(name=course) stdnts = Members.objects.filter(department=dep, semester=smstr, course=crs.id, year=yr) return render(request, 'office/exm_mrk.html', {'stdnts': stdnts}) else: return form return render(request, 'office/exmrk_form.html', {'form': form}) The above view queries the database based on parameters entered by the user and returns a list of students in a new template. So how can I enter the students' scores in the new template? Thanks in advance. This is the model: dep_choices=[ ('MIS','MIS'), ('BBA','BBA') ] course = models.ForeignKey(Course, null=True, on_delete=models.SET_NULL) student … -
How to get a Python/Django app web ready?
I have a python > django project ready to be launched to the web but I'm having trouble configuring it. What do I need to do to the files to get it ready to be launched? Does anyone have a link to a tutorial or such? -
What is the use of False in delete() function in django?
I'm working on code refactoring of django project which was like 4 years old and came across a syntax which confused me. They passed a boolean parameter False to django ORM like object.delete(False). I checked the docs for delete() function in django ORM. But couldn't find False parameter to it. And there is no method overriding in Django Model for delete() method. What is this False parameter for? -
How to get value of model method in Django Rest Framework?
So basically I have a django model that has a ManyToManyField of friends and two methods that run on it. Here are my files: Models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) friends = models.ManyToManyField(User, blank=True, related_name='friends') def friends_list(self): return self.friends.all() def number_of_friends(self): return self.friends.all().count() Serialzers.py: from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' Views.py: from rest_framework import viewsets, permissions from .models import Profile from .serializers import ProfileSerializer class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ProfileSerializer The issue is that in the Api, the return values of the method aren't there. The friends_list method for example is supposed to return a list of friends you have and even though this does work in a traditional django project, the Django Rest Framework is not showing any value for this method. How can I fix this and get the return values for both methods to show up in the api? -
Creating Custom Login Authentication in Django
I tried to follow the instruction on other StackOverflow question, but still does not work. I'm trying to create a custom login authentication using django for my school project. i want the user to login only using their username Here's my views : from django.shortcuts import render from django.contrib.auth import authenticate, login, logout # Create your views here. from myatm.newauth import MyBackend def user_login(request): if request.method == 'POST': token = request.POST.get('token') print(token) user = authenticate(username = token) if user: if user.is_active: login(request,user) else: print('gagal') else: print(user) # always print none return render(request, 'bank/login.html') here is my custom auth : from django.contrib.auth.backends import BaseBackend from django.contrib.auth.models import User class MyBackend(BaseBackend): def authenticate(self, username=None): try: return User.objects.get(username=username) except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None Note : I already add my custom auth on settings -
Order by a foreigh key related model field does not take effect
On viewset BargainOrdersAdminViewSet as you can see, I declared the filter_backends as (SearchFilter, OrderingFilter), and I alse declared ordering as -create_at as default and available ordering_fields ('create_at', 'order__gmt_payment'). When I ordered the queryset by create_at and -create_at, I got the expected ordered results. But, When I ordered the queryset by order__gmt_payment, it did not work as expected and I got the default -create_at ordered results instead. Below is the involved code. class BargainOrdersAdminViewSet(...): ... queryset = BargainOrders.objects.all() filter_backends = (SearchFilter, OrderingFilter) ordering = '-create_at' ordering_fields = ('create_at', 'order__gmt_payment') search_fields = ... class BargainOrders(models.Model): """砍价商品订单表""" order = models.ForeignKey(Orders, on_delete=models.CASCADE, null=True) # 订单 ... class Orders(models.Model, ModelWithUserPropertyMixin): ... gmt_payment = models.DateTimeField(null=True) I am calling API with this endpoint: /api/admin/bargain/orders?ordering=order__gmt_payment. It gives me the results ordered by default -create_at. I can not figure it out. Please help me out. -
Django Python email validations no shared email between multiple users
I am needed to know what code I need to put into my models.py (validations) so that when a user goes to register for a new account, that they get an error message if that email address is already in use by another user. -
Unable to save inlineformset Django
I'm new to Django. I created a custom layout form with an inline-formset. Sadly, I can't save this form in any way and don't get any error message. The only thing I understand with the debug toolbar, no data is being posted to the order field in the order detail (child) table, which is assigned as a foreign key from the ID field of the order table (parent). My models, forms, views, and templates are given below : model.py class PurchaseOrder(models.Model): purchase_id = models.CharField(max_length=50) order_date = models.DateField(default=now) voucher = models.CharField(max_length=25, blank=True, null=True) supplier = models.ForeignKey('Supplier', blank=True, null=True, on_delete=models.SET_NULL) order_amount_usd = models.DecimalField(max_digits=10, decimal_places=2, default=0) order_amount_bdt = models.DecimalField(max_digits=10, decimal_places=2, default=0) discount_type = models.CharField(max_length=1) discount_percent = models.DecimalField(max_digits=5, decimal_places=2, default=0) discount_amount = models.DecimalField(max_digits=5, decimal_places=2, default=0) freight_charge = models.DecimalField(max_digits=10, decimal_places=2, default=0) debit_account = models.ForeignKey('Account', blank=True, null=True, related_name='debit_account', on_delete=models.SET_NULL) total_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) paid_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) credit_account = models.ForeignKey('Account', blank=True, null=True, related_name='credit_account', on_delete=models.SET_NULL) tracking = models.CharField(max_length=30, blank=True, null=True) received = models.BooleanField(default=False) status = models.CharField(max_length=25) narrations = models.CharField(max_length=100, blank=True, null=True) received_at = models.DateTimeField(blank=True, null=True) elapsed_days = models.DurationField(default=timedelta()) journal_entry = models.BooleanField(default=False) created_at = models.DateTimeField(default=now, editable=False) created_by = models.ForeignKey(User, related_name="purchaseorders", blank=True, null=True, on_delete=models.SET_NULL) class Meta: default_related_name = 'PurchaseOrder_detail' def get_absolute_url(self): return reverse('purchase-order-update', kwargs={'pk': self.pk}) def __str__(self): … -
Django equivalent to node app.get("/*" call
I am trying to replicate this node js call in Django. I am not familiar with node, but wondering how to represent /* in Django or if there is existing middleware that does the same. app.get("/*", function(req, res) { } I would appreciate any example or a pointer that I can use to help port this function. -
Django channels testing with HttpCommunicator
I have a DRF application, which also has a single websocket consumer Now I'm trying to make a test case, which inherits from a Djano 3.1 TestCase. Said test case should register a user via rest_auth registration endpoint and than connect to the channels consumer To register a user in a test case I use HttpCommunicator like so: class TestRoomWebsockets(APITestCase): async def test_connect(self): communicator = HttpCommunicator( application, "POST", reverse(UrlUtils.Users.REGISTER), body=json.dumps({"username": ..., "password1": ..., "password2": ...}).encode("utf-8") ) response = await communicator.get_response() self.assertEqual(response["status"], 200) But it fails with status code 400. The response is {'status': 400, 'headers': [(b'Content-Type', b'application/json'), (b'Vary', b'Accept'), (b'Allow', b'POST, OPTIONS'), (b'X-Frame-Options', b'DENY'), (b'Content-Length', b'120'), (b'X-Content-Type-Options', b'nosniff'), (b'Referrer-Policy', b'same-origin')], 'body': b'{"username":["This field is required."],"password1":["This field is required."],"password2":["This field is required."]}'} I have no idea, why the data is lost somewhere. Could someone please explain, what am I doing wrong? Please tell, if more details are required to solve the issue. Some additional files asgi application looks like this: application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": TokenAuthMiddlewareStack( URLRouter([ path('ws/', my_router), ]) ) }) -
filter records based on a relationship | Django
I have the following models: class PodcastPlatform(models.Model): name = models.CharField(max_length = 60) badge_path = models.FilePathField(path = settings.BADGES_DIR, unique = True) class Meta: ordering = ['name'] def __str__(self): return self.name class Podcast(models.Model): name = models.CharField(max_length = 60) description = models.CharField(max_length = 400) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) class Meta: ordering = ['-created', '-updated'] def __str__(self): return self.name class PodcastLink(models.Model): podcast_platform = models.ForeignKey(PodcastPlatform, on_delete = models.CASCADE) podcast = models.ForeignKey(Podcast, on_delete = models.CASCADE) url = models.URLField(max_length = 400, verbose_name = 'URL') class Meta: ordering = ['podcast_platform__name'] unique_together = ['podcast_platform', 'podcast'] def __str__(self): return self.podcast_platform.name def get_badge_url(self): return static(re.search('img/.{0,}', self.podcast_platform.badge_path).group()) I want to filter the instances of the Podcast model where they have at least one link or a related instance of the PodcastLink model. To do it, I did the following: Podcast.objects.filter(podcastlink__gte = 1) Returning the following QuerySet: <QuerySet [<Podcast: Libero tenetur>, <Podcast: Libero tenetur>, <Podcast: Libero tenetur>, <Podcast: Assumenda iusto>, <Podcast: Assumenda iusto>, <Podcast: Assumenda iusto>, <Podcast: Assumenda iusto>, <Podcast: Explicabo>, <Podcast: Explicabo>, <Podcast: Explicabo>, <Podcast: Explicabo>, <Podcast: Explicabo>]> I get the expected result, but instead I notice that the instances are repeating... Try the following and in the same way I got the same result (repeated … -
Not able to maintain login in iframe for django
I am trying to maintain the login session in an iframe for a Django website. When the iframe is embedded in the same domain (example.com) the login session is maintained. But when the iframe is embedded in another domain (another.com) the login of example.com is not there, even though the src of the iframe is set to example.com. -
How to add a unique randomly generated 6 digit key stored in a model
I need each model in my database to have a unique six-digit key associated with it. For example, class Quiz(models.Model): name=models.CharField(max_length=250) randomly_generated_id=models.RandomField() #how do I generate a random key here? -
Django: Can't load JS file but all static files are rendered correctly
When I inspect I got a blank page but all static files are well loaded even CSS. My Settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
Postgres Syntax to DJANGO ORM Syntax
I have the following Postgres syntax, that does what I want it to do, however, I would like to implement it in the models.py tab in ORM. SELECT split_part(booking_inform, ',', 1) AS col1 , split_part(booking_inform, ',', 2) AS col2 , split_part(booking_inform, ',', 3) AS col3 , split_part(booking_inform, ',', 4) AS col4 , split_part(booking_inform, ',', 5) as col5 , split_part(booking_inform, ',', 6) as col6 FROM main_inmate; I am splitting the column "booking inform" into six new columns based on a commas. Thanks! -
Apple login in django rest framework with allauth and rest-auth
I have implemented Apple login in django with allauth and rest-auth. I implemented same way as Google login which worked perfectly. views.py class AppleLogin(SocialLoginView): adapter_class = AppleOAuth2Adapter urls.py urlpatterns = [ path("auth/apple/", AppleLogin.as_view(), name="apple-login"), ] pip versions Django==2.2.17 django-allauth==0.43.0 django-rest-auth==0.9.3 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 When I test as below I'm getting KeyError: 'id_token' and this is where error comes from: https://github.com/pennersr/django-allauth/blob/master/allauth/socialaccount/providers/apple/views.py#L92 I have no idea how to fix this error. Thank you for your help ! curl -X POST 'https://.../auth/apple/' \ -d 'access_token=AUTHENTICATION_CODE' or curl -X POST 'https://.../auth/apple/' \ -d 'id_token=ID_TOKEN' \ -d 'access_token=AUTHENTICATION_CODE' -
How to get rid of redundant elements in Django + Bootstrap4
I cannot find where to remove the unnecessary duplicate word that is above. new_entry.html: {% extends "learning_logs/base.html" %} {% load bootstrap4 %} {% block content %} <h5><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></h5> <form action="Topic: {% url 'learning_logs:new_entry' topic.id %}" method='post'> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-primary">Add</button> {% endbuttons %} </form> {% endblock content %} views.py: @login_required def new_entry(request, topic_id): """Добавляет новую запись по конкретной теме.""" topic = Topic.objects.get(id=topic_id) check_topic_owner(topic.owner, request.user) if request.method != 'POST': # Данные не отправлялись; создается пустая форма. form = EntryForm() else: # Отправлены данные POST; обработать данные. form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) # Вывести пустую или недействительную форму. context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) Perhaps I need to send something else? I don't know where the code itself is responsible for these parameters. For example, it would be interesting to find where to change the width of the form. -
Error during template rendering : NoReverseMatch at /products/product-3/
** Error ** NoReverseMatch at /products/product-3/ Reverse for 'add_to_cart' not found. 'add_to_cart' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/products/product-3/ Django Version: 3.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'add_to_cart' not found. 'add_to_cart' is not a valid view function or pattern name. ** products ** def single(request, slug): product = Product.objects.get(slug=slug) images = ProductImage.objects.filter(product=product) context = {'product': product, 'images': images} template = 'products/single.html' print(request) print(context) print(template) return render(request, template, context) ** urls.py in product app ** from . import views app_name = 'product_app' urlpatterns = [ path('', views.index, name='home'), path('s/', views.search), path('products/', views.all, name='products'), path('products/<slug:slug>/', views.single, name='single_product'), ] -
Are processes the same as concurrency in django-post_office?
I am using django-post_office to send c.10,000 emails in a single task each morning. It's possible to do this via the function send_queued(processes=1, log_level=None) in a celery task. I understand it's best practice to run celery with concurrency, e.g. celery -A settings worker -l info --concurrency 6 Is the processes flag in django-post_office the same as this? E.g. if I am running 6 concurrent celery processes should I have this flag also set as 6? If not, what's the difference between the two?