Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to add a default Variation when creating a new Item
I have created a an item model with variation and variation Manager model. I want to add a default variation function so that when I create a new item a default of size variations is created small medium and large. Here is the model: class Item(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(unique=True) image = models.ImageField(blank=False, upload_to='') timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size',), ('color', 'color',), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField( max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) price = models.DecimalField( decimal_places=2, max_digits=100, null=True, blank=True) objects = VariationManager() active = models.BooleanField(default=True) def __str__(self): return self.title -
Django | where to iterate: views or template
I'm wondering where is the best place to build the code I need: template or views. Let's say I have 3 lists and inside some dicts: sell = [{'date__month': 1, 'date__year': 2020, 'sells_by_month': 15}, {'date__month': 5, 'date__year': 2020, 'sells_by_month': 115}] payments = [{'date__month': 5, 'date__year': 2020, 'payments_by_month': 18}] provider = [{'date__month': 4, 'date__year': 2020, 'providers_by_month': 200}, {'date__month': 5, 'date__year': 2020, 'providers_by_month': 320}] For every month/year I need to check if there is any sells, payments or providers. I need to display in templates something like that Period Sells Payments Provider 01-2020 15 0 0 02-2020 0 0 0 03-2020 0 0 0 04-2020 0 0 200 05-2020 115 18 320 06-2020 0 0 0 I can build another dict with a loop in views.py but anyway I'll need to create another loop to display all this table in templates. So I guess this could take too much time with a desnecessary looping in views.py. Is it possible to create some code directly in templates with just one if-else loop condition OR it's a good pratice to build the whole dict in views.py? What do you think? -
Dropzone does not submit form and do proper ajax call
I am using Dropzone to upload images in my form and then send to my Django view in order to process. However, I have an issue. If I do not add any images the form is submitted correctly and Ajax will update my template properly. However, if I add an image, I can see the form is submitted however, it requires me to refresh the page. if I remove preventDefault() and stopImmediatePropagation the form will then be submitted twice. This is my form: <form method="POST" data-url="{% url 'home:post-create' %}" id="my-dropzone" class="dropzone post-create-form" enctype="multipart/form-data"> <!-- my form foes here --> <div class="dz-default dz-message"></div> <div class="modal-footer col-12"> <button type="submit" id="sub-etal" class="btn btn-primary" style="border-radius: 20px; width: 100%;">Post</button> </div> </form> This is my Dropzone initialization: <script> Dropzone.autoDiscover = false; $(document).ready (function () { var myDropzone = new Dropzone("#my-dropzone" , { dictDefaultMessage: '', addRemoveLinks: true, acceptedFiles: ".jpeg,.jpg,.png,.gif", uploadMultiple: true, url: "/home/post/create/", autoProcessQueue: false, paramName: "images", maxFiles: 4, thumbnailWidth: 350, dictRemoveFile : 'Remove', thumbnailHeight: 350, previewTemplate: document.getElementById('preview-template').innerHTML, previewsContainer: "#preview-selected", init: function () { var myDropzone = this; this.element.querySelector("button[type=submit]").addEventListener("click", function (e) { if (myDropzone.getQueuedFiles().length > 0) { e.preventDefault(); e.stopImmediatePropagation(); myDropzone.processQueue(); } else { myDropzone.uploadFiles([]); //send empty } }); this.on("sendingmultiple", function () { }); this.on("successmultiple", function (files, response) … -
How can i update user table when profile table update?
I have profile model,i want to update user model when is_active field in this model changed class Profile(models.Model): user = models.OneToOneField(User, blank=True, null=True,on_delete=models.CASCADE) id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) when is_active field in profile model update,i want update is_active field in user model in django. Profile.objects.filter(pk=user_id).update(is_active=status) -
I'm using ubuntu, django 3.0.5, sqlte3 ...Help!!! Thanks! running "python manage.py shell" in command line, it gives error:
i am learning django, I'm using python 3.8, django 3.0.5, sqlite 3 after running "python manage.py shell". is this due to sqlite? The Error i get is: Traceback (most recent call last): SyntaxError: invalid syntax ModuleNotFoundError: No module named 'apt_pkg' Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/hrishi/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/hrishi/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hrishi/.local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/hrishi/.local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/hrishi/.local/lib/python3.8/site-packages/django/core/management/commands/shell.py", line 99, in handle return getattr(self, shell)(options) File "/home/hrishi/.local/lib/python3.8/site-packages/django/core/management/commands/shell.py", line 35, in ipython from IPython import start_ipython File "/usr/local/lib/python3.8/dist-packages/IPython/__init__.py", line 55, in <module> from .core.application import Application File "/usr/local/lib/python3.8/dist-packages/IPython/core/application.py", line 25, in <module> from IPython.core import release, crashhandler File "/usr/local/lib/python3.8/dist-packages/IPython/core/crashhandler.py", line 27, in <module> from IPython.core import ultratb File "/usr/local/lib/python3.8/dist-packages/IPython/core/ultratb.py", line 119, in <module> from IPython.utils import path as util_path File "/usr/local/lib/python3.8/dist-packages/IPython/utils/path.py", line 17, in <module> from IPython.utils.process import system File "/usr/local/lib/python3.8/dist-packages/IPython/utils/process.py", line 19, in <module> from ._process_posix import system, getoutput, arg_split, check_pid File "/usr/local/lib/python3.8/dist-packages/IPython/utils/_process_posix.py", line 23, in <module> import pexpect File "/usr/lib/python3/dist-packages/pexpect/__init__.py", line 75, in <module> from .pty_spawn import spawn, spawnu File "/usr/lib/python3/dist-packages/pexpect/pty_spawn.py", line 14, in <module> from .spawnbase import SpawnBase File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", … -
Django views count
''' models.py ''' class ViewsCount(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post_views = models.ForeignKey(BlogSlider, on_delete=models.CASCADE) views_count = models.IntegerField(default=0) def __str__(self): return self.user.username ''' views.py, i get the user. i also want to get post_view. How can i get it? ''' def get_object(self): blog_obj, created = ViewsCount.objects.get_or_create(user=self.request.user) blog_obj.views_count += 1 blog_obj.save() return blog_obj -
Run a task in the background in django immediately in a view and have it repeat
How can I fire a background job immediately in a view in django without waiting for it to complete? I have a task that I want to run in the background as soon as my app starts up because it's a long-running task, and I'd like for it to keep running over and over as long as the server is running. Celery seems too robust for what I want to achieve, is there a way to do this with Django-background-tasks? I tried multithreading, but it made my app very laggy. The task I want to keep running is subprocess.Popen(["python", "create_model.py"]) and I use popen so that the rest of the program doesn't wait for it to complete to proceed. -
Two apps with "default" cache backend
Django 3.0.6 settings.py CACHES = { # https://github.com/jazzband/django-redis # Redis { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # }Redis # file_resubmit { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, "file_resubmit": { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', "LOCATION": '/tmp/file_resubmit/' }, # } file_resubmit } Problem Apps file_resubmit and django-redis say in their documentations that cache's backend is "default". Could you tell me how to write this CACHES so that the two apps work well together? -
Django - What is the right way to save multiple selections from Django form
What is the correct way of saving multiple selections selected from Django form? this is my model class Rgn_Details(models.Model): request_no = models.ForeignKey(Request_Flow, on_delete=models.CASCADE, related_name='request_ref') region = models.ForeignKey(Region, on_delete=models.PROTECT, related_name='regn') class Meta: ordering= ['-region'] def __str__(self): return self.region I have a model form like this. class RegionForm(forms.ModelForm): region = forms.ModelMultipleChoiceField(queryset=Region.objects.all().order_by('region_id'), widget=Select2MultipleWidget) class Meta: model = Rgn_Details fields = ['region'] this is my view def create(request): if request.method == 'POST': form1 = RequestForm(request.POST, prefix="form1") form2 = RegionForm(request.POST, prefix="form2") if form1.is_valid() and form2.is_valid(): req = form1.save() region = form2.save(commit=False) region.request_no = req region.save() if I try region.save() its not working though form validation have no errors... I am getting Cannot insert the value NULL into column 'region_id', table 'rgn_details' Am I doing something wrong with save method when you have multiple selections with Django-Select2 widget? -
Why does my Django custom middleware not working
trying to create a custom middleware, added the middleware class to the middleware in settings.py file but my middleware doesn't seem to function(but when i print out inside the middleware, i get the output. from .models import MarketingMessage class DisplayMarketing: def init(self, next_layer=None): self.get_response = next_layer def process_request(self, request): try: request.session['marketing_message'] = MarketingMessage.objects.get_featured_item().message except: request.session['marketing_message'] = False # return None def process_response(self, request, response): # Do something with response, possibly using request. return response def __call__(self, request): response = self.process_request(request) if response is None: response = self.get_response(request) response = self.process_response(request, response) return response -
Apache not responding to SSL requests
I have django app configured with apache2, it is responding fine to http requests, website works seamlessly. However when I try to connect through https, it doesn't respond. On looking through what might be te issue I found these: 1) port might be blocked on firewall 2) problems in Apache configuration Netstat and lsof commands show that Apache is listening on 443 port. Ufw has apache, 443, 80 and 800 allowed. So I think there might be an issue with apache SSL config only. But I tried this. I used wget command to download an image from my website. Both http and HTTPS is retursn 200 OK and file is downloaded. Also, using openssl -showcerta command shows me the proper SSL certificate I have installed. So that means maybe Apache is responding too. So what might be the issue here? I've tried restarting the server. Restarting apache. But my web browser throws an error 'the site took too long to respond'. -
Why are my changes not being reflected in css? Django bootstrap
So I am noticing that my css changes are not being reflected. I did a hard-reload and cleared the cache but still nothing. Like I can literally delete the css file and my badge which I'm trying to edit is still there... it only goes away once I take it off of base.html directly. So what is going on here? I have a static folder in my app, with a css folder and then my css/notification file. I tried doing collectstatic through terminal but that doesn't do anything. **settings.py/static ** STATIC_URL = '/static/' STATICFILES_DIR = [ "/DatingAppCustom/dating_app/static", ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'dating_app/media') -
Django pre populate form field with foreign key (not a user model)
I've been struggling with passing the pk from objects in ListView template. How would I pre populate the vehicle2wash field in the WashModel form by selecting a specific CarModel.object in a generic ViewList template? This view is giving me an error but I feel like it's the closest I can get. models class CarModel(model.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) plates = models.CharField(max_length=20, unique=True) class WashModel(model.Model): message = models.CharField(max_length=20, unique=True) vehicle2wash = models.ForeignKey(CarModel, on_delete=models.CASCADE) views class WashService(LoginRequiredMixin, CreateView): model = WashModel form_class = WashServiceForm template_name = 'service_app/standard_wash_form.html' def get_initial(self): initial = super(WashService, self).get_initial() initial = initial.copy() initial['car_pk'] = request.CarModel.pk return initial HTML ListView template <form action="{% url 'service_app:standard_service' car_pk=object.pk %}" method='POST' > {% csrf_token %} <input class=btn btn type="submit" value="Add"/> </form> -
Django - How to get details from many-to-many relationship in multiple select form field
I have 2 models linked with a M2M relationship and I would like to build a form allowing to manage the links but also to add controls on selected values. This take place outside admin templates. I managed defining the form to manage links but I was not able to consider additional information to define validity controls. Here are my models: class EventGroup(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name="société" ) users = models.ManyToManyField(UserComp, verbose_name="utilisateurs", blank=True) group_name = models.CharField("nom", max_length=100) weight = models.IntegerField("poids", default=0) class Event(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name="société" ) groups = models.ManyToManyField(EventGroup, verbose_name="groupes", blank=True) rules = [("MAJ", "Majorité"), ("PROP", "Proportionnelle")] event_name = models.CharField("nom", max_length=200) event_date = models.DateField("date de l'événement") slug = models.SlugField() current = models.BooleanField("en cours", default=False) quorum = models.IntegerField(default=33) rule = models.CharField( "mode de scrutin", max_length=5, choices=rules, default="MAJ" ) The form: class EventDetail(forms.ModelForm): groups = forms.ModelMultipleChoiceField( label = "Liste des groupes", queryset = EventGroup.objects.none(), widget = forms.CheckboxSelectMultiple, required = False ) class Meta: model = Event fields = ['event_name', 'event_date', 'quorum', 'rule', 'groups'] The view: def event_detail(request, evt_id=0): if evt_id > 0: current_event = Event.objects.get(id=evt_id) event_form = EventDetail(request.POST or None, instance=current_event) else: event_form = EventDetail(request.POST or None) company = Company.get_company(request.session['comp_slug']) event_form.fields['groups'].queryset = EventGroup.objects.\ filter(company=company).\ order_by('group_name') if … -
How to export zip in django admin?
I have images fields in my model. How to I can export to zip from my django admin. Here is my code from django.db import models class ModelWithImage(models.Model): image = models.ImageField( upload_to='images', ) -
How to associate foreignkey data in django 3.0
How do I pull all of the users and put their full name into a context that I pass to a view? My view currently pulls all of the filtered rows and I want to replace the id of the user with their full name before I pass the context to the view. This is probably very simple, but I can't seem to make it work. The field trigger_caused_by holds the id of the user that made the change that fired the trigger. Account models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True, verbose_name="Email Account") first_name = models.CharField(max_length=50, blank=True, null=True, verbose_name="First Name") last_name = models.CharField(max_length=50, blank=True, null=True, verbose_name="Last Name") active = models.BooleanField(default=False, verbose_name="Is Account Active") approved = models.BooleanField(default=False, verbose_name="Is Account Approved") readonly = models.BooleanField(default=True, verbose_name="Read Only Account") staff = models.BooleanField(default=False, verbose_name="Staff Account") admin = models.BooleanField(default=False, verbose_name="Admin Account") USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return f"{self.email} - {self.last_name}, {self.first_name}" def get_full_name(self): if self.last_name and self.first_name: full_name = self.last_name + ", " + self.first_name return full_name return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active @property … -
Own data for everyuser in django
So I am building a to do app in Django. I have created databases for the users and todo items. But I have a problem, how can each user have its own data. Like every user should add their own data. It seems like there is no answer out there. My models.py class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title My forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] So how can I connect those both. I have red that I have to use foreign key. But I really don't understand how I can do it -
django-elasticsearch-dsl-drf suggest url gives 404 error
I am using django-elasticsearch-dsl-drf and have document configured with suggest completionfield. Also my viewset definitation has suggesters. Document: class ProductsDocument(Document): productName = fields.TextField( attr='productName', fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField(), } ) description = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField(), 'lower': fields.Text(analyzer=html_strip), } ) Viewset: class ProductsView(BaseDocumentViewSet): document = ProductsDocument serializer_class = ProductsSerializer pagination_class = PageNumberPagination lookup_field = 'id' filter_backends = [ FilteringFilterBackend, SuggesterFilterBackend, IdsFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, CompoundSearchFilterBackend, NestedFilteringFilterBackend, CompoundSearchFilterBackend, ] search_fields = ( 'productName', 'price', 'inStock', 'description', 'sellerprof.country.name', ) suggester_fields = { 'productName_suggest': { 'field': 'productName.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], 'default_suggester': SUGGESTER_COMPLETION, }, 'description_suggest': { 'field': 'description.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], 'default_suggester': SUGGESTER_COMPLETION, }, 'productName_suggest': 'productName.suggest', 'description_suggest': 'description.suggest', } When I try using suggest completion URL, I got NotFoundError enter image description here I am not sure what I am missing. -
Popup modal not showing up
Im working on a collage project and i want to create user signup window that popups on the click of specified text. 100% of code is pasted from https://pypi.org/project/django-bootstrap-modal-forms/ but somehow for me isn't working. urls.py from django.urls import path from . import views urlpatterns = [ path("", views.check_session, name="check_session"), path("log_in.html", views.log_in_view, name="log_in_view"), path('registration/', views.RegistrationView.as_view(), name="registration"), ] views.py class RegistrationView(BSModalCreateView): form_class = CustomUserCreationForm template_name = 'registration.html' success_message = 'Success: Sign up succeeded. You can now Log in.' forms.py class CustomUserCreationForm(PopRequestMixin, CreateUpdateAjaxMixin, UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] log_in.html (containing trigger of modal) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Trading-Bot Mileva</title> <link rel="stylesheet" href="{% static 'css/log_in_style.css'%}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body> <div class="log_in_registration_bg"> <video autoplay muted loop> <source src="{% static 'images_videos_sounds/log_in_registration_background.mp4' %}" type="video/mp4"> </video> </div> <div class="container-fluid"> <form action="log_in.html" method="POST"> <div class="space"></div> <div class="row d-flex justify-content-center"> <div class="input-group mb-3 col-4"> <div class="input-group-prepend"> <span class="input-group-text text-primary">Username</span> </div> {{log_in_form.username}} </div> </div> <div class="row d-flex justify-content-center"> <div class="input-group mb-3 col-4"> <div class="input-group-prepend"> <span class="input-group-text text-primary">Password</span> </div> {{log_in_form.password}} </div> </div> <div class="row d-flex justify-content-center"> {%csrf_token%} <input class="btn btn-outline-primary col-1" type="submit" value="Log in"> </div> </form> <div class="modal fade" tabindex="-1" … -
CreateView with condition if exists
I am trying to use CreateView to create a property if it doesn't exist. Though if there is a property with street and zipcode it will not create a new property. Models.py class Property(models.Model): owner = models.ForeignKey(CustomUser, null=True, on_delete=models.SET_NULL) street = models.CharField(max_length=50, blank=False) zipcode = models.CharField(max_length=10, blank=False) class Meta: unique_together = ('street', 'zipcode') However, if the owner field is empty on the already created object. I would simply like to pass the user submitting the form to the owner field of the already created property to "claim" the property. View.py class AgentNewProperty(CreateView): model = Property fields = ['street','zipcode',] template_name = 'create_property.html' success_url = 'success.html' def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) Am I thinking this properly? Not really sure how to go about solving this. Any help greatly appreciated! -
How to upload an html string as pdf file to Google Cloud Storage ? (Python)
I am trying to upload an HTML string, as a PDF file, to GCS, from my Django application. import google, os from google.cloud import storage class GcpHelper: def __init__(self, bucket_name): self.service_account_json_path = 'google_auth.json' storage_client = storage.Client.from_service_account_json(self.service_account_json_path) try: self.__bucket_name = bucket_name self.bucket = storage_client.get_bucket(bucket_name) except Exception as err: logger.error("Error {} while connecting to bucket {}!".format(str(err), bucket_name)) def put_data_in_bucket(self, file_name, data, content_type="application/pdf"): """Uploads data to gcp bucket""" try: blob = self.bucket.blob(file_name) blob.upload_from_string(data, content_type=content_type) return True except Exception as err: logger.error("Unable to upload file {} due to {}".format(file_name, str(err))) raise Exception("Write to gcp failed!") gcp_helper = GcpHelper('bucket_name') voucher_html = open('voucher_test.html').read() #some operations on voucher_html string here gcp_helper.put_data_in_bucket("booking/voucher.pdf", voucher_html) I was trying to upload the string directly somehow, rather than saving it as PDF file and then uploading the file. (If nothing works, then will have to do that) But of course this didn't work as the PDF file uploaded was corrupted. I was hoping the blob.upload_from_string would take care of any formatting/encoding that would be required.But as it seems, it doesn't. ;) -
Django access from outside VMWARE (Public access)
I'm using Django 3.0.5 under Kalilinux2020.1 launched from a virtual machine on VMWARE ESXI. I want to make my project public but it's not working. I modified the settings.py and add : ALLOWED_HOSTS = ['*'] The django server is launched using pyhton3 manage.py runserver 0.0.0.0:8080 I allowed the port 8080 in the firewall using firewall-cmd --zone=public --add-port=8080/tcp and I forwarded the port 8080 in the router P.S: I can access to my server from the other machines in the VMWare (LAN) but i can't get access from outside. Anyone has faced this problem? -
How can I take star rating of product in django and how can I store it in model and render it to template?
I want to take product rating in django app for this I have made two models my two models are like this from django.db import models from accounts.models import * from django.core.validators import MinValueValidator, MaxValueValidator # This is my product model. class Products(models.Model): name = models.CharField(max_length=50) img = models.ImageField(upload_to='productImage') CATEGORY = ( ('Snacks','Snacks'), ('Juice','Juice'), ) category = models.CharField(max_length=50, choices=CATEGORY) description = models.TextField() price = models.FloatField() review = models.TextField() @property def no_of_rating(self): rating = Rating.objects.filter(product=self) return len(rating) @property def rating(self): sum = 0 ratings = Rating.objects.filter(self) for rating in ratings: sum += rating if len(ratings>0): self.rating_set(sum//len(rating)) else: self.rating_set(0) def __str__(self): return self.name #this is the table am using for storing the ratings class Rating(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) def __str__(self): return str(self.product)+"---"+str(self.user) How can i calculate the average rating for each product and store it in the product model and how can I render it to django template? -
How do I repopulate user info in a Django form?
Previsouly, I used forms.ModelForm to create a Django form and in views.py used: p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) This way, if the form was not valid when submitted, it would repopulate the information the user entered previously. This saved a user from having to enter the information again. I have since changed to forms.Form because I can't figure out how to customize Crispy Forms using forms.ModelForm, but now if I call instance=request.user.profile, I get an error. What can I do to repopulate the information the user previously placed in the form so they do not have to do it again? -
Proper way of query in mongoDB
If I will use MongoDB, say I had a set of documents that contained “user_id”, “password”, and “display_name”. What query should I make if I wanted to collect all display names that start with the letter? and the password doesn’t show up in the results.