Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you immediately redirect to another view once a view is rendered in Django?
I have a view like below. class ConfirmationPageView(generic.TemplateView): template_name = "confirmation.html" What I want is to immediately move onto the below view once the ConfirmationPageView is loaded (which means its templates were loaded too). class SecondPageView(generic.TemplateView): template_name = "second.html" I don't care if the user can't see the ConfirmationPageView in this very short transition. I just need this confirmation page to show up breifly so that a third party analytics application can track whether a user visited this confirmation page. Thank you, and please leave any questions in the comments. -
Django free and pro version in one project [closed]
How do I go about having 2 versions of django projects, one is free the other is paid? I don't know how to restrict some users from the pro version. I also want to include speech to text in the app -
How to optimize a batch query to make it faster
When changing the status of a document, I would like to put all the products in the document into stock. This involves changing several fields. At low amount of product instances, the query works quickly >50ms. However, some documents have products in quantities of, for example, 3000. Such a query takes more than a second. I know that there will be cases with much higher number of instances. I would like the query to be faster. A simple loop takes ~1sec. class PZ_U_Serializer(serializers.ModelSerializer): class Meta: model = PZ fields = '__all__' def update(self, instance, validated_data): items = instance.pzitem_set.all() bulk_update_list = [] for item in items: item.quantity = 100 item.quantity_available_for_sale = 100 item.price = 100 item.available_for_sale = True item.save() return super().update(instance, validated_data) Batch_update takes about 400ms per field. In this case 1600ms (which is slower than a loop). class PZ_U_Serializer(serializers.ModelSerializer): class Meta: model = PZ fields = '__all__' def update(self, instance, validated_data): items = instance.pzitem_set.all() bulk_update_list = [] for item in items: item.quantity = 100 item.quantity_available_for_sale = 100 item.price = 100 item.available_for_sale = True bulk_update_list.append(item) items.bulk_update(bulk_update_list, ['quantity', 'price', 'quantity_available_for_sale', 'available_for_sale'], batch_size=1000) return super().update(instance, validated_data) In post-gre console I see at (3000 objects) about 11,000 read hits. I tried adding transaction.atomic before … -
Why user.is_authenticated not working? django, LoginRequiredMixin
I'm logged in. why display NOT LOGIN! in html? VIEWS from django.contrib.auth.mixins import LoginRequiredMixin class UserHomeView(LoginRequiredMixin, ListView): model = User template_name = 'users/users_index.html' paginate_by = 10 context_object_name = 'user' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) return context HTML {% if user.is_authenticated %} LOGIN! {% else %} NOT LOGIN! {% endif %} setting.py LOGIN_URL = '/users/login/' -
Editing Profile not updating
I am editing profile using Django framework. The problem lies where I cannot save or update the data inputted by the user and it shoes the error list. If I make it as not required, it shows blank in the system. How can I only save the ntry which user update and remain all other entry unchanged? Thank you Error: <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>email<ul class="errorlist"><li>This field is required.</li></ul></li><li>password<ul class="errorlist"><li>This field is required.</li></ul></li><li>confirm_password<ul class="errorlist"><li>This field is required.</li></ul></li><li>password_readonly<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Edit User Profile def sa_profile_edit(request): if request.user.is_authenticated: form =UserFormAdmin(instance=request.user) form_profile = MemberForm(instance=request.user.usermember) context = {'form':form, 'form_profile': form_profile} if request.method == 'POST': form =UserFormAdmin(request.POST,instance=request.user) form_profile = MemberForm(request.POST, request.FILES, instance=request.user.usermember) if form.is_valid() and form_profile.is_valid(): form.save() form_profile.save() messages.success(request,'Profile Successfully Updated') return redirect('sa_profile') else: print(form.errors) form =UserFormAdmin(instance=request.user) form_profile = MemberForm(instance=request.user.usermember) user_data = request.user context = {'form':form,'user_data':user_data, 'form_profile': form_profile} return render(request, 'pages/sa_editProfile.html', context) return render(request, 'pages/sa_editProfile.html', context) If role is super -- only super can view this def check_role_super(user): if user.role == 3: return True else: raise PermissionDenied Model class User(AbstractBaseUser): MEMBER = 1 ADMIN = 2 SUPERADMIN = 3 ROLE_CHOICE = ( (MEMBER, 'Member'), (ADMIN, 'Admin'), (SUPERADMIN, 'Super Admin') ) ACTIVE = 1 DELETED = 2 DEACTIVATED = 3 STATUS = ( … -
Django AuthenticationForm Error messages not showing
My question is when I give the wrong email or password, No error message is Shown, but why ?? and how can I fix that? This is my signin View function def signin(request): form = AuthenticationForm(request=request, data=request.POST) if form.is_valid() == True: user = authenticate(email=form.cleaned_data['username'], password=form.cleaned_data['password']) if user is not None: login(request, user) return HttpResponse(f'{request.user}') else: context = {'form': form} return render(request, 'signin.html', context) This is my Html <form action="{% url 'signin' %}" method="post"> {% csrf_token %} {% for field in form %} {{ field.errors }} {{ field }} <br> {% endfor %} <button type="submit">Signin</button> </form> -
I don't know why this class is not adding through javascript
I am trying to add a javascript class show with dropdown-content, but it is not adding there infact while console logs are working perfectly fine upto the last scope of the javascript script tag. Can anyone help me out from this? The text with the id is basically coming from django database which is unique. <div class="eps_dots more_dropdown dropdown"> <a href="#" onclick="get()" id="{{course.course_id}}" class=""><i class="uil uil-ellipsis-v"></i></a> <div class="dropdown-content "> <span><i class="uil uil-heart"></i>Save</span> <span><i class="uil uil-ban"></i>Not Interested</span> <span><i class="uil uil-windsock"></i>Report</span> </div> </div> <script> function get() { const focused = document.activeElement.getAttribute("id"); console.log(focused); menu(focused); } function menu(focused) { const path = '#' + focused + ' .dropdown-content'; console.log(path); $(path).toggleClass("show"); } </script> .eps_dots .show{ display: block !important; } -
How to store and work on traffic map data efficiently
I have been to work on a project which deals with traffic map data from Here API and I wanted to know what is the best way of storing data that is fetched from API. The performance issue can be resolved on frontend if the data is stored either in Relational or Non-Relational Database. Traffic data is in json and I have been dumping all data at frontend to work on it. I am looking for the efficient way and guidance to build a structured web application. The Backend is in Django-Python and the json-response are used for data. There is a need for ML and AI in project. LeafletJs is used for frontend maps. In short, what should be the suitable formation of database and architectural design of backend? -
check if passed context is Empty in Template
what I'm trying to achieve here is if context is empty or if STUDENT variable is empty, instead of returning all students. it should return none and in template it shows No results found. currently when nothing is stored in q my template render all the students. in views. def student_home(request): q = request.GET.get('q') if request.GET.get('q') != None else "" students = Student.objects.filter(Q(first_name__icontains=q) | Q(last_name__icontains = q) | Q(grade__icontains=q)) context = {'students': students} return render(request, 'StudentManager/home.html', context) search-bar in NAVBAR. <form class="d-flex" role="search" action='{% url 'student_home' %}'> <input class="form-control me-2" type="search" name='q' placeholder="Search Student" aria-label="Search"> <button type="submit" class="btn" style="background: #fff2df;">Search</button> </form> -
What would be the best approch to display a commenting form in the ListView for each blog post?
I currently have fully functional commenting form in my blog post view that I want to display in the ListView. Sort of like linkedin has under every list item, if you have noticed, i think facebook has the same thing. Is there a shortcut to achieve this? -
Not null constraint failed django with clean function
I am getting the error you see in the title. my purpose if banner_button_activate is true then banner_button_title and banner_button_url must be filled. But if it is false it doesn't matter if it is full or not. I did number 1, but when it comes to number 2, I get the error in the title. example NOT NULL constraint failed: appearance_banner.banner_button_url models.py class banner(models.Model): banner_name = models.CharField(max_length=200,primary_key=True) banner_image = models.ImageField(("Banner resmi"), upload_to="media/images/site/banner",help_text="1770x550 boyutunda resim önerilmektedir.") banner_title = models.CharField(max_length=100,null=True,blank=True) banner_title_activate = models.BooleanField(default=True) banner_description = models.TextField(null=True,blank=True) banner_description_activate = models.BooleanField(default=True) banner_button_title = models.CharField(max_length=50,null=True,blank=True) banner_button_url = models.SlugField(null=True,blank=True) banner_button_activate = models.BooleanField(default=True) banner_button2_title = models.CharField(max_length=50,null=True,blank=True) banner_button2_url = models.SlugField(null=True,blank=True) banner_button2_activate = models.BooleanField(default=True) banner_order = models.IntegerField(editable=True,default=1,blank=False,null=False,verbose_name="Sıra") banner_status = models.CharField(max_length=100,choices=STATUS,verbose_name="Banner Statüsü") def __str__(self): return self.banner_title def delete(self, *args, **kwargs): self.banner_image.delete() super(banner, self).delete(*args, **kwargs) def clean(self): # if (self.banner_title_activate): # if not (self.banner_title): # raise ValidationError({"banner_title":"Eğer bu bölüm aktifse buton title dolu olmalı.",}) if not (self.banner_button_title and self.banner_button_url and self.banner_button_activate): print("selam") print(self.banner_button_url) if None == self.banner_button_title and None == self.banner_button_url and False != self.banner_button_activate: print("selam 3") raise ValidationError({"banner_button_url":"Eğera bu bölüm aktifse buton url dolu olmalı.","banner_button_title":"Eğer bu bölüm aktifse button title dolu olmalı."}) elif (None == self.banner_button_url and True == self.banner_button_activate): print("selam 2") raise ValidationError({"banner_button_url":"Eğer bu bölüm aktifse button url dolu … -
django - No User matches the given query. Page Not found 404: User post list view breaks post detail view
I'm fairly new to django and trying to build a message board app. Everything's been running smoothly up until I tried to add functionality to display a list of posts by author. I got it working but then my post detail view started throwing a 'No User matches the given query. Page Not found 404' error and I can't seem to figure out why. Can anyone help? views.py class UserPostList(generic.ListView): model = Post # queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'user_posts.html' paginate_by = 6 def get_queryset(self): """ Method to return posts restricted to 'published' status AND to authorship by the user whose username is the parameter in the url. """ user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter( status=1, author=user ).order_by('-created_on') class FullPost(View): def get(self, request, slug, *args, **kwargs): """ Method to get post object. """ queryset = Post.objects.filter(status=1) post = get_object_or_404(queryset, slug=slug) comments = post.comments.order_by('created_on') liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True return render( request, "full_post.html", { "post": post, "comments": comments, "liked": liked }, ) # I'll be adding a comment form in here too urls.py urlpatterns = [ ... path('<slug:slug>/', views.FullPost.as_view(), name='boards_post'), ... path('<str:username>/', views.UserPostList.as_view(), name='user_posts'), ... ] Error message (When trying to view a single post (previously working) after … -
Django exception: decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
I have strange behavor in code. My model is: class Item(models.Model): .... price = models.DecimalField(max_digits=5, decimal_places=2, help_text="Цена товара", verbose_name="Цена") # price = models.IntegerField(help_text="Цена товара", verbose_name="Цена") When I try filter object: class ProductBuyView(APIView): def get(self, request, item_uuid: str, format=None): product = Item.objects.all().filter(uuid__exact=uuid.UUID(item_uuid))[0] ... I get an exception File "/home/lev/python_projects/taste_case_stripe/stripe_app/views.py", line 14, in get product = Item.objects.all().filter(uuid__exact=uuid.UUID(item_uuid))[0] File "/home/lev/python_projects/taste_case_stripe/venv/lib/python3.10/site-packages/django/db/models/query.py", line 445, in __getitem__ qs._fetch_all() File "/home/lev/python_projects/taste_case_stripe/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/lev/python_projects/taste_case_stripe/venv/lib/python3.10/site-packages/django/db/models/query.py", line 117, in __iter__ for row in compiler.results_iter(results): File "/home/lev/python_projects/taste_case_stripe/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1333, in apply_converters value = converter(value, expression, connection) File "/home/lev/python_projects/taste_case_stripe/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/operations.py", line 344, in converter return create_decimal(value).quantize( decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] ...decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] but when I change type field to Int class Item(models.Model): .... price = models.IntegerField(help_text="Цена товара", verbose_name="Цена") everthing is OK. As I guess the problem is decimal field. But what is wrong with it... -
Django add file and select automatic employe id
I would like to add documents to an employee's profile in a form but I would like the form to automatically select the employe id (Matricule), anyone have the solution? models.py class Employe(models.Model): Matricule = models.CharField(max_length=10, null=False) Prenom = models.CharField(max_length=40, null=True) Nom = models.CharField(max_length=40, null=True) Tel = models.CharField(max_length=20, null=True) Adresse = models.CharField(max_length=100, null=True) Courriel = models.EmailField(max_length = 254) class Document(models.Model): employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL) Description = models.CharField(max_length=100, null=True) Fichier = models.FileField(upload_to='documents/') views.py def createDocument(request, id): employe = Employe.objects.only('Matricule') forms = documentForm(instance=employe) if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/employe') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) Button Form -
How to make subsequent request to SAP Business One Service Layer from Django
I want to use Django to make requests to SAP Business One Service Layer. SAP B1 Service Layer requires initial login to establish a session. I am able to authenticate and get a correct response with a returned session ID from the Service Layer. How can I save a session from another server (in this case the Service layer) to make additional requests? Below is code of the initial SAP post request to the Login endpoint. sap_url = "https://sap_url.com:50000/b1s/v2/Login" headers = { "authkey": "XXXXXXXXXXXXXXXXXXXX", "Accept": "*/*", "Content-Type": "text/plain", } data = { "CompanyDB": "XXXXXXXX", "UserName": "XXXXXXXX", "Password": "XXXXXXX" } response = requests.post(sap_url, headers=headers, json=data) print("JSON Response ", response.json()) return HttpResponse(response.json(), content_type='application/json') When I make additional request to the Service Layer I get an error from the JSON Response. Any insight or suggestions is much appreciated. Thank you. JSON Response {'error': {'code': '301', 'message': 'Invalid session or session already timeout.'}} -
In React + Django app, JS renders properly when TS doesn't
I know JS and React, but have zero experience with TS. I'm following a tutorial on YT, but figured I'd use TS to learn it, instead of JS. And so after some setting up, I figured I'm ready to continue with the tutorial. However... This works with JS: index.html (Django template): [irrelevant html setup] <body> <div id="main"> <div id="app"></div> </div> <script src="{% static "frontend/main.js" %}"></script> </body> App.js: import React from "react"; import { render } from "react-dom"; const App = () => { return <h1>Testing React code</h1>; }; export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); index.js: import App from "./components/App"; // that's it. The import is all there is in index.js This is later compiled by babel-loader to main.js, which I'll not paste here, since it unreadable anyway. However, it does render the text from App.js. When I have the analogical setup with TS, it doesn't work for some reason. App.tsx: import React, { FC } from "react"; import { render } from "react-dom"; const App: FC = () => { return <h1>Testing React code</h1>; }; export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); index.ts is the same as index.js, html file also remains unchanged. … -
How to deploy Django with docker on apache2 with a domain and server name
I have a Django application that I need to deploy on a VPS with Apache2 .. the application is dockerized but it is not working as expected.. here is what I have tried : Dockerfile ## syntax=docker/dockerfile:1 #FROM python:3 #ENV PYTHONDONTWRITEBYTECODE=1 #ENV PYTHONUNBUFFERED=1 #WORKDIR /code #COPY water_maps/requirements.txt /code/ #RUN pip install -r requirements.txt #COPY . /code/ FROM ubuntu RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN #ln /usr/bin/pip /usr/bin/pip3 RUN pip3 install --upgrade pip RUN pip3 install django ptvsd #ADD ./test3.watermaps-eg.com.conf /etc/apache2/sites-available/000-default.conf COPY test3.watermaps-eg.com.conf /etc/apache2/sites-available #this line is for the global domain error ADD apache2.conf /etc/apache2/apache2.conf EXPOSE 80 3500 RUN echo pwd COPY . /var/www/html/ WORKDIR /var/www/html RUN apt install -y python3.10-venv RUN python3 -m venv venv RUN pip install -r water_maps/requirements.txt RUN a2ensite test3.watermaps-eg.com RUN python manage.py migrate CMD ["apache2ctl", "-D", "FOREGROUND"] docker-compose.yaml version: "2" services: django-apache2: build: . container_name: django-apache2 ports: - '80:80' - '3500:3500' - '8006:81' volumes: - .:/var/www/html test3.watermaps-eg.com.conf WSGIPythonPath /var/www/html WSGIPythonHome /var/www/html/venv <VirtualHost *:80> ServerName test3.watermaps-eg.com ServerAlias www.test3.watermaps-eg.com ServerAdmin admin@innoventiq.com DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/html> Require all granted </Directory> <Directory /var/www/html/static> … -
How to use Django ORM in a join with an aggregate subquery
I have a model like this (simplified): class Events(models.Model): reference_date = models.DateField() event = models.IntegerField(db_index=True) created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: unique_together = (('reference_date', 'event'),) I can have the same event with multiple reference dates, but I only have one event per reference_date. The table data looks something like this: id reference_date event created_at updated_at 1 2022-01-01 12345 2022-03-05 18:18:03 2022-03-06 18:12:09 2 2022-01-02 12345 2022-03-08 08:05:11 2022-03-08 08:05:55 3 2022-01-08 12345 2022-06-15 18:18:12 2022-06-16 02:23:11 4 2022-01-01 98765 2022-01-11 07:55:25 2022-01-13 08:45:12 5 2022-01-02 98765 2022-06-22 10:25:08 2022-07-05 18:55:08 6 2022-01-09 45678 2022-02-19 12:55:07 2022-04-16 12:21:05 7 2022-01-10 45678 2022-03-05 11:23:45 2022-03-05 18:55:03 I need the latest record for each event. But I need all the event attributes, not just the max(reference_date) I'm looking for this result: [ {'id': 3, 'event': 12345, 'reference_date': '2022-01-08', 'created_at': '2022-06-15 18:18:12', 'updated_at': '2022-06-16 02:23:11'}, {'id': 5, 'event': 98765, 'reference_date': '2022-01-02', 'created_at': '2022-06-22 10:25:08', 'updated_at': '2022-07-05 18:55:08'}, {'id': 7, 'event': 45678, 'reference_date': '2022-01-10', 'created_at': '2022-03-05 11:23:45', 'updated_at': '2022-03-05 18:55:03'} ] From a 'sql-perspective' I could get the results in multiple ways: SUBQUERIES, ROW_NUMBER, CORRELATED SUBQUERY etc. In this particular case for clarity reasons I prefer to use a join with itself using … -
I got a error while running server in django i was using git before
bibek@sweety-babe:~/Desktop/Friends$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/home/bibek/.local/lib/python3.10/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/bibek/.local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/bibek/.local/lib/python3.10/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/bibek/.local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/bibek/.local/lib/python3.10/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/bibek/.local/lib/python3.10/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc File "/home/bibek/.local/lib/python3.10/site-packages/django/db/migrations/loader.py", line 248, in build_graph self.graph.validate_consistency() File "/home/bibek/.local/lib/python3.10/site-packages/django/db/migrations/graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/bibek/.local/lib/python3.10/site-packages/django/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/bibek/.local/lib/python3.10/site-packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration base.0001_initial dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') i am getting this error suddenly after git push. I dont know what is the reason behind this please help me. this is just dummy (The POST method is used to send data to the server to create/update a resource on the server. In this HTTP POST request example, the Content-Type request header … -
Which the Better Option for Storing Large Data in Django Application
so i have an Django app that i currently working on, this app will do euclidean distance for 2000+ data. That much data if run when the web is in high demand will collapse so i think about several solution but i don't know if this is different when it's deployed. First idea is to compute all distances and put it in hardcoded variable in some_file.py. The file will look like this data = [[1,2,..],[3,4,..],[5,6,..],[7,8,..],...] and can be accessed like this data[0][2] = 2 this file is 60MB Second idea is the basic one, i create a table with 3 columns. A,B, and euclidean_distances(A,B). But this solution will create 4.000.000+ records. *NOTES I'm using Postgresql for my database My Question is, which one is the better solution to save all the distances when it is deployed ? i'm open to any other solution -
Django context not loading new items after POST
I have a view in Django that shows statistics of various items within the app. Users can filter what statistics they want to see based on selections. Currently I use JavaScript to update the values based on the context passed to the view. When the selection changes, I want to pass the new data to Django through a POST request and create a pie chart, save it as an image and pass it back to the view. I currently do this prior to the template loading, but when I try to pass the image in to context after the POST, I get nothing. Charts in view.html cmp_counts = [] cmp_counts.append(len(Campaign.objects.filter(reviewComplete=False))) cmp_counts.append(len(Campaign.objects.filter(reviewComplete=True))) cmp_counts.append(len(Campaign.objects.filter(closed=True))) labels = ["Open", "Completed", "Closed"] for count in cmp_counts: if count == 0: index = cmp_counts.index(count) labels.remove(labels[index]) cmp_counts.remove(count) print(cmp_counts) def auto(values): a = np.round(values/100*sum(cmp_counts), 0) plt.pie(cmp_counts, labels=labels, textprops={'color':"w"}, autopct=lambda x: '{:.0f}'.format(x*sum(cmp_counts)/100)) plt.title('All Campaigns', color="w") tmpFile = BytesIO() plt.savefig(tmpFile, transparent=True, format='png') encoded = base64.b64encode(tmpFile.getvalue()).decode('utf-8') html = '<img class="report-graphs" src=\'data:image/png;base64,{}\'>'.format(encoded) context['pie_chart'] = html plt.clf() This works just fine and creates the following pie chart: However, when trying to pass the charts that should change based on selection, I don't receive any error, I just can't access the context. HTML Script … -
How to force reverse related field unique in Django?
class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(settings.PRODUCT_MODEL, on_delete=models.CASCADE) quantity = models.SmallIntegerField(default=1) class Meta: ordering = ["pk"] class Select(models.Model): cartItem = models.ForeignKey(CartItem, on_delete=models.CASCADE) option = models.ForeignKey(Option, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) With the above code, what I want to do is each CartItem instance has an unique select_set. If two cartItems has the same product and select_set with the same option and choice combinations, They are considered to be same. I've done it with select as JSONfield of dict(option as key, choice as value) in which case what i need to do is just compare their JSONfield. class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(settings.PRODUCT_MODEL, on_delete=models.CASCADE) quantity = models.SmallIntegerField(default=1) selects = models.JSONField(default=dict) this one is the previous JSONfield one. cart_item, created = cart.cartitem_set.get_or_create( product_id=product_id, selects=selects ) if quantity == 0: cart_item.delete() else: cart_item.quantity = quantity cart_item.save() I've tried this one filtering having only same choices. queryset = cart.cartitem_set.filter(product_id=product_id) for option_id, choice_id in selects.items(): queryset = queryset.filter(select__choice=choice_id) cart_item, created = queryset.get_or_create( product_id=product_id, ) if not created: cart_item.quantity += quantity else: cart_item.quantity = quantity for option_id, choice_id in selects.items(): cart_item.select_set.create(option_id=option_id, choice_id=choice_id) cart_item.save() is there one hit create operation like the above one? using get_or_create And if possible I want to … -
Page not found (404) at /remove/, Hy i am a beginner and i want to delete data then i get this error ,please help me to solve this problem
urls.py ''' urlpatterns = [ path('', views.index, name='index' ), path('form', views.form, name='form' ), path('about', views.about, name='about' ), path('add_data', views.add_data, name='add_data' ), path('remove', views.remove, name='remove' ), path('remove/<int:emp_id>', views.remove, name='remove' ), ] ''' views.py ''' def remove(request,emp_id = 0): if emp_id: try: emp_removed=Members.objects.get(id=emp_id) emp_removed.delete() return HttpResponse('remover data successfully..') except: pass emps=Members.objects.all() context={ 'emp':emps } return render(request,'remove.html', context) ''' remove.html ''' <ul class="dropdown-menu"> {% for i in emp %} <li><a class="dropdown-item" href="/remove/{{emp.id}}">{{i.firstname}}</a></li> {% endfor %} </ul><ul class="dropdown-menu"> {% for i in emp %} <li><a class="dropdown-item" href="/remove/{{emp.id}}">{{i.firstname}}</a></li> {% endfor %} </ul> i want to delete some item from my template and i am getting the above mentioned error, if anyone know the answer please tell me ... This page shows when i run this code -
Django Save method giving an error trying to add a new record to table
I have the following code in a view: lp_detail = LearningPathDetail() pos_in_path = 1 lp_detail.lpheader_id = pk lesson_ids = request.POST["lesson_ids"].split(",") for lesson_id in lesson_ids: lp_detail.id = "" lp_detail.lesson_id = lesson_id lp_detail.pos_in_path = pos_in_path lp_detail.save() pos_in_path += 1 pk is the ID from the header table that points back to the header record that identifies all of the detail records associated with it. lesson_ids is a list of DB ids that need to be inserted into the lp_detail table. What I think the code should do (according to the manual) based on the id being blank (I have also tried setting it to None) is create the record, but instead I get an error: Field 'id' expected a number but got ''. Here is the model for the LearningPathDetail table: class LearningPathDetail(models.Model): lpheader = models.ForeignKey(LearningPathHeader, on_delete=models.CASCADE) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) pos_in_path = models.IntegerField(default=1) I am not sure what I have incorrect here. -
How to use several requirements.txt profiles with Django App at Heroku?
I've been trying to deploy a Django web app at Heroku and I'm using this layout for requirements: requirements/ ├── base.txt ├── local.txt ├── production.txt ├── staging.txt └── test.txt requirements.txt requirements.txt # This file is expected by Heroku. -r requirements/staging.txt # I have to change this for each env I thought that depending on an environment variable Heroku would pick the apropiate txt file. The thing is that after multiple attempts and searching the docs I realized that Heroku only picks requirements.txt and no other file. So I can only push to heroku for staging and if I need to push for another environment, I have to change requirements.txt in the repo or having an alternative branch only for this file. I'm thinking of using Heroku for at least a couple of environments, so I'd like to be able to manage more than one Heroku environment. So I went to investigate and I learnt that is possible to make a setup.py excluding the requirements.txt and managing this, but while reading the docs I couldn't understand yet how can I make setup.py pick the good requirements file among the multiple ones I have. I suppose somebody must have wanted to do …