Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding to manytomany field returns empty queryset
I am trying to add items in the many-to-many field. After adding it, I am getting an empty queryset. It taking me crazy. if request.user.is_authenticated: order = Order.objects.create(restaurant=Restaurant.objects.get(code_name=restaurant_code), table=Table.objects.get(code_name=request.data['table']), customer=request.user ) else: order = Order.objects.create(restaurant=Restaurant.objects.get(code_name=restaurant_code), table=Table.objects.get(code_name=request.data['table']) ) for menuitem in request.data['menuItems']: customList = [ItemType.objects.get(id=v) for v in list(menuitem['addOns'])] orderedMenuItem = OrderedMenuItem.objects.create(quantity=menuitem['quantity'], menuitem=MenuItem.objects.get(pk=menuitem['id']), remarks=menuitem['remarks']) orderedMenuItem.custom_item_types.add(*customList) order.ordered_menu_items.add(orderedMenuItem) order.save() Here I have ItemType as manytomany field got orderedMenuItem model. When trying to add ItemType object into OrderedMenuItem model, its giving empty query set. -
MyModelAdmin must have search_fields for the autocomplete_view
I have 404 in Admin suggest with error ApartmentPromotionAdmin must have search_fields for the autocomplete_view. My admin organized as follows from string import Template from dal import autocomplete from django import forms from django.contrib import admin from django.contrib.admin.widgets import AutocompleteSelect from django.forms import widgets class PromotionApartmentForm(forms.ModelForm): class Meta: fields = "__all__" widgets = { "apartment": AutocompleteSelect( ApartmentPromotion._meta.get_field("apartment").remote_field, admin.site, attrs={"style": "width: 400px"}, # You can put any width you want. ), } class ApartmentPromotionAdmin(admin.ModelAdmin): form = PromotionApartmentForm list_display = ("id", "apartment") autocomplete_fields = ["apartment"] I have admin.site.register(ApartmentPromotion, ApartmentPromotionAdmin) and models are class ApartmentPromotion(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE, related_name="promotions") ... def __str__(self): return f"<{self.id}> {self.apartment} {self.status}" class Meta: indexes = [ models.Index(fields=["id"]), models.Index(fields=["apartment_id"]), ] class Apartment(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="owned_apartments") .... class Meta: indexes = [ models.Index(fields=["owner_id"]), ] could you help me to fix the problem ? -
Update Task APIView' object has no attribute 'action'
I m totally new in django and rest. I wanna write a program that only lets the owner update or delete his tasks. When I try to use it, it doesn't prohibit me to update or delete (others tasks) and when I press the update or delete button it returns me this error "Update Task APIView' object has no attribute 'action'" Thanks for helping models.py class Task(models.Model): title=models.CharField(max_length=250) text=models.TextField() user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) status=models.ForeignKey('Status',on_delete=models.SET_NULL,null=True) startDate=models.DateTimeField(auto_now_add=True) endDate=models.DateField(null=True) def __str__(self): return self.title class Status(models.Model): name=models.CharField(max_length=250) def __str__(self): return self.name Permissions.py: from rest_framework import permissions class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view,obj): if (obj.user == request.user) | (view.action == 'retrieve'): return True else: return False Serializers.py: from rest_framework import serializers from .models import Task,Status class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task # fields = ['title', 'text', 'status', 'endDate'] fields = '__all__' class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__' Views.py class TaskViewSet(ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Task.objects.all() serializer_class = TaskSerializer permission_classes = [permissions.IsAuthenticated, IsOwner,] def perform_create(self, serializer): serializer.save(user=self.request.user) class ListTaskAPIView(generics.ListAPIView): serializer_class = TaskSerializer permission_classes = [IsAuthenticatedOrReadOnly] model= Task def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against … -
Do you need to know how to design a database before you can create a good django model?
Do django developers draw a database architecture before they code it in the models.py? If yes , does it mean you have to be good in database design before you can create a good database-driven website? If yes where do I get to learn database design? -
django many-to-many-field in list display for item like count
I want to display total likes against each item in Django admin list_display. The many to many field is linked with the user model. Below is my code Model: class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=False, blank=False,upload_to='images/') upload = models.FileField(upload_to ='uploads/') date = models.DateTimeField(auto_now_add=True) item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT) item_tool = models.ForeignKey(Tools, default='XD', on_delete=SET_DEFAULT) slug = models.SlugField(unique=True, blank=True, null=True) # new author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='post_likes') def total_likes(self): return self.likes.count() Admin.py from django.contrib import admin from .models import Categories, Item, Tools class ItemAdmin(admin.ModelAdmin): list_display = ('title','author','item_category','date') list_filter = ('item_category',) admin.site.register(Categories) admin.site.register(Item, ItemAdmin) admin.site.register(Tools) -
Can't login in Django project after switching to django 3 and return to django 2
I have a Django 2.2 project that runs in a bunch of different servers, but they use the same database. I've created a branch to migrate to Django 3, but not all servers will be migrated at the same time. I use Argon2: # https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] When I switched to django 3.2 in my developing branch everything worked fine. But then, when I returned to Django 2.2, I started getting errors like: Template syntax error Incorrect padding (exception location: .../python3.6/base64.py in b64decode) Those problems where solved by just deleting the cookies and reloading. So I guessed that they were related to the change in django 3.1 to a new default hashing algorithm from sha1 to sha256. Anyway, after reloading, the page worked. But when I tried to login it didn't recognize the credentials. Then I restored the database from backup and could login in django 2.2. I tried again to run on django 3.2 with the setting: DEFAULT_HASHING_ALGORITHM = 'sha1' Now, when switching back to 2.2, I didn't get errors on page load (I didn't need to delete cookies) but the credentials still didn't work. For me it looks like after switching … -
Django model how to do many to one mapping?
I am trying to map multiple field to same field in vendor and menu class. If I map using foreign key like below it works. But this is not what I want. class OrderItem_Mon(models.Model): vendor_name = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) menu_name = models.ForeignKey(Menu, on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField('date created', auto_now_add=True) note = models.CharField('note', max_length=255, null=True, blank=True) I need to map multiple field to same field of specific table like this. class OrderItem_Mon(models.Model): vendor_name_1 = models.ForeignKey(Vendor, db_column='vendor_name', on_delete=models.SET_NULL, null=True) menu_name_1 = models.ForeignKey(Menu, db_column='menu_name',on_delete=models.SET_NULL, null=True) vendor_name_2 = models.ForeignKey(Vendor, db_column='vendor_name',on_delete=models.SET_NULL, null=True) menu_name_2 = models.ForeignKey(Menu, db_column='menu_name', on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField('date created', auto_now_add=True) note = models.CharField('note', max_length=255, null=True, blank=True) However, it does not work. How do I make this work? Basically, I need to make new form that have dropbox that gets value from vendor and menu model to each field. Help -
Django: I want to create a self-generated code based on previous records and a sequential number
I'm a coding noob and I'm writing a website in Django for Project and task management, and I want to generate a project code field in a 'Project' model automatically based on previous records. I was thinking to make the 'project code' a CharField which must have 3 parts: 'department code', a foreign key of a 'Department' model with its own 'name' and 'code' fields, from which I only need the 2-3 letter code value, a 'year' code based on project start date using the last 2 digits of the date's year, and a sequence code which should be the last record based on the above filters +1. The project code field should look like this: DDD-YY-SS, where DDD is department code, YY is 2-digit year number and SS the sequence number. I'm trying to include the code generator in a custom save method like this: def save(self, *args, **kwargs): dpt = str(self.department.code) project_date = self.projectdate yy = str(project_date.year)[-2:] filter_kw = '{}-{}-'.format(dpt, yy) lastrec = ProjectModel.objects.filter(project_code__startswith = filter_kw).last() if lastrec == None: lastrec = '00' else: lastrec = str(lastrec.project_code)[-2:] newnum = "{:02d}".format(int(lastrec)+1) self.code = '{}-{}'.format(filter_kw, str(newnum)) super(ProjectModel, self).save(*args, **kwargs) But I think this code is... sketchy? I feel like using … -
Django race condition aggregate(Max) in F() expression
Imagine the following model: class Item(models.Model): # natural PK increment = models.PositiveIntegerField(_('Increment'), null=True, blank=True, default=None) # other fields When an item is created, I want the increment fields to automatically acquire the maximum value is has across the whole table, +1. For example: |_item____________________________| |_id_|_increment__________________| | 1 | 1 | | 2 | 2 | | 4 | 3 | -> id 3 was deleted at some stage.. | 5 | 4 | | 6 | 5 | .. etc When a new Item() comes in and is saved(), how in one pass, and in way that will avoid race conditions, make sure it will have increment 6 and not 7 in case another process does exactly the same thing, at the same time? I have tried: with transaction.atomic(): i = Item() highest_increment = Item.objects.all().aggregate(Max('increment')) i.increment = highest_increment['increment__max'] i.save() I would like to be able to create it in a way similar to the following, but that obviously does not work (have checked places like https://docs.djangoproject.com/en/3.2/ref/models/expressions/#avoiding-race-conditions-using-f): from django.db.models import Max, F i = Item( increment=F(Max(increment)) ) Many thanks -
Page not found (404) Request Method: GET trying to click to another .html file
I've done so much research I must have clearly missed something done or something wrong. The server I'm running is localhost:8000 I've added the homepage everything works fine until I try to click on another html file and received Page not found (404) Request Method: GET trying to Using the URLconf defined in user.urls, Django tried these URL patterns, in this order: admin/ secret/ home/ [name='home'] home/ [name='contact'] home/ [name='Project'] ^static/(?P<path>.*)$ index/Project.html. Here's the root urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from django.views.generic import RedirectView from portfolio_django import views admin.autodiscover() urlpatterns = [ path('admin/', include('admin_honeypot.urls', namespace='admin_honeypot')), url('secret/', admin.site.urls), path('home/', include("portfolio_django.urls")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) from django.urls import path from portfolio_django import views urlpatterns = [ path('', views.home, name='home'), path('', views.contact, name='contact'), path('', views.Project, name='Project') views.py from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html') def Portfolio(request): return render(request, 'Project.html') def contact(request): return render(request, 'contact.html') -
How to perform multiple count analytics using django?
I have an analytics dashboard - basically it shows the overview of the data's. Lets say that we have a table named "Records" In my analytics dashboard, i need to show various details about the records of particular user: user = Records.objects.filter(id=pk) By this we get all the records associate with the user, now to show various analytics like as follows, Total Records, Total Records by Today Total Records by Week Total Records by Month Total Active Records // Records which has status == active Total InActive Records // Records which has status == inactive How to do all these ? While researching i found few options to follow, Option 1 : Do separate query for each of the need Option 2 : Do fetch all the data's and perform the above calculations in view and send as context How to deal with these ? Am also planning to use charts -
generate a qr code and when scanned display url data in django
here when an item is added when need to automatically generate the qrcode and when scan with our mobile camera it need to show the url data Python version = 2.7 Django version = 1.8 qrcode version = 6.0 lets us consider my models.py as def qr_code_file_name(instance, filename): return '%s/qr_codes/%s/' % (instance.client_id, filename) class StockItems(models.Model): item_name = models.CharField(max_length=512) qr_code = models.ImageField(upload_to=qr_code_file_name, blank=True, null=True) def __unicode__(self): return self.item_name def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.item_name) canvas = Image.new('RGB',(90,90),'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = File('qrcode-code1.png') buffer = BytesIO() canvas.save(buffer,'PNG') self.qr_code.save(fname,File(buffer),save=False) canvas.close() When i am trying the save the new item created and the automatically saving the qr_code i am getting an error Here is my traceback of error Traceback (most recent call last): File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/andrew/devel/projectscan/mcam/server/mcam/core/views.py", line 516, in dispatch return super(CustomAuthMixin, self).dispatch(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/braces/views/_access.py", line 102, in dispatch request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 249, in post return super(BaseCreateView, self).post(request, *args, **kwargs) File "/home/andrew/.virtualenvs/projectscan/local/lib/python2.7/site-packages/django/views/generic/edit.py", line 215, in post … -
Is it important to create virtual environment for new project in django-admin?
Is it important to create virtual environment for new project in django-admin -
Django (HTML) - Clickable label in template (not working)
I'm working on a Django project where I would like using some customized checkbox forms when this issue shown up. Both code chunks are exactly the same, but using different forms. The issue comes when the first's sample label is clickable (so I can hide the radio button), but the second one is not working as expected, the user must click on the radio button, if I hide it the whole label becomes useless. NOT WORKING PROPERLY: <form action="" class="form-group" method="POST"> <div class="modal-body"> <div class="row"> <div class="col"> <ul> {% csrf_token %} <fieldset > {% for radio in form_pizzas.producto %} <li style="list-style-type:none"> <span class="radio">{{ radio.tag }} <label class="label" for="{{ radio.id_for_label }}"> {{ radio.choice_label }} </label> </span> </li> {% endfor %} </fieldset> </ul> </div> <div class="col"> {{form_pizzas.cantidad.label}} {{form_pizzas.cantidad}} {{form_pizzas.observaciones.label}} {{form_pizzas.observaciones}} </div> </div> </div> <div class="modal-footer"> <button class="btn btn-light" type="button" data-bs-dismiss="modal">Volver</button> <input type="submit" class="btn btn-primary" value="Agregar" /> </div> WORKING PROPERLY: <form action="" class="form-group" method="POST"> <div class="modal-body"> <div class="row"> <div class="col"> <ul> {% csrf_token %} <fieldset > {% for radio in form_emp.producto %} <li style="list-style-type:none"> <span class="radio">{{ radio.tag }} <label class="label" for="{{ radio.id_for_label }}"> {{ radio.choice_label }} </label> </span> </li> {% endfor %} </fieldset> </ul> </div> <div class="col"> {{form_emp.cantidad.label}} {{form_emp.cantidad}} {{form_emp.observaciones.label}} {{form_emp.observaciones}} </div> </div> … -
I am trying to sorting data in django the data is coming from different table in different dropdown but I am stuck I am not getting perfect match
**basically I am making a search engine for car's selling company in this search engine data is coming from different models but I am not getting the accurate data using these filter how can I get the perfect match I need help to solve this problem I will be very thankfull to you ** home.html <form action="/searchdd" method="POST" id="indexForm" data-cars-url="{% url 'ajax_load_cars' %}"> {% csrf_token %} <div class="col-md-12"> <div class="row"> <div class=" col-md-3"> <label for="" class="white">Make</label> <select id="companyddl" name="companyname" class="searchengine"> <option disabled selected="true" value="">--Select Make--</option> {% for company in companies %} <option value="{{company.CompanyID}}">{{company.CompanyName}}</option> {% endfor %} </select> </div> <div class=" col-md-3"> <label for="" class="white">Model</label> <select id="carddl" name="carname" class="searchengine"> <option disabled selected="true" value="">--Select Model--</option> </select> </div> <div class="col-md-3"> <label for="" class="white">From Year</label> <select name="fromdate" id="fromdate"> <option disabled selected="true" value="">--select Year--</option> {% for manf in manufac %} <option value="{{manf.ManufacturingYMID}}">{{manf.ManufacturingDate}}</option> {% endfor %} </select> </div> <div class="col-md-3"> <label for="" class="white">To Year</label> <select name="todate" id="todate"> <option disabled selected="true" value="">--select Year--</option> {% for manf in manufac %} <option value="{{manf.ManufacturingYMID}}">{{manf.ManufacturingDate}}</option> {% endfor %} </select> </div> </div> </div> <div class="col-md-12"> <div class="row"> <div class="dropdown my-2 col-md-3 col-sm-12"> <label for="" class="white">Type </label> <select name="type" id="type" class="searchengine" style="padding-right: 7px; margin-left: 3px;"> <option disabled selected="true" value="">--Select Type--</option> {% for ty … -
How can i do this via aggregation in django
I have a method in the model that saves the final price in the cart, it looks like this: class Cart(models.Model): """Cart""" owner = models.OneToOneField('Customer', on_delete=models.CASCADE) meals = models.ManyToManyField(CartMeal, related_name='related_cart', blank=True) total_products = models.PositiveIntegerField(default=0) final_price = models.DecimalField(max_digits=9, decimal_places=2, default=0) in_orders = models.BooleanField(default=False) for_anonymous_user = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.id: self.total_products = self.meals.count() self.final_price = sum([cmeals.final_price for cmeals in self.meals.all()]) super().save(*args, **kwargs) I was told that I can make this line self.final_price = sum([cmeals.final_price for cmeals in self.meals.all()]) with a single query using aggregate. How can I do this and where? In the model or do I need to do this in the view? Thanks. -
Django Unable to test API patch method with query parameters other than pk MultiValueDictKeyError
I have an APIView implementing patch for an entity (lets say money). I can send a request from axios and the money gets updated but I cannot make the test to work. The request.query_params are empty when I send them via self.client.patch inside the test case. Then it throuws MultiValueDictKeyError('money_code') Here is the code: class UpdateMoneyQuantity(APIView): def patch(self, request): try: money_code = request.query_params["money_code"] money_object = Money.objects.get(money_code=money_code) # set partial=True to update a data partially serializer = MoneySerializer( money_object, data=request.data, partial=True ) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=HTTP_200_OK) return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST) except Money.DoesNotExist as err: return Response( data={ "error": "Unable to find the desired code." }, status=HTTP_400_BAD_REQUEST, ) except Exception as err: logger.exception( f"Unable to perform patch on money quantity. \n Exception: {str(err)}" ) return Response(data=str(err), status=HTTP_500_INTERNAL_SERVER_ERROR) Here is the url: path( "update-money-quantity/", UpdateMoneyQuantity.as_view(), name="update-money-quantity", ), Here is the test case I am trying to write but couldn't make it work. class MoneyUpdateTest(APITestCase): def test_update_quantity(self): """ Ensure we can update the quantity. """ obj = Money.objects.create( money_code="RG100TEST1", supplier="Test supplier", ) params = {"money_code": "RG100TEST1"} url = reverse("update-money-quantity") data = { "saving": 110, "actual_saving": 105, } response = self.client.patch(url, data=data, query_params=params) self.assertEqual(response.status_code, HTTP_200_OK) self.assertEqual( Money.objects.get(money_code="RG100TEST1").saving, 110 ) self.assertEqual( Money.objects.get(money_code="RG100TEST1").actual_saving, 105 ) -
HTML files are not recognised in Django project
I am learning Django, everything was working fine but there was no syntax highlighting for django commands like {% block body_block %} {% endblock %} and so on... So, i installed a vscode extensions Django by Baptiste Darthenay and Django by Roberth Solis, now syntax highlighting is working but HTML files are not recognised Link. There is no code completion, everything has to be typed word by word. Disabling these extensions is working well, but then there is not syntax highlightling. Please Help!! -
Cannot query "": Must be "User" instance in Django 3.2
I get this error from below view: from django.shortcuts import render, redirect from movies import models as movies_models from django.contrib.auth import get_user_model User = get_user_model() def playlists_view(request): if (not request.user.is_authenticated) or (not request.user.is_staff): return redirect('Login') playlists = movies_models.PlayList.objects.filter(created_by=request.user).order_by('-id') return render(request, 'cpanel/playlists.html', {'playlists': playlists}) My playlist model is this: from django.db import models class PlayList(models.Model): type = models.PositiveSmallIntegerField(choices=type_choice, default=1, verbose_name='نوع فیلم') category = models.ManyToManyField(Category, related_name='Playlists', verbose_name='دسته بندی و ژانر') name_en = models.CharField(max_length=55, unique=True, verbose_name='نام انگلیسی') name_fa = models.CharField(max_length=55, unique=True, verbose_name='نام فارسی') summary = models.TextField(max_length=1024, verbose_name='خلاصه فیلم') imdb_score = models.FloatField(default=0, verbose_name='IMDB امتیاز') users_score = models.FloatField(default=0, verbose_name='امتیاز کاربران') # seen_number = models.FloatField(default=0, verbose_name='تعداد نفراتی که فیلم را مشاهده کرده اند') publish_status = models.CharField(max_length=55, null=True, blank=True) is_free = models.BooleanField(default=False, verbose_name='رایگان است') visit_times = models.IntegerField(default=0) play_times = models.IntegerField(default=0) year = models.CharField(max_length=4, verbose_name='سال') time = models.CharField(max_length=55, verbose_name='مدت زمان فیلم') tv_pg = models.PositiveSmallIntegerField(choices=tv_pg_choice, default=5, verbose_name='درجه بندی سنی') actor = models.ManyToManyField(Actor, blank=True, verbose_name='بازیگران') director = models.ManyToManyField(Director, blank=True, verbose_name='کارگردان') thumb_image = models.ImageField(null=True, blank=True, editable=True, upload_to=image_path, verbose_name='تصویر انگشتی فیلم') image_1920x1080 = models.ImageField(null=True, blank=True, editable=True, upload_to=image_path, verbose_name='تصویر بنر دسکتاپ فیلم') image_600x810 = models.ImageField(null=True, blank=True, editable=True, upload_to=image_path, verbose_name='تصویر بنر موبایل فیلم') country = models.ManyToManyField(Country, verbose_name='کشور') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) users_score_n = models.IntegerField(default=0) users_score_p … -
Unable to perform conditional redirect from a class based view Django
I am trying to redirect a user who has already registered to a different view. here is the code for the views.py However when qs.exists() = true I get an error 'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.' I am a beginner have read the documentation but unable to find where i am going worng. Thanks from django.shortcuts import render, redirect from django.views import View from Lpage.forms import SubscriberEntryForm from Lpage.models import Subscriber class homeview(View): def get(self,request): msg = request.session.get('msg', False) if(msg): del(request.session['msg']) return render(request,'Lpage/index.html') def post(self, request): form = SubscriberEntryForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) qs = Subscriber.objects.filter(email__iexact=obj.email) if qs.exists(): return redirect('messageview') else: obj.save() request.session['msg'] = "msg" return redirect(request.path) def messageview(request): return render(request,'Lpage/messages.html',{}) -
How to does not include default values in calculations in django?
I am working on Django where I have two models Gigs and Orders and I am calculating average Completion time of order of every gig. in order model I have two fields order start time (which I'm sending whenever seller accepts the order) and order completed time (which I'm sending when seller delivered) the order. but the problem is that I can't set these both field default=Null cause I am using it in Gig order and views. so I set them as default=timezone.now. but now I want when I calculate average completion time it should not include that fields which are initialized automatically by default. Models.py class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=timezone.now) orderCompletedTime = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.annotate( _average_completionTime=Avg( ExpressionWrapper(F('gig__orderCompletedTime') - F('gig__orderStartTime'), output_field=DurationField()) ) … -
How can i pass an form instance to another form while both are saving Django?
Info: I have a python Django web app where users are allowed to create articles. Each article has multiple files(photos/videos) that are associated with that article. I have three model TemporaryUpload(1), TemporaryUploadChunked(2) and StoredUpload(2). Everything is working fine. first Data is asynchronously uploaded to TemporaryUpload before submitting the form. after hit form submit button data stored into StoredUpload table. This is working perfectly for me! Now What i want to do: When the user hit submit button article is create and files are linked with the article Which files are submited by user into StoredUpload. how can i associate these file with article when user hit submit button? What I have so far: i have ArticleModel/ArticleForm. when the user hit submit button The article created and the files are appended into StoreUpload table it's working fine. But the files are not linked it with an article. i want to link the files with artcle. models.py class TemporaryUpload(models.Model): FILE_DATA = "F" URL = "U" UPLOAD_TYPE_CHOICES = ( (FILE_DATA, "Uploaded file data"), (URL, "Remote file URL"), ) upload_id = models.CharField( primary_key=True, max_length=22, validators=[MinLengthValidator(22)] ) file_id = models.CharField(max_length=22, validators=[MinLengthValidator(22)]) file = models.FileField(storage=storage, upload_to=get_upload_path) upload_name = models.CharField(max_length=512) uploaded = models.DateTimeField(auto_now_add=True) upload_type = models.CharField(max_length=1, choices=UPLOAD_TYPE_CHOICES) … -
I am developing library management system in Django I don't know how should I store the data?Please reply [closed]
I am developing library management system in Django, I didn't want to host the website online ***Now how should I store the data of the website if I didn't host the website I am using a database but how will the librarian run the website as he doesn't know how to run commands like "python manage.py runserver" *** As there any way so that I can create the website for library without hosting online and run the website easily -
How to execute tasks sequentially in celery based on a parameter?
I am currently working on a data polling app in which we have some 600-700 different data sources. We have a client installed at every source location which periodically collects data and sends a CSV file to the server. At server, we receive the CSV and process the data later using celery tasks. We have currently 10 celery workers running on the server which handle one file each simultaneously. Although, we do want this concurrency yet we would also like to implement celery in such a way data files from one source should always be processed sequentially. That means, if the files are from same data source 2nd file should always be processed only after 1st file is completely processed. Does celery provide such an option or I need to build some custom queue management solution? Note: I am currently using Celery with Django. -
Deploying React - django apps on Azure web apps
Locally, I am able to run my django app and react app. I migrated the django app to the azure web apps. My question is, what is best practice regarding connecting the react app to the django app. Should I start another web app instance, or should I try to run both on the same instance?