Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating and updating Model object using form
models.py class PostModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now_add=True) title = models.TextField(null=True) body = models.TextField(null=True) def __str__(self): return str(self.user) class ImagesPostModel(models.Model): post = models.ForeignKey(PostModel, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True) views.py def post(request): post = PostModel(user=request.user) post.save() if request.method == 'POST': form = PostModelForm(request.POST, instance=post) images = request.FILES.getlist('images') for image in images: ImagesPostModel.objects.create(post=post, images=image) if form.is_valid(): form.save() return redirect('/Blog/home/') else: form = PostModelForm(request.POST) return render(request, 'post.html', {'form': form}) I created a PostModel object post and save it in the database using save() method. I have provided the instance parameter as post object in the form, so the form should be updating the above created post but it is creating another PostModel object and inserting into the database by itself. So there are two post begin created and being inserted into the database, first one is because of post = PostModel(user=request.user) and I dont know why the second one is being created. why is this happening? -
How to parse to json multi select from postgres function in django
I have two select queryies that will return refcursors, they are in one function: open Ref1 for select * from TMP limit page_size offset (page - 1) * page_size; return next Ref1; ---- open Ref2 for select totalRecord as totalRecord , pageTotal as pageTotal; return next Ref2; In view django I use a cursor to execute above function like that: with connection.cursor() as cursor: cursor.execute('select * from fnc_get_news(1, 30)') row = cursor.fetchall() I dont know how to do next and I know I can try pyodbc to do it. I try to install Django 3.2, odbc-postgresql (latest) and when run server I got: File "/usr/local/lib/python3.8/dist-packages/django_pyodbc/base.py", line 98, in > < raise ImproperlyConfigured("Django %d.%d is not supported." % DjangoVersion[:2]) <django.core.exceptions.ImproperlyConfigured: Django 3.2 is not supported. I am standstill with this problem, please help me. -
Cookies not being sent with Axios
I have a form built on Nuxt/vuejs. On the backend side on django the CSRF protection is enabled which now expects two things in the Api call X-CSRFToken as a header and csrftoken as a Cookie , I tested the Api by calling the Api through Postman which works fine but in case Of Vue it is not sending the Cookies with post request let me show you my code Axios post request const headers = { "X-CSRFToken": "some token", "Cookie": "csrftoken=some token", } await axios.post(`onboarding/first-name-last-name-email/`, { "first_name": "uneeb2", "last_name": "sad", "email": "asdsa@asd.colm" }, { headers: headers }, { withCredentials: true }) one important thing to mention here CORS is enabled by server, so I am not doing anything specific for that. I also tried setting the cookie as natively by document.cookie = "csrftoken=some token; Path=/; Expires=Mon, 16 Feb 2023 08:02:50 GMT;"; through this I can see the Cookie being set on browser but this still not sends the cookie with post request As you can see I've also tried withCredentials: true which was one of the common proposed solutions by in my case this did not work as well. About the Server config , the Django server is a … -
Use filename insted of 'Download'
On my Django page I have a paragraph to download attached files: {% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Attachment {{ forloop.counter }}: </strong><a href="{{i.file.url}}" >Download</a></p>{% endfor %} How can I show File name insted of word 'Download'. Users don't know which file is which when downloading, in case of many files. Also, if extension is possible. So, insted of: Attachment: Download I would like to have: Attachment: image.png -
Getting "'type' object does not support item assignment" in django
I am using django referrer policy middleware and it is giving me intermittent error of type assignment. Below is the error trail. File "/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/env/lib/python3.6/site-packages/django_referrer_policy/middleware.py" in __call__ 36. response['Referrer-Policy'] = settings.REFERRER_POLICY Exception Type: TypeError at / Exception Value: 'type' object does not support item assignment Django : 2.0.3 Python : 3.6 Thanks in advance. -
Django: How to group a QuerySet by two ForeignKeys then apply Sum
I have the following simplified models: class Workout(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="workouts") # ... class Exercise(models.Model): # ... class WorkoutSet(models.Model): dt = models.DateTimeField(default=timezone.now) workout = models.ForeignKey( Workout, on_delete=models.CASCADE, related_name="sets") exercise = models.ForeignKey( Exercise, on_delete=models.PROTECT, related_name="sets") repetitions = models.PositiveSmallIntegerField() weight = models.DecimalField(max_digits=6, decimal_places=2) # ... Assume I have the following data in the WorkoutSet table: Workout ID Exercise ID Repetitions Weight DateTime 1 1 10 15 02/02/2022 1 1 10 15 02/02/2022 1 1 10 15 02/02/2022 1 2 8 30 02/02/2022 1 2 8 35 02/02/2022 1 2 8 35 02/02/2022 2 1 10 20 15/02/2022 2 1 10 20 15/02/2022 2 1 10 20 15/02/2022 And assuming today is the 16th of February, 2022. Ultimately, I want, for each exercise (if it happens to be their best performance), to say: "This week, you achieved your best for exercise 1 with a total load of 600 (20X10+20X10+20X10), which is 150 higher (15X10+15X10+15X10) than your previous personal record (PR)". This is how I'm thinking of tackling this: Get this week's WorkoutSet objects related to the user Group the results by Workout ID and Exercise ID, and annotate with the sum of the multiplication of Repetition and Weight Get the … -
Using prefetch_related_objects on nonhomogenous objects with a shared relationship
ModelA has a Many-to-One relationship to ModelC ModelB has a Many-to-One relationship to ModelC I have a situation where I need to access the related objects through both like model_a_instance.model_c and model_b_instance.model_c and I don't want to fire off N additional queries. I found that using prefetch_related_objects(list_of_model_a_instances + list_of_model_b_instances, 'model_c') works as expected. However, peaking into prefetch_related_objects code I noted this. # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. first_obj = obj_list[0] Are there any side effects I should be worried about here? I did notice that the related instances are identical. list_of_model_a_instances[0].model_c is list_of_model_b_instances[0].model_c Out[1]: True So, downstream code will need to not unexpectedly modify the related objects to prevent undefined behavior. Anything else I should be worried about here? -
Javascript (Ajax ) function of combined events in Django application
I 'm building a restaurant eCommerce api using Django framework. Now I 'm working on cart application part. The restaurant offers several products (categories) incl. pizza, burger... For pizza, the product variants contains size (small, medium and large) as well as base (thin, standard). For burgers, it contains different sauces as its variants. Different combinations give different prices. For example, the price of pizza with salami (product id =1), small size (size id=1) and standard base (base id=2) is 12 euro. The corresponding productAttribute id (salami+small+standard) is 3. The purchasing workflow would be, after customer choosing a product (pizza salami) and selecting size and base, the price would be automatically updated. I 'm wondering how should I implement this logic. Any comments? Thanks! -
is it ok to call REST API inside normal Django app
So I am creating an app which has mobile version as well as web version but most of the users will be on mobile and very less on web,I am done with rest API now I have to create a client site but I dont want to use react or any other framework. So do you think is it possible to create a normal django project and call API under each view signup, login and then return the response through render to web page? -
custom group with foreignkey didn't work on permission control
I need to add some fields to my group model, so I make my own custom model that linked to original group with ForeignKey. when I tried the custom group with permission control it didn't work. custom group model : class Roles(models.Model): id = models.CharField(max_length=255, blank=True, primary_key=True) name = models.CharField(max_length=255, blank=True) label = models.CharField(max_length=255, blank=True) desc = models.TextField(blank=True, null=True) group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) custom user model : class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True) label = models.CharField(max_length=255, blank=True) roles_id = models.ForeignKey(Roles, on_delete=models.CASCADE, blank=True, null=True) desc = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is there anything wrong with my model? -
Possible to get queryset from list of queryset -Django
I wanted to take queryset from multiple models. I am trying to achieve multiple search with and condition. views.py, def list(self, request, *args, **kwargs): search_query = self.request.query_params.get('search') split_query = search_query.split() employment = None employee1 = [] employment1 = [] for query in split_query: print("hi", query) # query = self.request.query_params.get('search') employee = PositionFulfillment.objects.filter( Q(employment__employee__code__icontains=query) | Q(employment__employee__person__name__icontains=query) | Q(employment__employee__person__surname__icontains=query) ) # emp = list(chain(employee)) employee1.append(employee) print("employee", employee1) active_employee = PositionFulfillment.objects.filter(primary_flag=True, thru_date=None) if active_employee: employment = active_employee.filter( Q(position__position_type__name__icontains=query) | Q(employment__organization__name__icontains=query) | Q(employment__status__status__employment_status__icontains=query) ) employment1.append(employment) all_results = list(chain(map(lambda x: x, employee1), map(lambda y: y, employment1))) # all_results = list(chain(employee, employment)) print("all_results", all_results) serializer = EmployeeSearchSerializer(all_results) return Response(serializer.data, status=status.HTTP_200_OK) I have got output like below, all_results, [<QuerySet [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]>, <QuerySet []>, <QuerySet []>, <QuerySet [<PositionFulfillment: 28>]>] Expected output, [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]> ,<QuerySet [<PositionFulfillment: 28>]>] How can i achieve this??? -
How can I get the donation amount field against each employee in Django from frontend?
I am working on a donation app. In this app, I am changing a feature that every employee of the organization gets an equal amount of donation to a customized amount of donation. I will be receiving different donation amounts for each employee from the frontend. I don't exactly know how to do that. Here is my code: class BusinessDonation(): def create(self, request, response, business): employees= Employment.objects.filter(business=business, active=True) try: amounts = int(request.payload.get("amounts")) total = int(request.payload.get("total")) except ValueError: return response.bad_request("Invalid donation amounts, %s, should be in whole dollars" % amounts) error = run_employee_donation(business.id, to_cents(amounts)) if error != '' and error is not None: return response.bad_request(error) response.set(**{'success': True} -
Django application not running inside docker
[ex][1] Django response from browser -
Django: aggregate if all boolean model fields is True
from django.db import models class Car(models.model): sold = models.BooleanField(default=False) I can detemine if all cars were sold by making two queries: sold_count = Car.objects.filter(sold=True).count() all_count = Car.objects.count() are_all_sold = (all_count - sold_count) == 0 Since this operation is very frequent on my app, I am wondering if it is possible to do it in just one DB query? e.g. using Aggregation or Query Expressions, etc. -
What is error for when install psycopg2==2.7.*?
pip3 install psycop2==2.7.* I try to install Django project on a live server but when I install the package I am getting error! pip install psycopg2==2.7.* -
Django How to check a request is Ajax
The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header. -
Parameter "form" should contain a valid Django Form. error happen
now I use Django and try to make some Board included upload file function actually, I do not have any experience in making a web HTML code so just try to use Django for making a web Board and I success just make a board but wanna which have a file upload function so I mix my code and other code and I think almost success but did not work it and got an error like a title I guess almost clear but a few problems just remain like below [about Bootstrap] so need help. 1 is my git address 2 is refer code address <div class="form-group"> <label for="content">command</label> <textarea class="form-control" name="content" id="content" rows="10">{{ form.content.value|default_if_none:'' }}</textarea> <button type="submit" class="btn btn-primary">save</button> </div> <!-- add code --> <div class="container"> <form method="POST" action="{% url 'pybo:fileUpload' %}" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form fileuploadForm %} <input type="submit" class="btn btn-primary col-12" value="submit"> </form> </div> -
Accessing values stored in a Field and comparing it with other parameter in serializer
This is what i have in Django Author model as a primary key id = models.URLField(primary_key=True) One example can be {id:"http://localhost:3000/authors/1d698d25ff008f7538453c120f581471"}. In My serializer, i want to compare 1d698d25ff008f7538453c120f581471 portion of the path to an author_id i passed in. Right now, I am using, from urllib.parse import urlparse ... def create(self, validated_data, author_id): author, created = Author.objects.update_or_create( urlparse(id).path.split('/')[2]=author_id, defaults=validated_data) return author Is there an alternative of doing this? -
Django Oscar - Multi Vendor Setup where partners can only manage their own products
I am using django-oscar to set up a multi vendor marketplace I have linked a user as a partner and given them "limited access dashboard" But they still have management access to all products on the site. (Menu item: Catalogue\Products) I only want my vendors to add/edit/sell/delete their own products only! What do I need to do? -
Making Login Api with custom django user model with my defined username and emp_password fields
Custom User model authentication not work for me i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password. I try to map my username and password with employee table emp_password field.I try this last 2 days so still stuck in this issue. Please help me thank you in advance. Let share with you code models.py Hello everyone, Custom User model authentication not work for me i need to override default password field with my define emp_password field because in database i have already created users with their passwords field name as emp_password. I try to map my username and password with employee table emp_password field and then if everything work then make login api for employee login Let share with you code models.py from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.hashers import make_password class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, emp_email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not emp_email: raise ValueError('The Email … -
django settings does not affect after changes(CELERY_BROKER_URL)
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['json'] TASK_SERIALIZER = 'json' [2022-02-14 12:02:26,910: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@192.168.3.100%3A6379:5672//: failed to resolve broker hostname. Trying again in 2.00 seconds... (1/100) -
Need to fetch two specific field values from one model to another seperately in django API rest framework
model 1 class Users(models.Model): employee_name = models.CharField(max_length=50) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) desingnation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="desingnation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) def __str__(self): return self.employee_name model 2 class Consolidated(models.Model): emp_name=models.ForeignKey(Users,on_delete=CASCADE) proj_name=models.ForeignKey(Project,on_delete=CASCADE) custom_name=models.ForeignKey(Client,on_delete=CASCADE) Cons_date=models.ForeignKey(Add_Timelog,on_delete=CASCADE) bill_no_bill=models.ForeignKey(Users,on_delete=CASCADE,related_name="billable_and_non_billable+") def __str__(self): return str(self.emp_name) Serializers class UserSerializers(serializers.ModelSerializer): class Meta: model= Users fields = '__all__' class Consolidated_serializers(serializers.ModelSerializer): class Meta: model=Consolidated fields= '__all__' Viewsets class UserViewset(viewsets.ModelViewSet): permission_classes=(permissions.IsAdminUser,) queryset=models.Users.objects.all() serializer_class=serializers.UserSerializers class Consolidated_ViewSet(viewsets.ModelViewSet): permission_classes=(permissions.IsAdminUser,) queryset=models.Consolidated.objects.all() serializer_class=serializers.Consolidated_serializers Actually I was stucked in the middle, as I need to take the values from 'billable_and_non_billable' field from the Users model and display those values under Consolidated model bill_no_bill field. With the above code I can only take the employee_name values from the Users model to the emp_name of Consolidated model and the same value is getting displayed in the bill_no_bill field. Please help me find any ways for this problem as I am new to this Django. Basically its needs to be a API which operates GET method. -
Django Rest Framework Multiple Model Serializtion
I am using Django Rest Framework to make and API. I have and endpoint that i want to use to generate a JSON object that contains data from different models. The viewset for the model is: class InvoiceView(viewsets.ModelViewSet): def list(self, request): cart_id = request.data["cart_id"] shop = Shop.objects.get(id=request.user.id) cart = ShoppingSession.objects.get(id=cart_id) cart_items = CartItem.objects.filter(session=cart_id) paymentmethod = PaymentMethod.objects.get(id=cart.payment_method.id) Invoice = namedtuple('Receipt',('shopname','cart', 'cartitems', 'paymentmethod')) invoice = Invoice( shopname = shop, cart = cart, cartitems = cart_items, paymentmethod = paymentmethod ) serializer = ReceiptSerializer(Invoice) return Response(serializer.data,) The serializers used are: class ShopSerializer(serializers.ModelSerializer): class Meta: model = Shop exclude = ['is_staff', 'is_active', 'start_date'] class ReceiptSerializer(serializers.Serializer): shopname = ShopSerializer() cart = ShoppingSessionSerializer() cartitems = CartItemSerializer(many=True) paymentmethod = PaymentMethodSerializer() When the url is run and a GET request is executed. An error is generated that looks like this. AttributeError: Got AttributeError when attempting to get a value for field `first_name` on serializer `ShopSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `_tuplegetter` instance. Original exception text was: '_collections._tuplegetter' object has no attribute 'first_name'. How are you supposed to user multiple serializers in one serializer class for this kind of custom use-case? -
Django url path matching not working as expected
I have problem with Django model get_absolute_url reverse methods. I have a url pattern that works perfectly but the problem for example when I visit example.com/blog/python/first-post the path works perfectly, but when I try a random path like, example.com/blog/python-randomr9353/first-post it still works correctly even though it shouldn't because, python-randomr9353 is not a valid path and it should return a page not found error. Here is my code. Models class ArticleSeries(models.Model): title = models.CharField(max_length=200) series_slug = AutoSlugField(populate_from='title') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:article_list', kwargs={'series_slug': self.series_slug}) class Tag(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=200) article_slug = AutoSlugField(populate_from='title') tag = models.ManyToManyField(Tag, default=1, verbose_name='Tag') series = models.ForeignKey(ArticleSeries, default=1, verbose_name='Series', on_delete=models.SET_DEFAULT) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:article_detail', args=(self.series.series_slug, self.article_slug)) url patterns app_name = 'blog' urlpatterns = [ path('', views.IndexView.as_view(), name='index_view'), path('blog', views.BlogView.as_view(), name='blog_view'), path('blog/<slug:series_slug>', views.ArticleListView.as_view(), name='article_list'), path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail'), ] Views class IndexView(TemplateView): template_name = 'blog/index.html' extra_context = {} class BlogView(ListView): model = ArticleSeries template_name = 'blog/blog_view.html' context_object_name = 'series_list' def get_queryset(self): series = ArticleSeries.objects.all() return get_list_or_404(series) class ArticleListView(ListView): model = Article template_name = 'blog/article_list.html' context_object_name = 'article_list' def get_queryset(self): slug = self.kwargs['series_slug'] articles = Article.objects.filter(series__series_slug=slug) return get_list_or_404(articles) class ArticleDetailView(DetailView): model = Article template_name = … -
ordering = ['-created'] what it means in Django? why we use - sign in ordering?
Below is my code. class Basecalss(models.Model): title = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: abstract = True ordering = ['-created'] Here why we use - sing before created, what it means??