Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django char field with choices list
So, I want to implement a char field with choices list. The idea is that it looks like a common char field but when you click on it and start typing something in, a dropdown menu pops up and you can choose something (also it sorts choices depending on what user types in). How do we do that? -
Can't get LightSlider (JQuery) working in my Django application
For a website I am creating I want to add a slider/carousel using LightSlider (JQuery). For some reason it is not working and I can't figure out what the problem is. I tested if JQuery is working and it is. Thereby I tested the code outside of Django, so only with HTML, CSS, JS, JQuery, and it worked. What am I doing wrong? Head of base template <link rel="stylesheet" type="text/css" href="{% static 'blog/css/main.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'blog/css/lightslider.css' %}"> <script src="{% static 'blog/js/JQuery3.3.1.js' %}"></script> <script src="{% static 'blog/js/lightslider.js' %}" type="text/javascript"></script> Template/html page <div class="container" id="carousel"> <ul id="autoWidth" class="cs-hidden"> <li class="item-a"> <div class="card"></div> </li> </ul> </div> <script type="text/javascript" src="{% static 'blog/js/script.js' %}"></script> Settings INSTALLED_APPS = [ 'django.contrib.staticfiles', ] STATIC_URL = '/static/' Script $(document).ready(function() { $('#autoWidth').lightSlider({ autoWidth:true, loop:true, onSliderLoad: function() { $('#autoWidth').removeClass('cS-hidden'); } }); }); Documentation LightSlider -
How to use Get and Filter in set to get values related to a particular user
Im trying to get values of an order which a particular user made, I mean I have an e commerce app where a user can made purchases, I successfully got the order item to display when a user wants to make an order, but i want to get all the orders which are already purchased by that user to display in a different page (Order History), Im trying to use queryset for the Serializers but its just not work despite severally tweaks, and i have ready the docs but cant seem to get it right. Please help, Model: user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(eOrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(null=True) ordered = models.BooleanField(default=False) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted = models.BooleanField(default=False) transaction_id = models.CharField(max_length=200, null=True) qr_code = models.ImageField(upload_to='qrcode', blank=True) This is the serializer for the (Order History) class TicketSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() class Meta: model = Order fields = '__all__' def get_order_items(self, obj): return OrderItemSerializer().data View: class TicketDetailView(RetrieveAPIView): serializer_class = TicketSerializer permission_classes = (IsAuthenticated,) def get_object(self): try: # order = Order.objects.get(user=self.request.user).filter(ordered=True) # order = Order.objects.filter(order=True) # … -
Why me website is not deploying on heroku?
Im leraning Djnago and as my first project im doing a Todo application. I have done it successfully and now I wanna deploy it online with heroku. Its firs time im using heroku and I have stuck in a problem. When I deploy the branch it the heroku page it says "Your app was successfully deployed." and when I click the view it open another page when it says Application Error and also says "An error occurred in the application and your page could not be served." and tells me to run "heroku logs --tail" After I run the command it shows the error: 2021-02-22T20:01:06.239123+00:00 app[web.1]: ModuleNotFoundError: No module named 'todo-app' 2021-02-22T20:01:06.239250+00:00 app[web.1]: [2021-02-22 20:01:06 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-02-22T20:01:06.362082+00:00 app[web.1]: [2021-02-22 20:01:06 +0000] [4] [INFO] Shutting down: Master 2021-02-22T20:01:06.362177+00:00 app[web.1]: [2021-02-22 20:01:06 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-02-22T20:01:06.420234+00:00 heroku[web.1]: Process exited with status 3 2021-02-22T20:01:06.534432+00:00 heroku[web.1]: State changed from starting to crashed 2021-02-22T20:01:10.312560+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=todo-appmm.herokuapp.com request_id=ab514164-fe96-4d7c-9c8c-e443dd19c0d0 fwd="77.242.30.150" dyno= connect= service= status=503 bytes= protocol=https 2021-02-22T20:11:55.501461+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=todo-appmm.herokuapp.com request_id=390dbc04-4df0-439c-8373-edaf953cbe2e fwd="77.242.30.150" dyno= connect= service= status=503 bytes= protocol=https 2021-02-22T20:11:55.923684+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET … -
Adding an item to a chart in django - Attribute Error
I am working on my first django-project and I am trying to build an e-commerce website from scratch. I tried to write a logical flow for adding an item to my chart but somewhere I'm mistaken. It continuously raises an error that I do now know how to handle. In models.py I created the model for an item that will be added to the chart and it'll be displayed on the chart.html page. models.py class UserItem(models.Model): name = models.CharField(max_length=50, blank=True, null=True) price = models.FloatField(blank=True, null=True) img = models.ImageField(upload_to='gallery', blank=True, null=True) quantity = models.IntegerField(default=1) prod_id = models.ForeignKey(to=ComputerScienceProducts, on_delete=models.CASCADE, blank=True, null=True) def add_item_to_cart(self, prod_id): prod = ComputerScienceProducts.objects.get(pk=prod_id) try: existing_prod = UserItem.objects.get(prod) existing_prod.quantity += 1 existing_prod.save() except: new_prod = UserItem.objects.create(name = prod.name, price=prod.price, img=prod.img) new_prod.save() In views.py, the logic I tried to implement in coding lines is: If the user clicks the button "add to chart", will be sent through a GET method the pk of the product he wants to add on his or her chart. From that point, I look for the product that has that PK in the database. Then I check whether the product is already in the cart and if so, I just increase the quantity by 1, … -
Stuck on "Waiting for (domain)..." after submitting form in django application
I have a simple django application that has a 'contact' page where the user can submit a form directed to my gmail account. The form works fine when I run it on localhost on my computer, but when running on my linux server, my browser gets stuck on "Waiting for (domain name)..." after I click submit, and the page just sits there (no errors, just stuck on 'waiting') Since it works locally. I have a feeling it has something to do with my server (ubuntu running apache), but this is my first time managing a server and I'm lost. HTML form <div class="container"> <center> {% if message_name %} <h2>Message sent successfully</h2> <p>Thanks for reaching out, {{message_name}}!</p> {% else %} </center> <h2>Contact us</h2> <div class="col-lg-12"> <br> <form class="contact-form" role="form" method="post"> {% csrf_token %} <div class="form-group"> <label for="contact-name">Your Name</label> <input type="name" name="message-name" class="form-control" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars"> <div class="validate"></div> </div> <div class="form-group"> <label for="contact-email">Your Email</label> <input type="email" name="message-email" class="form-control" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email"> <div class="validate"></div> </div> <div class="form-group"> <label for="contact-subject">Subject</label> <input type="text" name="message-subject" class="form-control" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject"> <div class="validate"></div> </div> <div class="form-group"> <label for="contact-message">Your Message</label> <textarea … -
I'm unable to log into django app with other accounts except the superuser
I am new to Django. I have a project where I'm not able to log in with other accounts except the superuser account. Here are my models class School(models.Model): school = models.CharField(max_length=100, null=False, blank=False,default='school') class User(AbstractUser): schools = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False,default=1) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Teacher(models.Model): school = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False) name = models.CharField(max_length=30, blank=False, null=False) code = models.CharField(max_length=30, blank=False, null=False) class Student(models.Model): school = models.ForeignKey(School, on_delete=models.PROTECT, null=False, blank=False) first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) adm = models.CharField(max_length=30, blank=False, null=False) I am new to Django and self learning. May anybody out there help me, please. Where could the problem be?? -
Django Filter Forms: How Can I Use Buttons As Replacement For Multple Choice
I am filtering using ModelMultipleChoiceFilter but i don't like the way it looks so i want to use buttons instead of the default widget and i don't want to use checkboxes either. I have seen this done before so i just need to know how to actually do it. Is there a way to use buttons as multiple choice instead of the default widget where you have to press CTRL to select multple choices from the list? Is there a way to maybe create a custom widget or some work around? Here is the filters.py class PostFilter(django_filters.FilterSet): product = django_filters.ChoiceFilter(choices=PRODUCT_CHOICES) genres = django_filters.ModelMultipleChoiceFilter(queryset=Genres.objects.all()) keywords = django_filters.ModelMultipleChoiceFilter(queryset=Keywords.objects.all()) class Meta: model = Post fields = [ 'product', 'genres', 'keywords', ] views: def find_search(request): Posts = Post.objects.all() myFilter = PostFilter(request.GET, queryset=Posts) Posts = myFilter.qs -
Trying to add slug to end of get_absolute_url function in models (Django)
I have a function in my Post model, a get_absolute_url which is a reverse for 'post-detail', it has kwargs for primary key , how do i add another for slug; which is in my Profile model. At the moment I'm getting error : NoReverseMatch at /post/26/tested123/update/ Reverse for 'post-detail' with keyword arguments '{'pk': 26}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/$'] This error occurs when I click the update button on my update post page feed model feed/models.py class Post(models.Model): description = models.TextField(max_length=255) pic = models.ImageField(upload_to='path/to/img', blank=True) date_posted = models.DateTimeField(default=timezone.now) user_name = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.CharField(max_length=100, blank=True) def __str__(self): return self.description def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) profile model users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') slug = AutoSlugField(populate_from='user') bio = models.CharField(max_length=255, blank=True) friends = models.ManyToManyField('Profile', blank=True) def __str__(self): return str(self.user.username) def get_absolute_url(self): return "/users/{}".format(self.slug) views.py @login_required def post_detail(request, pk, slug): post = get_object_or_404(Post, pk=pk) user = request.user is_liked = Like.objects.filter(user=user, post=post) if request.method == 'POST': form = NewCommentForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.post = post data.username = user data.save() return redirect('post-detail', pk=pk, slug=slug) else: form = NewCommentForm() return render(request, 'feed/post_detail.html', {'post':post, 'is_liked':is_liked, 'form':form}) views.py class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['description', … -
Django Change_Password custom template
I was coding with Django around you know to make my coding skill better any way, i started with custom Registration forms for users, i had no problem with it, so i came around change password template, there is the default, but I want to extend it inside my base.html template, but it doesn't work, path : homepage\templates\registration\passwordmanagment\password_change_form.html code : {% extends 'registration/passbase.html' %} {% block content %} <h1>Password change</h1> <p>Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly.</p> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-success" type="submit" value="Change my password"> </form> {% endblock content %} base file path : homepage\templates\registration\passbase.html {% load static %} {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <title>registration </title> </head> <body> {% block content %} {% endblock content %} <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> </body> </html> -
docker containers on the same net (from compose) don't see each other
I have two docker containers: nginx_server and django_server (with UWSGI) and a posgres with postgresql. Now the thing is, My nginx setup seems to be a bit off, because if gives me a 502 Bad Gateway any time I curl 0.0.0.0:8000 (both on host and inside container). django_server is runs on UWSGI and is configured such as: uwsgi --http-socket 0.0.0.0:80 \ --master \ --module label_it.wsgi \ --static-map /static=/app/label_it/front/static \ I'am able to connect to it both outside and inside container and get a proper result. Inside django_server container I can ping and curl nginx_server with positive result and 502 Bad Gateway. curl django_server in nginx_server container outputs: <html lang="en"> <head> <title>Bad Request (400)</title> </head> <body> <h1>Bad Request (400)</h1><p></p> </body> </html> (I receive above output in django_server container when curl localhost:80 rather than curl 0.0.0.0:80 / curl 127.0.0.1:80) It seems to me, like nginx_server is not properly requesting data from uwsgi. nginx_server configuration: upstream django { server django_server:8000; } # configuration of the server server { # the port your site will be served on listen 0.0.0.0:8000; # the domain name it will serve for server_name label_it.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size … -
Resetting Password inside Django Save Function
I am currently using django rest password reset urls for my password reset needs and I have it attributed to a URL: url("^password-reset/", include("django_rest_passwordreset.urls", namespace="password_reset")), However, I would like to call this endpoint in a save method of a model using the email attributed to the user model. Is there any way to do something like this? -
During form validation, when authorization is in progress, if and else are triggered simultaneously
During form validation, when authorization is in progress, if and else are triggered simultaneously. With 50% of the case, success and errors will be added to the dictionary, and the user is actually authorized if the login and password fit. The first time I encountered this. class LoginView(View): def post(self, request, ans={}, *args, **kwargs): form = LoginForm(request.POST) if form.is_valid(): ans["success"] = reverse('news') email=form.cleaned_data.get('email_l') password = form.cleaned_data.get('password_l') user = authenticate(email=email, password=password) login(request,user) else: ans['errors'] = form.errors return JsonResponse(ans) my form: class LoginForm(forms.ModelForm): email_l=forms.EmailField(widget=forms.EmailInput(attrs={'placeholder':''}),label='Почта', ) password_l=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':''}),label='Пароль') class Meta: model=User fields=("email_l","password_l") def clean(self): cleaned_data = super(LoginForm,self).clean() email_l = cleaned_data.get('email_l') password_l = cleaned_data.get('password_l') user = authenticate(email=email_l, password=password_l) if not user: raise forms.ValidationError('this error') return cleaned_data -
UWSGI Django connect http uwsgi.ini
Someone can tell me why this line works for me: sudo uwsgi --chdir=/home/krzyzak21/venv/my_gless --module=my_gless.wsgi:application --env=DJANGO_SETTINGS_MODULE=my_gless.settings --master --http=127.0.0.1:8000 --home=/home/krzyzak21/venv/ but this: sudo uwsgi --ini my_gless/config/uwsgi.ini dont and add error: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f49a03debc0 (most recent call first): [uwsgi] projectname =my_gless base = /home/krzyzak21/venv/%(projectname) master = true virtualenv = /home/krzyzak21/venv/%(projectname) pythonpath = %(base) chdir = %(base) env = DJANGO_SETTINGS_MODULE=$(projectname).settings module = %(projectname).wsgi:application -
login user should access only topic which user has posted
User should get only his/her topics but user is getting all users topic in html. User can post topic and in post user can see list of topic. User should see only user topics but all user topic is being seen. What would be the procedure to get only user topic, for example: ram creates topic as laptop mobile tv shyam creates topic as furniture food while creating post ram should get only topic option as laptop,mobile,tv but he is getting all option including shyam topic also. Following are the codes class Topic(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) def __str__(self): return self.title class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name="alltopic") title = models.CharField(max_length=100) body = models.TextField() def __str__(self): return self.title def createPost(request): form = PostForm() if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect("postlist") context = {"form": form} return render(request, "createpost.html", context) and html <div class="container"> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" >submit</button> </form> </div> -
Why pytz.localize and datetime.replace return different results?
As documentation of pytz says: def localize(self, dt, is_dst=False): '''Convert naive time to local time''' if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') return dt.replace(tzinfo=self) So as the last line shows, localize and dt.replace are the same. Because the algorithm above, if we remove the if part, is return dt.replace(tzinfo=self) which just use datetime.replace. But we know that the output are different: time = datetime.now() tehran_tz = pytz.timezone('Asia/Tehran') print(tehran_tz.localize(time)) print(time.replace(tzinfo=tehran_tz)) Output: 2021-02-22 21:15:29.781400+03:30 2021-02-22 21:15:29.781400+03:26 It's not about which one is correct which is discussed here. But why they are different while their code are the same. -
What is the best way to ssh servers from django app?
I'm new to django and trying to build tool that need to perform task on linux servers. I gone through Fabric which is cool, is this the only way i can do ssh? When user submit request, the task/job should run background, what is the best way to achieve? Appreciate for your all inputs suggestions. -
How to write cache lock on two keys in Django
I want to create lock on two keys so that if any one key(eg key1 or key2) exists in cache then following code should not be executed... how can I achieve it? for eg- with cache_lock(key1 or key2, timeout = 70): line1 line2 .... should not be executed -
Django: How To Pass List Of Arguments Through URL
![enter image description hereI am trying to create a search page where buttons can be clicked which will filter the posts like in this page Splice Sounds (i think you need an account to view this so ill add screenshots). To do this i think i need to pass a list so that i can filter by that list but i can't find a way to do this. having a GET form for each genre (which is being created by a for loop) would allow me to filter by one genre at a time but i want to filter by multple genres at once so that won't work in the site that i linked to: they pass the genres/tags into the url so how could i do this in django? Also: i could make seperate url paths and link to those but then i would have to do this for every combination of genres/tags which would be too much so i can't do that. here is some relevant code: this is how i want to filter which is why i need to pass a list of args for arg in args: Posts = Posts.filter(genres=arg) -
How to make one view from one app be shown in all urls in Django?
I have created an app for the main template of my project (All other templates inherit from this one). The template includes header, footer and an aside in which i can add and delete posts from the admin panel. Now, when rendering all the templates everything (header, footer and the respective {% block content %}) is shown correctly but not the aside because i'm not passing any url to the view managing it. I'm trying to pass that view to every URL of my project so the aside is always shown. I just dont get the way of doing it. Just to clarify: Following the code i'm going to show now the aside is shown in localhost:8000 only. Not in localhost:8000/inicio nor any other url. Aside views.py from django.shortcuts import render from .models import asides def post_aside(request): aside_posts = asides.objects.all() return render(request, "main/main.html", {"aside_posts" : aside_posts}) urls.py of the app with the aside from django.urls import path from . import views urlpatterns = [ path('', views.post_aside, name='main'), ] urls.py of the project from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('inicio/', include('inicio.urls')), path('galeria/', include('galeria.urls')), … -
Matching Query Error while trying to make Case Insensitive Usernames in Django
I'm trying to Override the user model to make usernames case insensitive and allow semicolons. I haven't added the code for semicolons yet. I am getting a matching query error while trying to create a superuser. When I run python manage.py createsuperuser I get a matching query error Here is my code models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) class UserManager(BaseUserManager): def get_by_natural_key(self, username): return self.get(**{self.model.USERNAME_FIELD + '__iexact': username}) def create_user(self, username, password=None, is_active=True, is_staff=False, is_admin=False): if not username: raise ValueError("Users must have an username address") if not password: raise ValueError("Users must have a password") user_obj = self.model( username = self.get_by_natural_key(username) ) user_obj.set_password(password) # change user password user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, username, password=None): user = self.create_user( username, password=password, is_staff=True ) return user def create_superuser(self, username, password=None): user = self.create_user( username, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) #full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user non superuser admin = models.BooleanField(default=False) # superuser timestamp = models.DateTimeField(auto_now_add=True) # confirm = models.BooleanField(default=False) # confirmed_date = models.DateTimeField(default=False) USERNAME_FIELD = 'username' #username # USERNAME_FIELD and password … -
Deserialization Error: Problem installing fixture
I am having trouble loading in my initial json data. I am running the command python manage.py loaddata initial_data An example of some of my json: { "model": "assessment.jobs.models.List", "pk": 4, "fields": { "name": "Future Of Food", "description": "Redefining how we eat, feat. Infarm, Memphis Meats & Air Protein.", "image": "https://urltoimage.com" } }, { "model": "assessment.jobs.models.Job", "pk": 5, "fields": { "job_title": "Application Software Engineer", "company": "SpaceX", "location": "New York, NY", "min_salary": 40000, "max_salary": 65000, "apply_link": "https://boards.greenhouse.io/spacex/jobs/5027836002" } }, { "model": "assessment.jobs.models.List_For_Job", "pk": 6, "fields": { "list_name": "list example", "job": 5 } }, My models, which from the initial data is in the path assessment/jobs/models.py: class List(models.Model): name = models.CharField(max_length=200) description = models.TextField() image = models.URLField() class Job(models.Model): job_title = models.CharField(max_length=200) company = models.CharField(max_length=200) location = models.CharField(max_length=200) min_salary = models.IntegerField() max_salary = models.IntegerField() apply_link = models.URLField() class List_For_Job(models.Model): list_name = models.CharField(max_length=200) job = models.ForeignKey(Job, on_delete=models.CASCADE) I have a feeling the error is how I am calling the model in the json? I am really not sure though, this is my first django project. I tried making List, Job, and List_For_Job lowercase when I was calling the model and that did not work. Also in my installed apps it says "assessment.jobs" so … -
How to match a list with a dict and time related values
I got this in my views.py # Get the amount of kilo attached to products product_data = {} for product in ProductSpy.objects.all(): product_data[product.id] = {"product_id": product.product_id, "kilo": product.kilo} # Get quantity bought of each product total_qty_bought = self.order_item_model.objects.values("product").annotate(Sum("quantity")) So in my product_data dump I got this here: 6: {'product_id': 32, 'kilo': Decimal('25.00')}, and in my total_qty_bought dump I got this: {'product': 32, 'quantity__sum': Decimal('5')}, Now as the product_id match the product, I want it to return 125, as we got 5 times the quantity of 25 kilo. In my total_qty_bought dump you'd find id's not relevant, so if they dont match any in my product_data dump, I want them ignored. How can I achieve this smartest? print dump: product_data: {4: {'product_id': 30, 'kilo': Decimal('25.00')}, 5: {'product_id': 31, 'kilo': Decimal('25.00')}, 6: {'product_id': 32, 'kilo': Decimal('25.00')}, 7: {'product_id': 33, 'kilo': Decimal('25.00')}, 8: {'product_id': 37, 'kilo': Decimal('15.00')}, 9: {'product_id': 38, 'kilo': Decimal('15.00')}, 10: {'product_id': 39, 'kilo': Decimal('10.00')}, 11: {'product_id': 40, 'kilo': Decimal('10.00')}, 12: {'product_id': 41, 'kilo': Decimal('5.00')}, 13: {'product_id': 42, 'kilo': Decimal('2.50')}, 14: {'product_id': 43, 'kilo': Decimal('5.00')}, 15: {'product_id': 44, 'kilo': Decimal('2.50')}, 17: {'product_id': 50, 'kilo': Decimal('2.50')}, 18: {'product_id': 51, 'kilo': Decimal('5.00')}, 19: {'product_id': 52, 'kilo': Decimal('10.00')}, 20: {'product_id': 53, 'kilo': … -
UnboundLocalError at /product/7 local variable 'gotten_review' referenced before assignment
So I get UnboundLocalError at /product/7 local variable 'gotten_review' referenced before assignment When I visit the detail view page, I don't think I have referenced this 'gotten_review' before so i don't know why is this error happening views.py def detailview(request, id): book = get_object_or_404(Book, pk=id) if request.user.is_authenticated: oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) number = 0 for num in hehe: number += 1 fianlprice = 0 for item in hehe: fianlprice += item.book.price specific = Book.objects.get(pk=id) matching_books = Book.objects.filter(category=specific.category).exclude(pk=id)[:3] reviews = Paginator(ProductReview.objects.filter(book=id), 5) review_page = request.GET.get('reviews') review_objects = reviews.get_page(review_page) one_two_star = ProductReview.objects.filter(book=id, rating=1).count() + ProductReview.objects.filter(book=id, rating=2).count() three_star = ProductReview.objects.filter(book=id, rating=3).count() four_star = ProductReview.objects.filter(book=id, rating=4).count() five_star = ProductReview.objects.filter(book=id, rating=5).count() checking = True if ProductReview.objects.filter(book=id, user=request.user).exists(): checking = False if checking == False: gotten_review = ProductReview.objects.get(user=request.user) params = {'book':book, 'price':fianlprice, 'cart':oof, 'order':lmao, 'number':number, 'matching_books':matching_books, 'reviews':review_objects, 'one_two_star':one_two_star, 'three_star':three_star, 'four_star':four_star, 'five_star':five_star, 'gotten_review':gotten_review, 'checking':checking} return render(request, 'main/detail.html', params) else: specific = Book.objects.filter(pk=id) matching_books = Book.objects.filter(category=specific.category).exclude(pk=id)[:3] reviews = Paginator(ProductReview.objects.filter(book=id), 5) review_page = request.GET.get('reviews') review_objects = reviews.get_page(review_page) one_two_star = ProductReview.objects.filter(book=id, rating=1).count() + ProductReview.objects.filter(book=id, rating=2).count() three_star = ProductReview.objects.filter(book=id, rating=3).count() four_star = ProductReview.objects.filter(book=id, rating=4).count() five_star = ProductReview.objects.filter(book=id, rating=5).count() params = {'book':book, 'matching_books':matching_books, 'reviews':review_objects, 'one_two_star':one_two_star, 'three_star':three_star, 'four_star':four_star, 'five_star':five_star} return render(request, 'main/detail.html', params) -
How to modify django admin add new object page?
I need to change the default admin add page from Django. This page is located at: http://127.0.0.1:8000/admin/app/MODEL/add/ and I don't know how to overwrite that page. I would also want to modify the /change/int:pk page too, feel free to help me with both.