Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
how to link pages depending on foreign key using django
I tried to link countries to continents depending on the foreign key "ckey". I tried using filter and .raw but it didn't work. I tried to use it directly on HTML but it said it cannot praise it. I need to know if there is another way of linking pages like "continents -> countries -> cities -> ...." using Django. models from django.db import models # Create your models here. class Continents(models.Model): ckey = models.CharField(max_length=10, primary_key=True) continentName = models.CharField(max_length=50) class country(models.Model): countryNum = models.IntegerField(primary_key=True) countryName = models.CharField(max_length=15) countryBrief= models.TextField(max_length=500) currency = models.CharField(max_length=15) cost = models.FloatField(max_length=10) cultures = models.TextField(max_length=300) rulesBrief = models.TextField(max_length=200) location = models.TextField(max_length=500) ckey = models.ForeignKey('Continents', on_delete=models.PROTECT) views.py from django.shortcuts import render from django.http import HttpResponse from .models import Continents, country # Create your views here. def home(request): return render(request,"guide/home.html") def continents(request): continentdata = Continents.objects.all() return render(request,"guide/Continents.html",{'Continents':continentdata}) def countrylist(request): countries = country.objects.all() first_person = country.objects.filter(ckey='as45914') context = { "first_person":first_person, "countries":countries, } return render(request,"guide/countrylist.html",context=context) html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {{first_person}} </body> </html> strange message I got when I run the code How do I link pages like that? For example "Europe > United kingdom > all … -
How delete a record on button click using Django?
I am trying to delete a record in a database when a yes button is clicked using django. views.py def deleteServer(request, server_id): server = Server.objects.get(pk=server_id) print(request.POST) if request.POST.get('yesBtn'): server.delete() return HttpResponseRedirect('homepage') elif request.POST.get('noBtn'): return HttpResponseRedirect('homepage') return render(request, 'deleteServer.html', {'value': request.POST}) deleteServer.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Cancella server</title> </head> <body> <button onclick="document.getElementById('id01').style.display='block'" class="w3-button">Cancella server</button> <!-- The Modal --> <div id="id01" class="w3-modal"> <div class="w3-modal-content"> <div class="w3-container"> <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">&times;</span> <p>Vuoi davvero cancellare il server selezionato?</p> <a href="{% url 'homepage' %}" type="button" name="yesBtn" class="btn btn-success">SI</a> <a href="{% url 'homepage' %}" type="button" name="noBtn" class="btn btn-danger">NO</a> </div> </div> </div> </body> </html> When I click on the yes button the record is not deleted. I thought the problem is in the deleteServer function in the file views.py. -
CSS and HTML (django)
Hey so i have this CSS .welcome_box{ background-color: aqua; min-height: 50px; min-width: 50px; padding: 20px }` and in the html <div class="welcome_box" > <div class="center" > <a href="{% url 'login'%}"> <button class="button">Log In</button> </a> </div> <div class="center"> <a href="{% url 'signup'%}"> <button class="button"> Sign Up</button> </a> </div> </div> and the rel <link rel="stylesheet" href="{% static 'welcomepage/styles/css/mycss.css' %}"> however the CSS does not seem to take effect on the page, for some reason its only this class as the rest are working. I don't do much html and css so it may be something very basic. Edit: Inline CSS seems to work fine but again, the other classes from the same css file do take effect -
AssertionError: False is not True in Django when testing for valid forms
I am writing a test for my views to check if the POST data is validated but the test failed with this error, self.assertTrue(form.is_valid()) AssertionError: False is not true Below are my codes tests.py from .models import Customer from .forms import CustomUserCreationForm from django.contrib.auth import get_user_model from django.urls import reverse from django.http import HttpRequest # Create your tests here. class CreateAccountTest(TestCase): email = "example@gmail.com" def test_signup_page_status_code(self): response = self.client.get('/accounts/signup/') self.assertEqual(response.status_code, 200) def test_signup_url_by_name_and_uses_correct_template(self): response = self.client.get(reverse ('register')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'registration/signup.html') def test_signup_empty_form(self): form = CustomUserCreationForm() self.assertIn('first_name', form.fields) self.assertIn('last_name', form.fields) self.assertIn('password1', form.fields) self.assertIn('password2', form.fields) def test_signup__post_form(self): request = HttpRequest() request.POST = { 'email': self.email, 'first_name': 'Adam', 'last_name': 'Smith', 'password1': 'qazxswedcvfr', 'password2': 'qazxswedcvfr', } form = CustomUserCreationForm(request.POST) self.assertTrue(form.is_valid()) form.save() self.assertEqual(get_user_model().objects.all().count(), 1) -
Multi Value DictKey Error in django while getting files in Django
So, I have this simple django code in which a user uploads a image to change his user image but whenever I am trying to initiate the function it throws a multi value dict key error. Views.py def image(request): email = request.user.email img = request.FILES['image'] users = get_user_model() User = users.objects.get(email=email) User.image = img User.save() return redirect('settings') I am using a custom user model aswell so here is my models.py also class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True,) user_name = models.CharField(max_length=150, unique=False) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) image = models.ImageField(upload_to = 'pics') DOB = models.CharField(max_length =12, default=timezone.now) start_date = models.CharField(max_length =12,default=timezone.now) about = models.TextField( max_length=500, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_buss = models.BooleanField(default=False) phone = models.CharField(max_length=12) otp = models.CharField(max_length=6, null=True) otp_g = models.CharField(max_length=15, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name','first_name'] objects = CustomAccountManager() def __str__(self): return self.user_name class CustomAccountManager(BaseUserManager): def create_superuser(self, email,user_name, first_name,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('SuperUser must have is_staff as true') if other_fields.get('is_active') is not True: raise ValueError(_('SuperUser must have is_active as true')) if other_fields.get('is_superuser') is not True: raise ValueError('SuperUser must have is_SuperUser as true') return self.create_user(email,user_name, first_name, password, **other_fields) def create_user(self, email,user_name, first_name, password, … -
How Can I query Django Models with Foreign and OneToOneFields for Field Values
I have the following Django Models in my project: Event, Ticket, Pin and Guest so How can I query these tables in order to get the name of an Event Name the logged in guest user has registered for . Below are my code. My Models: class Event(models.Model): event_name = models.CharField(max_length=100) date = models.DateField(auto_now_add=False, auto_now=False, null=False) event_venue = models.CharField(max_length=200) event_logo = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images') added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.event_name}" #Prepare the url path for the Model def get_absolute_url(self): return reverse("event_detail", args=[str(self.id)]) #Ticket Model class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PASS, default=None, blank=True, null=True) added_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.event} " #Prepare the url path for the Model def get_absolute_url(self): return reverse("ticket-detail", args=[str(self.id)]) def generate_pin(): return ''.join(str(randint(0, 9)) for _ in range(6)) class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, *args, **kwargs): self.reference == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.ticket class Meta: unique_together = ["ticket", "value"] def __str__(self): return f"{self.ticket}" def get_absolute_url(self): return reverse("pin-detail", args=[str(self.id)]) class Guest(models.Model): guest_name = models.OneToOneField(User, on_delete=models.CASCADE, blank=True) pin … -
Django distinct queryset
I am new in django and maybe someone in here can help me with this.. model.py class Transaction(models.Model): ref_code = models.CharField() buyer = models.ForeignKey(User) product = models.ForeignKey(Product) quantity = models.IntegerField() ref_code is not unique. The Data is something like this: id: 1, buyer: John, product : Book, quantity: 1, ref_code = 111111 id: 2, buyer: Thomas, product : Pencil, quantity: 3, ref_code = 111111 id: 3, buyer: Mary, product : Book, quantity: 2, ref_code = 222222 id: 4, buyer: Bryan, product : Origami, quantity: 2, ref_code = 222222 id: 5, buyer: Anna, product : Eraser, quantity: 5, ref_code = 111111 id: 6, buyer: Lily, product : Notebook, quantity: 1, ref_code = 222222 How can I view buyer, product, and quantitiy in template based on ref_code ? So, it will look like this: REFERAL CODE: 111111 Buyer: John, Product : Book, Quantity: 1 Buyer: Thomas, Product : Pencil, Quantity: 3 Buyer: Anna, Product : Eraser, Quantity: 5 REFERAL CODE: 222222 Buyer: Mary, Product : Book, Quantity: 2 Buyer: Lily, Product : Notebook, Quantity: 1 Buyer: Bryan, Product : Origami, Quantity: 2 Thanks in advanced -
Reset a page after submitting a button
<form method=GET> {% csrf_token %} <ul><h2 style="font-weight: bold;">Список дел</h2><br><details open><summary style="color:#0077DC">свернуть фильтр</summary> <li><p class="name"><i>С какого числа искать:</i>{{ myFilter.form.start_date }}</p></li> <li><p class="name"><i>По какое:</i>{{ myFilter.form.end_date }}</p></li> <li><p style="font-size:16px; color: red;"><i>Наименование суда:</i>{{ myFilter.form.trial }}</p></li> <p style="font-size:16px; color:#f44133;"><i>Судопроизводство:</i>{{ myFilter.form.proceeding }}</p> <p style="font-size:16px; color: red;"><i>Первая подкатегория:</i>{{ myFilter.form.categories__value }}</p> <p style="font-size:16px; color: red;"><i>Вторая подкатегория:</i>{{ myFilter.form.categories__second1_dispute }}</p> <p style="font-size:16px; color: red;"><i>Вторая подкатегория:</i>{{ myFilter.form.categories__second2_dispute }}</p> <p style="font-size:16px; color: red;"><i>Третья подкатегория:</i>{{ myFilter.form.categories__third_dispute }}</p> <br> <button class="btn btn-dark" type="submit" style="width:39%;">Применить</button> <input class="btn btn-dark" type="reset" value="Отменить выбор" style="width:59%;"></a><br> <br> </form> A have the form and if a choose a filtration category I can reset the page, but if I submit the button and I want to reset the page after that nothing changes. -
Get View associated with a URL
I'm looking to know the associated class-based view that is associated with a path. Say I have URL pattern like this : urlpatterns = [ path("hello/<str:name>/", views.HelloView.as_view(), name="hello-page") ] Could I, from a path like "hello/foo/" get back to the HelloView class ? Ideally I'd like to be able to do it like this : the_url = "hello/foo/" url_associated_view = get_view_class_from_path(the_url) print(url_associated_view) >> HelloView It's different from this topic because the suggested answer only gives me the as_view function as a value, while I'm trying to get the HelloView class as return value. -
Django templates path change problem Django 4.1.1
enter image description here i am new in Django i want change my Django Template path . but they are set by dafault a path in setting.py then i import os but it will not working