Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to restrict an API on a public webserver to a specific frontend?
My web application has public API endpoints. I have two frontends one for internal admin and the other for customers both using the same backend endpoints. The goal is to allow certain APIs to only be available to the internal admin frontend. I thought about using HTTP ORIGIN header which would contain the frontend url. Is that a good approach? -
Nested or multiple select_for_updates
I wish to acquire locks on more than one unrelated object using .select_for_update. Do I need to wrap each call with a transaction.atomic? I've read the sections in the Django documentation and postgres' Row Locking but it's unclear on the matter. from django.db import models class A(models.Model): data = models.TextField() class B(models.Model): data = models.TextField() This is a bit of a contrived example, but given the above models, can I do this? def update_records(pk_a, pk_b, value): with transaction.atomic(): a_object = A.objects.get(pk=pk_a).select_for_update() b_object = B.objects.get(pk=pk_b).select_for_update() # modify values, etc or do I need to do this? def update_records(pk_a, pk_b, value): with transaction.atomic(): a_object = A.objects.get(pk=pk_a).select_for_update() with transaction.atomic(): b_object = B.objects.get(pk=pk_b).select_for_update() -
Django: Dynamically generated form fields are not show in view
I have the following form in my forms.py: class ObjectForm(forms.Form): object_text = forms.CharField(max_length=1000) def __init__(self, *args, **kwargs): krs = kwargs.pop('krs', None) super(ObjectForm, self).__init__(*args,**kwargs) i=6 self.fields['mytry%s' %i] = forms.CharField(label="mytry%s" %i) if krs: for kr in krs: self.fields['text_%s' %kr.no] = forms.CharField(label="kr_text") Now, the field 'mytry6' above the for-loop is shown when I display the form in the html template. But the fields generated in the for-loop are not shown. When I log the content of the form, I see that the additional fields with 'text_1' etc. are included in the form. But somehow they are not shown?!? Can anybody help? Thanks -
django + gunicorn + uvicorn + nginx 504 gateway timeout after adding --preload
Everything works fine for me when I don't use preload option in gunicorn, but when I add --preload to gunicorn, nginx gets 504 gateway timeout. here is my /etc/systemctl/systemd/gunicorn.service: [Unit] Description=uvicorn daemon After=network.target [Service] Environment=DJANGO_SETTINGS_MODULE=MyProject.settings.production User=user1 Group=www-data WorkingDirectory=/home/user1/myproject ExecStart=/home/user1/myproject/venv/bin/gunicorn MyProject.asgi:application --preload -w 2 -k uvicorn.workers.UvicornWorker --log-file - [Install] WantedBy=multi-user.target -
Multiple field boolean filtering by value with Django
I have 3 fields in a dataset that I want to create querysets over the possible permutation values for those fields. These fields are based on a numerical rating scale, so the queries are based on whether a value is matched in the given field. I've already filtered the fields to ensure that the values in all three fields are at minimum a 7 (out of the possible integer values of 7, 8, 9 for those three fields). Now I want to find the following potential comparisons as querysets (!7 means the value can be 8 or 9): [7, 7, 7] [7, !7, 7] [7, 7, !7] [!7, 7, 7] [7, !7, !7] [!7, 7, !7] [!7, !7, 7] I was able to do this with pandas by creating comparison columns with boolean evaluation to check the following permutations, (i.e. column 1 = 7, column 2 != 7 (so either 8 or 9), column 3 != 7 (so either 8 or 9)). permutation_dict = { "all": (True, True, True), "one and three": (True, False, True), "one and two": (True, True, False), "two and three": (False, True, True), "one": (True, False, False), "two": (False, True, False), "three": (False, False, True), } … -
how to get id from object in POST request
Here I m making a POST request with the following data: { "ruleAssignmentDetails": { "id": 1, "ruleAssignment": { "id": 1, "empId": 1, "roleId": 1, "empName": "Emp01", "roleName": "CEO" }, "detailSrl": 12, "rule": 4, "validityType": "F", "startDate": "2021-06-14", "endDate": null, "frequency": { "id": 1, "frequencyName": "Test", "frequencyTpe": "Weekly" } }, "detailSrl": 12, "parameterName": "Param1", "valueType": "D", "overwriteValue": null, "targetDefination": { "id": 1, "targetName": "MIN SALES", "displayName": "MIN SALES" } } split the objects into respective models but when I m not getting the 'id' of targetDefination and ruleAssignmentDetails serializer.py class RuleAssignmentParamsSerializers(serializers.ModelSerializer): ruleAssignmentDetails = RuleAssignmentDetailsSerializers() targetDefination = TargetDefinationSerializers() class Meta: model = RuleAssignmentParams fields = ( 'id', 'ruleAssignmentDetails', 'detailSrl', 'parameterName', 'valueType', 'overwriteValue', 'targetDefination', ) def create(self,validated_data): ruleAssDetails = validated_data.pop('ruleAssignmentDetails') targetdef = validated_data.pop('targetDefination') serial = RuleAssignmentParams.objects.create(**validated_data) return serial views.py def getSimpleRules(request): simpleRules = RuleSimple.objects.all() simpleRulesSer = OnlySimpleRules(simpleRules,many=True) return JsonResponse(simpleRulesSer.data,safe=False) @api_view(['GET']) def getRuleAssignment(request,pk): if request.method == 'GET': print("get working") q=get_object_or_404(RuleAssignmentParams,pk=pk) f=RuleAssignmentParamsSerializers(q) return JsonResponse(f.data) @api_view(['POST']) def ruleAssignment(request): if request.method == 'POST': data = JSONParser().parse(request) validated_data = data serializer=RuleAssignmentParamsSerializers(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when I run this it shows me this error: IntegrityError at /api/rules/ruleassign (1048, "Column 'ruleAssignmentDetails_id' cannot be null") How do I get the id of ruleAssignmentDetails and targetDefination ? -
Django: How to check that an inline action has been executed?
I have three actions and it just so happens that I have to fix this code so that the application makes sure or at least warns the user (this is still being defined) that they have skipped a step. In my admin.py I have three inline actions: actions = [clean_data, rel_from_db, send_production] They just run actions related to a database in this manner: def send_production(modeladmin, request, queryset): for qs in queryset: qs.clean_data() How can I instead stop the execution (before the loop) to make sure the performed the two previous steps? Could I just save a variable in admin.py that keeps the state. I read the ValidationError indicated in this solution but I'm confused because I wanna validate inline actions (functions) and not exactly a form field. -
Django Error: NoReverseMatch at / ; looking at wrong urlpattern?
I am simply trying to open the web app to the home page, but at startup I am given the NoReverseMatch error message. The full message is the following: Reverse for 'wiki' with no arguments not found. 1 pattern(s) tried: ['wiki/(?P<title>[^/]+)/$']. In case it's relevant, I am using Django version 3.2.4. In urls.py for my project I have: urlpatterns = [ path('', include("encyclopedia.urls", namespace="encyclopedia")), path('admin/', admin.site.urls), ] In urls.py for my app I have: app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<title>/", views.entry, name="wiki"), .... (rest omitted for brevity) ] In views.py I have: def index(request): context = { "entries": ["item1", "item2", "item3"], "form": SearchForm(), } return render(request, "encyclopedia/index.html", context) In index.html, I have: {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li> <form action="{% url 'encyclopedia:wiki' %}", method="POST"> {% csrf_token %} <input type="text" value="{{ entry }}" name="link" hidden> <input type="submit" class="link-btn" value="{{ entry }}" style="border: 0; background-color: white"> </form> </li> {% endfor %} </ul> {% endblock %} As the error message indicates, it appears to be looking at the url pattern named wiki, and then subsequently failing to find the arguments passed to it. However, I am not trying to check that … -
Django View Aggregate Not Doing Calculation
I'm trying to do a little division math in my view for an HTML display. For some reason I'm not getting a calculation with the below view. I'm new to all this so any suggestions would be appreciated. View from django.db.models.functions import Cast from django.db.models import FloatField, F class PatientListView(LoginRequiredMixin, ListView, Cast, FloatField): model = Patient template_name = 'patient_list.html' ind_treat_length = Patient.objects.annotate(treat_len=( F('cycle_length_days') / F('treatments_per_cycle'))) def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( author=self.request.user ) The ind_treat_length annotation is what I have come up with for this. My HTML template request is {{ patient.treat_len }} Am I missing something here? Thanks -
Django - how to filter on a comma seperated string
At my Django models.py I have a "genre" field (models.TextField). This fields contains sometimes only one string and sometimes a comma separated list of string like this: Comedy, Action, Drama Or Action, Fantasy or as mentioned only one string e.g. only Comedy Now at my view I want to do something like this: queryset_comedy = Movies.objects.get_queryset().filter(genre__in=["Comedy", "Family"]) queryset_action = Movies.objects.get_queryset().filter(genre__in=["Action", "Adventure"]) queryset_drama = Movies.objects.get_queryset().filter(genre__in=["Drama", "Thriller"]) I mentioned that my Query only matches field values which are standalone according to the genre field. For example Movie element one has the following genre string: Comedy, Action and Movie element Two only has "Comedy" as single string. Than the query outputs only Movie objects which have the string "Comedy" standalone and not Comedy, Action. How can I make a Movie element match when multiple sorting strings are given for genre? -
Django: How to properly bulk_update_or_create() in a for loop
I am currently creating some django objects (or at least that is the idea) while executing a for loop where I am generating some data. The idea is to create multiple objects or update some of them if already exist. def get_friends(self): for friend_option in self.get_friend_options: friend_permalink = friend_option.get_attribute('href') friend_name = get_name() users.append(user) friend_requests.append(Friend(account=self.current_account, friend_permalink=friend_permalink, friend_name=friend_name, is_friend=False, request_type=Friend.REQUEST_TYPE_RECEIVED, received_request_date=datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') )) Friend.objects.bulk_create(friend_requests) return friend_requests -
Django API for Google Login
I am going to implement Google Login using React+Django. I am using the package: django-allauth for social login(Google via API). When you enter access_token in GoogleLogin view, a user is registered in the database and view returns key. The same key for different access_tokens. My question is, how can I use this key to extract data from database about this user. Can anyone help, please? -
Not able to fetch product id in ecommerce application -django
views.py ''' from django.shortcuts import render,redirect from .models import Cart from new_app.models import Product def cart_home(request): cart_obj,new_obj=Cart.objects.new_or_get(request) products=Cart.objects.all() return render(request,'carts/home.html',{}) def cart_update(request): print(request.POST) product_id=1 print('id below') print(product_id) // not able to get the value of product id in console product_obj=Product.objects.get(id=product_id) cart_obj,new_obj=Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) return redirect('home') ''' models.py(cart) ''' from django.db import models from django.conf import settings from new_app.models import Product from django.db.models.signals import pre_save,post_save,m2m_changed User=settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self,request): cart_id=request.session.get("cart_id",None) # qs=self.get_queryset().filter(id=cart_id) qs=self.get_queryset().only('products') print(qs) if qs.count()==1: new_obj=False cart_obj=qs.first() print('cart obj below') print(cart_obj) if request.user.is_authenticated and cart_obj.user is None: cart_obj.user=request.user cart_obj.save() else: cart_obj=Cart.objects.new_cart(user=request.user) new_obj=True request.session['cart_id']=cart_obj.id return cart_obj,new_obj def new_cart(self,user=None): user_obj=None if user is not None: if user.is_authenticated: user_obj=user return self.model.objects.create(user=user_obj) class Cart(models.Model): user=models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE) products=models.ManyToManyField(Product,blank=True) subtotal=models.DecimalField(default=0.00,max_digits=100,decimal_places=2) total=models.DecimalField(default=0.00,max_digits=100,decimal_places=2) timestamp=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) objects=CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender,instance,action,*args,**kwargs): print(action) if action=='post_add' or action=='post_remove' or action=='clear': products=instance.products.all() total=0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal=total instance.save() m2m_changed.connect(m2m_changed_cart_receiver,sender=Cart.products.through) def pre_save_cart_receiver(sender,instance,*args,**kwargs): if instance.subtotal>0: instance.total=instance.subtotal + 10 else: instance.total=0.00 pre_save.connect(pre_save_cart_receiver,sender=Cart) ''' update_cart.html ''' <form method='POST' action='{% url 'update' %}' class="form ">{% csrf_token %} <input type="hidden" name='product_id' value= "{{ product_id }}"> {% if product in cart.products.all %} <button type="submit" class="btn btn-link">remove</button> {% else %} <button type="submit" class="btn btn-success">add to … -
Select chained in admin
Suppose I have the following models (in summary): class Control(models.Model: name = models.CharField() code = models.CharField(unique=True) type = models.CharField() subtype = models.CharField() class List(models.Model): type = models.CharField() subtype = models.CharField() And in my database, I have the list table populated like this: type | subtype -------------------------------- Information | Paper Information | Digital Information | Software Personal | System Processes | - How can I do, that from the admin site, when I add a new Control, the subtype is dependent on what I have chosen in type. For example, if in type I choose Information, that in Subtype you can only choose between Paper, Digital and Software. I know that from a URL that I create I can use AJAX, but I don't know how I could make it work like this from admin. I would be very grateful if someone can solve this question for me, because I have read things but I can not find it. -
Url always redirects to login on POST request
Whenever I try to make a POST request, the url automatically redirects to the login resulting in BAD_REQUEST This is my code for login: class LoginView(View): def get(self, *args, **kwargs): form = LoginForm() context = { 'form':form } return render(self.request, 'core/login.html', context) def post(self, *args, **kwargs): form = LoginForm(self.request.POST or None) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(self.request, email=email, password=password) if user is None: messages.add_message(self.request, messages.ERROR, 'Enter valid email or password') return redirect('login') login(self.request, user=user) return redirect('home') return redirect('login') This is my post function for api: class NoteCreateView(LoginRequiredMixin, APIView): def post(self, *args, **kwargs): print(self.request.user) data = (self.request.data) data['id'] = self.request.user.id print(data) serializer = NoteSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.data, status=HTTP_400_BAD_REQUEST) And this is the POST request made from frontend e.preventDefault() const note = document.getElementById('add-note').value let date = new Date() const data = { 'note':note, 'date_created':date } let url = 'http://localhost:8000/api/notes/create/' fetch(url, { method:'POST', headers:{ 'content-type':'application/json', 'X-CSRFToken':csrftoken }, body:JSON.stringify(data) }) .then(res => { getAllNotes() document.getElementById('form').reset() }) }) The url that it always redirects on making POST request /login/?next=/api/notes/create/ -
how to allow users to rate a product only once,
a Reviews model linked to Users and Product, nothing special, users can vote as much as they want which is working, but i'm stuck restricting the rating to just once the view so far: class ReviewCreateView(CreateView): model = Review form_class = ReviewForm template_name = "form.html" success_url = reverse_lazy('product_list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) model class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True,related_name='reviews') user = models.ForeignKey(User, on_delete=models.PROTECT, null=True,related_name='reviewers') rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) the other models wouldn't help that muc ,Product just describe a product ,and default (regular) User model the form is ModelForm based on the Review Model itself any suggestion is welcome, even if i have to redo the model, thank you very much -
Django Custom User Creation Form - Duplicate Entry
Creating a custom page for creating new users. The page edits and deletes users without a problem. When I create a user, I receive django.db.utils.IntegrityError: (1062, "Duplicate entry 'johndoe@gmail.com' for key 'accounts_user.email'"). I know that my code is attempting to save the entry twice. Following my traceback, I think it has something to do with the save function within the form conflicting the form.save() in the view. Here is all the code. I've exhausted my (limited) ideas. views.py @admin_only def index(request): user_accounts = User.objects.all() print(user_accounts) context = {'accounts': user_accounts} return render(request, 'accounts/user_accounts.html', context) @admin_only def create_account(response): data = dict() form = CreateAccountForm() if response.method == 'POST': form = CreateAccountForm(response.POST) if form.is_valid(): form.save() data['form_is_valid'] = True user_accounts = User.objects.all().order_by('id') data['accounts_list'] = render_to_string('accounts/account_list.html', {'accounts': user_accounts}) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string('accounts/create_account.html', context, request=response) return JsonResponse(data) forms.py class UserAdminCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = User fields = ( 'email', 'first_name', 'last_name', ) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, … -
after pressing verification link ... nothing happens in Django .. user still unverified
Views.py(name of app: userprofileinfo) from django.shortcuts import render from userprofileinfo.forms import UserForm from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_exempt,csrf_protect from django.views import View from django.contrib import messages from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.template.loader import render_to_string from .utils import account_activation_token from django.urls import reverse from django.contrib import auth @login_required def special(request): return HttpResponseRedirect("You are logged in, Nice!") @login_required def userlogout(request): logout(request) return HttpResponseRedirect(reverse('careforallapp:base')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False user.save() email = UserForm('email') current_site = get_current_site(request) email_body = { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } link = reverse('userprofileinfo:activate', kwargs={ 'uidb64': email_body['uid'], 'token': email_body['token']}) email_subject = 'Activate your account' activate_url = 'http://'+current_site.domain+link send_mail( email_subject, 'Hi '+user.username + ', Please the link below to activate your account \n'+activate_url, 'settings.EMAIL_HOST', [user.email], fail_silently=False ) return HttpResponseRedirect(reverse('careforallapp:base')) else: print(user_form.errors) else: user_form = UserForm() return render(request,'userprofileinfo/registration.html', {'user_form':user_form, 'registered':registered}) class VerificationView(View): def get(self, request, uidb64, token): try: id = force_text(urlsafe_base64_decode(uidb64)) user … -
Django app on Azure getting images from static files but not Bootstrap, Jquery or CSS files
Got a Django app deployed on Azure with this structure: wwwroot |---Myproject |---manage.py |---oryx-manifest.toml |---hostingstart.html |---static //Same static folder and same files from myapp ├── myapp │ ├── migrations │ ├── __pycache__ │ ├── static │ │ │---bootstrap-3.3.7-dist │ │ │ │--css │ │ │ │ │--bootstrap.min.css │ │ │ │ js │ │ │ │ │--bootstrap.min.js │ │ │---Datatables │ │ │ │--jQuery-3.3.1 │ │ │ │ │--jquery-3.3.1.js │ │ │ │ │datatables.js │ │ │ │ │datatables.css | | |---Images | | | |--myimage.png | | | |--myimage2.png │ └── templates Thing is, when I call statics on my template this way: <script src="{% static 'Datatables/jQuery-3.3.1/jquery-3.3.1.js' %}"></script> <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}"> <script type="text/javascript" charset="utf8" src="{% static 'Datatables/datatables.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'Datatables/datatables.css' %}"> <img src="{% static 'Images/myimage.png' %}" align="center"/><br> Images render perfectly, but CDN datatable and css styles not, and browser console throw me this errors: bootstrap.min.js:6 Uncaught Error: Bootstrap's JavaScript requires jQuery at bootstrap.min.js:6 And : myappwapp.azurewebsites.net/:1 Refused to apply style from 'https://myapp.azurewebsites.net/static/Datatables/datatables.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Makes no sense, order of calling … -
matching query does not exist. DoesNotExist at /blog/postComment
I am trying to add the feature of commenting and replying to it in my blog. But it is constantly throwing me the error of "BlogComment matching query does not exist." def postComment(request): if request.method == "POST": comment = request.POST.get('comment') user = request.user postSno = request.POST.get('postSno') post = Post.objects.get(sno=postSno) parentSno = request.POST.get('parentSno') if parentSno == "": comment = BlogComment(comment=comment, user=user, post=post) comment.save() messages.success(request, "Your comment has been posted successfully") else: parent = BlogComment.objects.get(sno=parentSno) comment = BlogComment(comment=comment, user=user, post=post, parent=parent) comment.save() messages.success(request, "Your reply has been posted successfully") -
Django template - how to show the value of a list at specified index
I have list - list_name[] and list_age[] list1[] contains the name of persons, and list_age[] contains age of that persons from list_name[] I have to write in template like this: 1st div should contain name=list_name[0] and age=list_age[0] 2nd div should contain name=list_name[1] and age=list_age[1] and so on -
Array to string with Django and MySQL
I need to design SQL query in html on Django I have an array in my table like : list = ['aa', 'bb', 'cc'] When I call this array in my page : <p>{{ list }}</p> I have : ['aa', 'bb', 'cc'] What do I do if I want : a b c I tried with .split(',') but I've already '[]' I tried with for item in list but I've : [ a a , b b , c c , ] Could you help me please ? -
Implementing "Last Viewed" functionality in Django
Am still a newbie trying to to implement "Last Viewed" functionality for my web app. I want this function to return the 10 latest objects a user viewed. And this should be user specific. Problem is that I don't know how to go about it. Any help will be appreciated. Below is my model.py code class Link(Stamping): name = models.CharField(max_length=256, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) url = models.CharField(max_length=256, default=None) type = models.CharField(choices=Link_Type, max_length=256, default=None) receivables = models.PositiveIntegerField(default=None) #How the user wants to distribute the watched_max on each link object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", related_name="child_links", null=True, blank=True, on_delete=models.CASCADE, default=None) watched = models.ForeignKey(Watched, null=True, blank=True, on_delete=models.CASCADE, default=None) watched_num = models.PositiveIntegerField(default=None, null=True, blank=True) watched_max = models.PositiveIntegerField(default=None, null=True, blank=True) ... ... -
matplotlib python list comprehensive?
I want to do a simple chart to show the total of all appointments profit per day. the result shows something like that which is definitely not right. I know that the issue is in my views.py list comprehensive but not sure how to fix it.. any help is appreciated models.py class Service(models.Model): service_name = models.CharField(max_length=50) service_price = models.DecimalField(max_digits=8, decimal_places=2) physician = models.ForeignKey('Physician', on_delete=models.CASCADE) def __str__(self): return self.service_name class Appointment(models.Model): appointment_date = models.DateField(null=True) appointment_time = models.TimeField(null=True) patient = models.ForeignKey('Patient', on_delete=models.CASCADE) reseptionist = models.ForeignKey('Reseptionist', on_delete=models.SET_NULL, blank=True, null=True) service = models.ForeignKey('Service', on_delete=models.CASCADE) physician = models.ForeignKey('Physician', on_delete=models.CASCADE) plots.py import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import base64 from io import BytesIO def get_graph(): buffer = BytesIO() plt.savefig(buffer, format="png") buffer.seek(0) img = buffer.getvalue() g = base64.b64encode(img) g = g.decode("utf-8") buffer.close() return g # create a plot function for different matplotlib plots def line_plot(x, y): plt.figure(figsize=(4,4)) # you can set size plt.plot(x,y) return get_graph() views.py from .plots import line_plot def index(request): revenue = [x.service.service_price for x in prices] month = [x.appointment_date for x in prices ] c = pie_plot(revenue,month) context = {'chart': c } return render(request, 'index.html', context) -
How to create pages / URLs combining Product Category and Attribute Values? [Django]
So, I have create a Django app with product categories (URLs: domain.com/vk/[category-name]). The product categories display all the products assign to that category. Now, products also have attribute values, which have attributes (keys) as foreign keys. For example, "Grey" is an attribute value where "Color" is the key. How do I create pages that combine the categories and attributes in the categories? For example, I want an URLs like this: domain.com/vk/[category-name]/[grey]/[nike]. Or in generalized: domain.com/vk/[category-name]/[color]/[brand]. The attributes must be hierarichal, meaning that if two attributes are selected at once, they have a set order (for example: color/brand and never brand/color). Here's some code pieces (redundant code left out): # models.py class Product(models.Model): title = models.CharField(max_length=255) class ProductAttributes(models.Model): name = models.CharField(max_length=255) class ProductAttributesValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(ProductAttributes, on_delete=models.RESTRICT) # views.py class ProductCategoryListView(ListView): template_name = "products/product_categories.html" # Default fetch template location: <blog>/<modelname>_list.html #queryset = Product.objects.filter(categories_id = ) # e.g. id=1 def get_queryset(self): self.category = get_object_or_404(ProductCategory, slug=self.kwargs["slug"]) #id=self.kwargs["id"] filtered_products = Product.objects.filter(categories=self.category) # categories_id=self.category.id #for return filtered_products def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Get Attributes of all products in the product category products = Product.objects.filter( categories=self.category, productattributesvalue__attribute__isnull=False ).values( 'title', 'productattributesvalue__attribute__name', …