Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
New to Django, Saving ForeignKeys, is this the right way?
So I am confused as to how I should save foreign keys relation in Django so far this is my first attempt and I am doing it like this with save(commit=False) when the form data is sent back to the server from POST request in my views.py as follows: def create_listing(request): if request.method == 'POST': form = get_product_category_fields(category=eval('Broomstick'), data=request.POST) imageform = ImageForm(request.POST, request.FILES) print(form.errors.as_data()) print(imageform.errors.as_data()) if form.is_valid() and imageform.is_valid(): fkey_image_album = imageform.save(commit=False) fkey_product_album = form.save(commit=False) album = ImageAlbum() album.save() fkey_product_album.album = album fkey_image_album.album = album fkey_product_album.save() fkey_image_album.save() return render(request, "auctions/index.html") forms.py from django.forms import ModelForm from .models import * def get_product_category_fields(category, data): class Category_Form(ModelForm): class Meta: model = category exclude = ['date_added', 'user', 'product_comment', 'album'] form = Category_Form(data=data) return form class ImageForm(ModelForm): class Meta: model = Image exclude = ['album'] models.py class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lte=100, length__lte=100) class Image(models.Model): image = models.ImageField(upload_to='uploads/') default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) def __str__(self): return self.image class auction_product(models.Model): product_name = models.CharField(max_length=64) date_added = models.DateField(default=timezone.now) user = models.ManyToManyField(User, through='product_ownership', related_name='product_user') product_bid = models.ManyToManyField(User, through='bid', related_name='product_bid') product_comment = models.ManyToManyField(User, through='comment') album = models.OneToOneField(ImageAlbum, related_name='product_model', on_delete=models.CASCADE) def __str__(self): return self.product_name -
facing problem in cyberpanel with hosting django website
i have tried to site from https://blog.cyberpanel.net/2019/01/10/how-to-setup-django-application-on-cyberpanel-openlitespeed/ but it is not helping . i think problem is related to openlitespeed. if anyone got idea help me thanks in advance . i was following same procedure as blog and same context context / { type appserver location /home/django.cyberpanel.net/public_html/cyberpanel binPath /usr/local/lsws/fcgi-bin/lswsgi appType wsgi startupFile cyberpanel/wsgi.py envType 1 env LS_PYTHONBIN=/home/django.cyberpanel.net/public_html/bin/pyhton env PYTHONHOME=/home/django.cyberpanel.net/public_html/ } -
I want to get the total of sales for each item
I am working on a small django project. In my models.py I have a Product class like: class Product(models.Model): ... ... ... And I have a Sales class like: class Sales(models.Model): item = models.ForeignKey(Product) quantity = models.IntegerField() I want to display a list of all my products with the total of sales for each product... I hope my question is clear enough. Thanks -
Django returns "CSRF Verification Failed" only when uploading large files [Nginx + Gunicorn]
I'm working on a project which involves uploading large files (a whole folder containing a lot of files actually). All post requests, including uploading small files and folders work well. However, when I try to upload a large folder with POST request, I get 403 "CSRF Verification Failed" error. I did include the csrf token which is why all my post requests work. This only happens with large files/folder. I've included these lines in nginx.conf: client_max_body_size 4G; proxy_send_timeout 7300s; proxy_read_timeout 7300s; I set my client_max_body_size to 4GB but when I upload a folder of 100MB I still get the CSRF failed error. I've tried uploading a folder of about 8MB and it works fine. I'm so confused now. Can someone help me please? Thanks in advance! -
Django redirect, reverse
How can i do it so the user after editing the post doesn't get redirected to homepage but to the detail view of the post they just edited My views.py from . models import Post from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import DeleteView, UpdateView, CreateView from django.urls import reverse_lazy def home(request): posts = Post.objects.all() return render(request, 'pages/index.html', {'posts':posts}) def detail(request, slug): post = Post.objects.get(slug=slug) return render(request, 'pages/detail.html', {'post':post}) class edit(LoginRequiredMixin, UpdateView): model = Post template_name = 'pages/edit.html' fields = ['title','image','body'] success_url = reverse_lazy('pages:homepage') def dispatch(self, request, *args, **kwargs): handler = super().dispatch(request, *args, **kwargs) user = request.user post = self.get_object() if post.author != user: raise PermissionDenied return handler my models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import pre_save from A_Tech_Blog.utils import unique_slug_generator class Post(models.Model): title = models.CharField(max_length=300) slug = models.SlugField(blank=True, null=True, max_length=300) image = models.ImageField(upload_to='post_images', default='default.jpg') time_created = models.DateTimeField(auto_now_add=True) views = models.IntegerField(default=0) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.title} -- Author={str(self.author)}' class Meta: ordering = ['-time_created'] verbose_name_plural = 'Posts' def get_absolute_url(self): return reverse('pages:detail', args=(self.slug)) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Post) I want to be able to edit the … -
Django: Returning data from a linked table
I am doing a project that revolves around storing scores against players. Each player can shoot several rounds, some several times. I am trying to make a page that shows a list of the rounds shot and the number of times that round has been shot. This will ultimately be a link to a table of those rounds. I have been able to bring back the round id but cannot get the round name back from the linked table. This seems such a basic thing but I cannot figure it out. My models are: class Score(models.Model): BOW_TYPE = ( ('R', 'Recurve',), ('C', 'Compound',), ('L', 'Longbow',), ) archer = models.ForeignKey('User', related_name='scores', on_delete=models.CASCADE) rndname = models.ForeignKey('Round', related_name='rounds', verbose_name=("Round Name"), on_delete=models.CASCADE) age = models.ForeignKey('Age', related_name='scores', on_delete=models.CASCADE) bowtype = models.CharField(max_length=1, verbose_name=("Bow Type"), choices=BOW_TYPE) score = models.IntegerField(default=0) dateshot = models.DateField(verbose_name="Date Round Shot", default=timezone.now) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.archer) + ' | ' + str(self.score) + ' | ' + str(self.rndname) + ' | ' + str(self.created_date) class Round(models.Model): roundname = models.CharField(max_length=200) maxscore = models.IntegerField(default=0) def __str__(self): return str(self.roundname) I can return the number id of the distinct rounds using this line in views.py: posts = Score.objects.values('rndname').distinct().order_by('rndname') and this returns the round id as … -
How to paginate 3 different objects in the same page efficiently?
I have 3 different models ModelA,ModelB,ModelC, all related to the user. So, I want to show them in a list ordered by date (infinite scroll down). But it's starting to take too much to load them at once. My ajax view: ... list1 = user.modela_list.all() list2 = user.modelb_list.all() list3 = user.modelc_list.all() result = list1 + list2 + list3 return render(request,'template.html',context={'result':result}) The template (I use the regroup templatetag to group them by the DateTimeField they all have): <div class="tab-pane fade show active" id="tab1" role="tabpanel"> {% regroup result by date.date as result_list %} {% for group_by_date in result_list %} <div class="section-title">{{ group_by_date.grouper }}</div> <div > {% for object in group_by_date.list %} .... {% endfor %} </div> </div> {% endfor %} </div> This creates something like this: So now, instead of just loading all the objects I wan't some kind of pagination but I can't figuire it out. How do I get the correct amount of ModelA, ModelB and ModelC objects by date?: #I can't do just this list1 = user.modela_list.all()[0:5] list2 = user.modelb_list.all()[0:5] list3 = user.modelc_list.all()[0:5] If I want 15 elements per load, how many of modelA, B and C do I have to show. I hope I explained myself. Thanks! -
TemplateDoesNotExist at / index.html Django
I'm learning django when create templates so got an error this is the error i got urls.py urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^first_app/',include('first_app.urls')), url(r'^admin/', admin.site.urls), ] settings.py BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_DIR = os.path.join(BASE_DIR, "static") -
Why doesn't this script add the structure correctly to the Django database?
I encountered a pretty weird problem with a ManyToManyField in Django today. When automatically reading input data from a dict the ManyToMany field gets populated falsely. My model is for this example pretty simple the UnitType has a name and 4 ManyToMany fields, one of them beeing possible_children = models.ManyToManyField('self', related_name='UnitTypeChildren', blank=True). When I run my management command which I set up for this minimal example I run (subtypes is truncutaded because there are a lot of values and everything with this works): building_subtypes = { 'garage/ parking': {'subtypes': [...]}, 'room': {'subtypes': [...], 'child': ['room']}, 'apartment': {'subtypes': [...]}, 'floor': {'subtypes': [...], 'child': ['room', 'apartment', 'garage/ parking']}, 'building': {'subtypes': [...], 'child': ['room', 'floor', 'apartment', 'garage/ parking']}, 'address': {'subtypes': [...], 'child': ['building', 'apartment', 'garage/ parking']}, 'business': {'subtypes': [...]}, 'other': {'subtypes': [...]} } for typ in building_subtypes: ut, new = UnitType.objects.get_or_create(name=typ) for subtype in building_subtypes[typ]['subtypes']: UnitSubType.objects.get_or_create(name=subtype, unit_type=ut) if 'child' in building_subtypes[typ]: for child in building_subtypes[typ]['child']: child_ut, new = UnitType.objects.get_or_create(name=child) print(subtype.name + ' ' + child_ut.name) # Prints correctly ut.possible_children.add(child_ut) # Check if it worked for ut in UnitType.objects.all(): childstring = "" for child in ut.possible_children.all(): childstring += str(child) + ', ' print(ut.name + ': ' + childstring) # Prints alternate structure When accessing … -
How to configure MySQL to automatically decrypt data/images request?
I am building a Django app that allows user to upload images to MySQL and the app also displays the uploaded images to users from MySQL. I plan to encrypt the filepath that stores those images. Is there a way to configure MySQL to automatically decrypt data/images when my Django app queries the database for those encrypted image/file path? -
How do I add 'list' attribute to an input field using jQuery?
I'm struggling to figure out the following; I have a django form field hidden in {{ field.field }}. It renders out as <input type="text" name="field-id" value="100" id="id_set-0-product" class="vForeignKeyRawIdAdminField"> I can tagret it using jQuery by its id but I need to add a list = "choicelist" which corresponds with <datalist id="choicelist" style="text-align: center"> </datalist> which I populate using ajax requests. How do I add the list = "choicelist" to it? Any help would be much appreciated! -
How To Attach One User To Another User For Payment And Upline AutoMatically In Django When New User Register
Am building a django project and i want Newly Auntheticated User to be Attached to Old Authenticated User as Upline for payment purposes(i sure know how to handle the payment case). This Attachment or Assign of this New User to Old User should be based on the Request of the Old User and the willingness of the New Users. There is a payment category for Users of the App in a range of $50, $100, $150, $200. Lets take for example- the old User Request For a payment of $50 and the new user select a category of payment of $50. Then the new user which is assigned to the old user will be automatically Assigned to pay the new User the amount Category Requested by the old User and agreed upon by the New Users. After the Request from the old User and Request from the New User then i will want my app to automatically assign the old user to the new user. Note. I will determine the other conditions that will enable the old user Elligible to make such requests. Lets take a look at my Code. Payment Category Class PayCategory(models.Model): Amount = models.Charfield(max_length=6) My Manager which … -
Unable to POST nested JSON using Invoke-WebRequest
I am trying to create a script that will copy some Django permissions, modify them and then re-apply them to our instance. I appear to have no problems reading / writing the requests, with the exception of the permissions "constraints" value. This value needs to be sent in the form of a JSON query. It appears that as the actual POST action itself needs to be performed as a JSON query, the Invoke-WebRequest cmdlet is modifying the nested JSON and adding escape characters. An example of the POST code in question is below (the remaining part of the script appears fine and is long so have not included however can do so if needed): $PostBody = @{'name' = $newPermName 'groups' = @($queGroupIDResult.results[0].id[0]) | ConvertTo-Json 'actions' = ConvertTo-Json @($subTempResult.actions) 'constraints' = @($subtempresult.constraints) | ConvertTo-Json} Try {$postResponse = Invoke-RestMethod -Body $PostBody -Headers @{ 'Authorization' = "Token $strapikey" } -Method Post -URI "$strserverurl/api/users/permissions/" Write-Host "--- Permission built"} #-ContentType 'application/json' Catch{Write-Host -ForegroundColor Red "--- There was an error performing the API post query"} An example of the 'constraints' value is: @($subtempresult.constraints) | ConvertTo-Json { "slug": "strsiteslug" } However when this is sent via Invoke-WebRequest it appears in the Django backend as: "[\r\n {\r\n \"slug\": … -
How to sum FloatFields in django models
I am trying to sum 4 FloatField models (cow1,2,3&4) and put their result in sum. Here's my models.py: from django.db import models class cow(models.Model): date = models.DateTimeField(auto_now_add=True, null=True) time = models.CharField(max_length=200, null=True) cow1 = models.FloatField(null=True, blank=True) cow2 = models.FloatField(null=True, blank=True) cow3 = models.FloatField(null=True, blank=True) cow4 = models.FloatField(null=True, blank=True) sum = models.FloatField(null=True, blank=True) def save(self): self.sum = self.cow1 + self.cow2 + self.cow3 + self.cow4 return super(cow, self).save() def __str__(self): return str(self.date.strftime("%d-%m-%Y")) + ", " + self.time Here's what I get: Little help pls, THANKS! -
How to use ModelManager to update ForeignKey relations
here are some models. class Library(models.Model): id = Models.AutoField(primary_key=True) books = models.ManyToManyField(Book) class Book(models.Model): id = Models.AutoField(primary_key=True) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=STATUS_IDLE) uuid = models.UUIDField(default=uuid.uuid4, unique=False) updated_at = models.DateTimeField(auto_now=True) These are the tables to explain problem better Book id status updated_at uuid 1 Ready 2020-12-14 15:10:08 20e125fc4cff4d5398a485cf43c502a0 2 Idle 2020-12-13 14:43:03 20e125fc4cff4d5398a485cf43c502a0 3 Ready 2020-12-12 13:34:11 20e125fc4cff4d5398a485cf43c502a0 4 Done 2020-12-11 13:11:34 bc191c9d71054b6282f0371538171774 5 Done 2020-12-10 12:50:17 bc191c9d71054b6282f0371538171774 Library_books id library_id book_id 1 15 1 I have many books with the same uuids and they have unique id's. My Models has more fields than I wrote above but I just simplified them. What I want to do is to change status of a last updated Book among same uuid using library_id. I tried this: Get book_id with library_id. Get uuid with the book_id that you've got in step1 Get all book_ids which have some uuid Find last updated one. Change status this is how I do currently: class SomeLibraryLogic(): def __init__(self, library): self.library = library def update_book_status(self): updated_book_list = [] books = self.library.books.all() for book in books: updated_book = Book.objects.filter(uuid=books.values_list("uuid").get()[0].last()) updated_book_list.append(updated_book) if len(updated_book_list) != 0: self.Library.cases.set(updated_book_list) self.task.save() This seems very dirty to me. Is it the most optimal way to do … -
Django Get Logged In User Info Outsides Views.py
I have been working on DRF. I usually prefer writing business logic on another python file rather than views.py. I tried to get current logged in user in views.py using self.request.user But I don't know how can I get same user info in my business logic file here is what I have came upto now in Views.py class AddBusCompanyStaffView(generics.CreateAPIView): serializer_class = AddBusCompanyUserSerializer def get_bus_company(self): return GetBusCompanyUseCase(bus_company_id=self.kwargs.get('bus_company_id')).execute() def perform_create(self, serializer): print(self.request.user) return AddBusCompanyUserUseCase(serializer=serializer, bus_company=self.get_bus_company() ).execute() I want user in my business logic section here -->usecases.py User = get_user_model() class AddBusCompanyUserUseCase(BaseUseCase): """ use this to add bus company of specific bus company """ def __init__(self, serializer: bus_company_user_serializers.AddBusCompanyUserSerializer, bus_company: BusCompany): self.serializer = serializer self._data = serializer.validated_data self._bus_company = bus_company def execute(self): self._factory() def _factory(self): user_position = self._data.pop('position') user_password = self._data.pop('password') user = User(**self._data) user.set_password(user_password) user.save() bus_company_user=BusCompanyStaff(user=user, position=user_position, staff_of=self._bus_company, created_by= #logged in user here ) how can I get self.request.user in created_by? -
Django view isn't redirecting to another page
I'm trying to redirect to another page from view, but it isn't working. My View is as follows: @csrf_exempt def detail(request, tconst): movie = get_object_or_404(Movie, tconst=tconst) #for rating if request.method=="POST": print("In Post") rating = request.POST.get('rating') ratingObject = Myrating() print(rating) ratingObject.user = request.user ratingObject.movie = movie ratingObject.rating = rating ratingObject.save() return redirect('home') return render(request, 'web/detail.html', {'movie':movie}) Here, my view should have redirected me to the home view but it's not happening. My URL patterns are as follows: urlpatterns = [ path('', views.home, name='home'), path('<int:tconst>/', views.detail, name='detail') ] I tried to see if there is any error but my console isn't showing any error, Console output is as follows: [17/Dec/2020 14:56:08] "GET /4/ HTTP/1.1" 200 5330 In Post 4 [17/Dec/2020 14:56:12] "POST /4/ HTTP/1.1" 302 0 [17/Dec/2020 14:56:12] "GET / HTTP/1.1" 200 10374 Please help me in solving this issue! -
python2.7 use package which python3.x could suppoet
I have a django program which developed by python2.7。but a new requirement needs a package that python3.x can support.How could I do? -
A choice in previous question is unchecked if the user move to the next question and select a choice
I am new to Django and HTML! I am currently implementing a questionnaire form. In the questionnaire URL, it shows questions and choices well. However, if the user moves to the next question and clicks a choice, the choice in the previous question is unchecked. Below is my questoinnaire.html code. {% if latest_question_list %} <form action="{% url 'results' %}" method="post"> <ul> {% for question in latest_question_list %} {% csrf_token %} <fieldset> {{forloop.counter}} {{ question.question_text }} <hr> {% for choice in question.choice_set.all %} <input type="radio" name= "choice" id="choice{{forloop.counter}}" value={{choice.id}}> <label for="choice{{forloop.counter}}">{{choice.choice_text}}</label><br> </hr> {% endfor %} </fieldset> {% endfor %} <input type="submit" value="Result"> </form> </ul> {% else %} <p>No questionnaires are available.</p> {% endif %} My questionnaire models.py is class Question(models.Model): question_text = models.CharField(max_length=200) pub_date=models.DateTimeField('date published', null = True) def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime. timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length = 100, null = True) value = models.IntegerField(default = 0) def __str__(self): return self.choice_text And this is views.py def question(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'questionnaire/question.html', context) -
when i select other form droplist then i want appear one textbox
Hi i have a list of industry in that there is a option other when i click on other then the textbox for other will be appear . i don't understand how to do this i have tried the djangoajax but not worked <div class="col-md-6 col-lg-5 " style = "position:relative; left:180px; top:20px; "> <div class="form-group"> <label class="col-sm-4 control-label"> Sector </label> <div class="col-sm-8"> {{ form.industry }} <span class="help-block"> {{ form.industry.errors }}</span> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" style = "top:20px; "> Others </label> <div class="col-sm-8" style = "top:20px; "> <!--{{ form.other }}--><input type="test" style="width: 350px;" id="model1234" > <span class="help-block">{{ form.other.errors }}</span> </div> </div> </div> -
django : Get the number of objects related to a model with foreign key
class Chapter(models.Model): title = models.CharField(max_length=100) class Lesson(models.Model): chapter = models.ForeignKey("Chapter", on_delete=models.CASCADE, related_name="lessons", related_query_name="lesson") I'm a beginner in Django. I want to get the number of lessons that are related to a Chapter with a foreign key and save that number as a field in the Chapter. I heard about select_related and prefetch_related but I didn't understand those completely. in my opinion, if I can get a list from : Chapter.objects.get(id=1).lessons My problem will be solved. but it returns <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager at 0x7ffa57a31b80> Not a list. So I can't get the number of lessons from it. is there a solution? -
Django rest framework: How can I make a viewset that returns custom data from another app's model?
I have two django apps. My project directory looks like: /my-project /accounts __init__.py admin.py api.py apps.py models.py serializers.py tests.py urls.py views.py /apartments __init__.py admin.py api.py apps.py models.py serializers.py tests.py urls.py views.py /my-project __init__.py asgi.py settings.py urls.py wsgi.py manage.py Accounts is an user authentication app and uses the default django user model. Apartments app's files looks like: models.py: from django.db import models from django.contrib.auth.models import User class Apartment(models.Model): apartment = models.CharField(max_length=50) resident = models.CharField(max_length=100) floor = models.IntegerField() ei_rate = models.FloatField(default=0) fi_rate = models.FloatField(default=0) oi_rate = models.IntegerField(default=0) owner = models.ForeignKey(User, related_name="apartments", on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) serializers.py: from rest_framework import serializers from apartments.models import Apartment class ApartmentSerializer(serializers.ModelSerializer): class Meta: model = Apartment fields = '__all__' api.py: from apartments.models import Apartment from rest_framework import viewsets, permissions from .serializers import ApartmentSerializer class ApartmentViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = ApartmentSerializer def get_queryset(self): return self.request.user.apartments.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) apartments/urls.py: from rest_framework import routers from .api import ApartmentViewSet router = routers.DefaultRouter() router.register('', ApartmentViewSet, 'apartments') urlpatterns = router.urls my-project/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/auth/', include('accounts.urls')), path('api/apartments/', include('apartments.urls')), ] I want to create a new django app in my project. For each user, I want to … -
Combine DetailView and SingleTableView in Django
How can I display a SingleTableView table together with a DetailView in django? What I want is to include or combine both into one. So that when calling DeviceDetailView i receive the device's details and a table of the devices's data (stored also in another model). Thank you class DataListView(SingleTableView): model = Data template_name = 'data/list.html' table_class = DataTable def post(self, request, *args, **kwargs): queryset = request.POST for i in queryset['list'].split(","): if queryset['action'] == 'delete': Data.objects.filter(data_id=i).delete() return HttpResponseRedirect('/data/') class DeviceDetailView(DetailView): template_name = 'devices/detail.html' def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Device, id=id_) -
How to implement switch accounts option in Django
Consider an application where there is a company account and employee account. I want to add employees as admin of the company. Then the admin should be able to switch account with the company. Is it possible to do the switch account option? I am a beginner in Django. Can anyone help me with this problem? -
django set ModelChoiceField's "to_field_name" to multiple columns
I want to provide multiple field names in Django's modelChoiceField's to_field_name something like field1 = forms.ModelChoiceField(queryset=myModel.objects.all(), required=False, empty_label="--------", to_field_name=["col1, col2"], widget=forms.Select(attrs={'class':'form-control'}), ) is this possible?? Do I need to override some classes?? Any help would be appreciated...