Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
As a Benevole, how i can create a view for participate in a given mission [closed]
models.py class ProfileBenevole(models.Model): ville = [ ('--Aucun--', '--Aucun--'), ('Agadir', 'Agadir'), ('Casablanca', 'Casablanca'), ('Essaouira', 'Essaouira'), ('Fes', 'Fes'), ('Marrakech', 'Marrakech'), ('Meknes', 'Meknes'), ('Oujda', 'Oujda'), ('Rabat', 'Rabat'), ('Tanger', 'Tanger'), ('Tetouan', 'Tetouan'), ] activiter_prefere = ( ('Cadre', 'Cadre'), ('Salarié', 'Salarié'), ('Sans emploi', 'Sans emploi'), ('Commercent', 'Commercent'), ('Etudiant', 'Etudiant'), ('Autre', 'Autre'), ) user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) photo_profile = models.ImageField( upload_to='uploads/images',null=True,blank=True) nomComplet = models.CharField(max_length=50,null=True) telephone = models.CharField(max_length=20,null=True) adresse = models.CharField(max_length=100,null=True) date_naissance = models.DateTimeField(auto_now_add=True, null=True) cin = models.CharField(max_length=12, null=True) domaine_experience = models.TextField(null=True) biographie = models.TextField(null=True, blank=False) activiter_prefere = models.CharField(max_length=100, choices=activiter_prefere) ville =models.CharField(max_length=100,choices=ville) def __str__(self): return self.user.username class Mission(models.Model): domaine_prefere = ( ('Sport', 'Sport'), ('Santer', 'Santer'), ('Soutien Scolaire', 'Soutien Scolaire'), ('Aides Sociales', 'Aides Sociales'), ('Entreprenariat', 'Entreprenariat'), ('Informatique', 'Informatique'), ('Animation', 'Animation'), ) nom=models.CharField(max_length=50,null=False,blank=False) description=models.CharField(max_length=150,null=False,blank=False) date_publier=models.DateTimeField() date_modification=models.DateTimeField(auto_now=True) domaine=models.CharField(max_length=20, choices=domaine_prefere) lieu=models.CharField(max_length=50,null=False,blank=False) nombre_participant=models.CharField(max_length=50,null=False,blank=False) photo_mission = models.ImageField( upload_to='uploads/images',null=True,blank=True) slug=models.SlugField(null=True,blank=True) participe=models.ManyToManyField(ProfileBenevole,related_name='participer') class Meta: ordering = ('-date_publier',) def save(self,*args, **kwargs): if not self.slug: self.slug=slugify(self.nom) super(Mission,self).save(*args, **kwargs) def __str__(self): return self.nom -
how to access foreign table field in django view
I have two models, the plans model & plans features ( foreign relation with plans table), given below: Following is the view which returns an object of features for each plan: Now I want to access, the "price" field of the plans table (model). How this is possible? my Django template is the following which doesn't work: I belive there is solution to this, I would love hear from you . thank you -
how to run function encryption in django
so i have function for encryption in views.py. the file is saved at models. i want to run the function to know if the function is work. but i don't know how to run the function or code in urls.py here's my views.py : key_bytes = 16 testaudio = Audio_store.objects.all().values_list('audio').last() key = 'testing' # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a # pair (iv, ciphtertext). "iv" stands for initialization vector. def encrypt(key, testaudio): assert len(key) == key_bytes print(testaudio) print(key) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key, AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(testaudio) print(iv) print(ciphertext) return (iv, ciphertext) testaudio got by user add it from html. -
Django Numpy ImportError with Apache but not on runserver
so i've tried every other thread and their suggested solutions but without success so far. I have a Django app with a virtualenv and Apache 2.4 and mod_wsgi, which i developed on other server. Now, I'm migrating (rebuilding from scratch) everything on another server. While everything else works, when i tried to install pandas, the app served through Apache throws me an ImportError for Numpy. Original error was: /optilab/env/lib64/python3.6/site-packages/numpy/core/_multiarray_umath.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object Thing is, this doesn't happen while using runserver with manage.py . Everything is the same: Python Version (3.6.8), Python Executable (/optilab/env/bin/python) except the Python Path order. For the testing runserver, this is the Python Path list: ['/optilab', '/optilab/env/lib64/python3.6/site-packages', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/optilab/env/lib64/python3.6/site-packages', '/optilab/env/lib/python3.6/site-packages', '/home/appuser/.local/lib/python3.6/site-packages', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages', '/env/lib64/python3.6/site-packages'] But, for the app served through Apache, the Python Path is: ['/optilab', '/optilab/core', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/optilab/env/lib64/python3.6/site-packages', '/optilab/env/lib/python3.6/site-packages', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages'] I suspect that the list order is the culprit for this problem, but it seems i'm not able to change it. My file structure is the following: /optilab /core <-- startproject directory /env <-- virtualenv files /static /media ... other apps This is the first part of my apache config (BTW, I tried … -
Docker domain name not redirecting to HTTP or HTTPS
I have deployed a Django project using Docker and Nginx. All the process has gone well, but I am having a little issue. I am using certbot for HTTPS, and the redirection from HTTP to HTTPS works fine, but the problem is when I just type the domain name, without HTTP or HTTPS. If I type just the domain name in the URL (example.com) page doesn't load. And if y type http://example.com or https://example.com, everything works perfect. What could be the problem? How can I do to redirect the domain name to HTTPS? My Nginx configuration is the next one: server { listen 80; server_name ${DOMAIN}; location /.well-known/acme-challenge/ { root /vol/www/; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name ${DOMAIN}; ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem; include /etc/nginx/options-ssl-nginx.conf; ssl_dhparam /vol/proxy/ssl-dhparams.pem; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } -
Error while installing psycopg2 using pip
I am trying to run docker in django using this command docker build -t myimage . Now the docker file tries to run the RUN pip install -r /app/requirements.txt --no-cache-dir but when ot gets to the Downloading psycopg2-2.9.3.tar.gz (380 kB) section, it throws the error. NOTE: i do not have psycopg2 in my requirements.txt file only the psycopg2-binary. requirements.txt file ... dj-database-url==0.5.0 Django==3.2.7 django-filter==21.1 django-formset-js-improved==0.5.0.2 django-heroku==0.3.1 psycopg2-binary python-decouple==3.5 ... Downloading pytz-2022.2.1-py2.py3-none-any.whl (500 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 500.6/500.6 kB 2.6 MB/s eta 0:00:00 Collecting psycopg2 Downloading psycopg2-2.9.3.tar.gz (380 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 380.6/380.6 kB 2.7 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running egg_info creating /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info writing /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI … -
Django : Transfer data to another view by a button
I have a table of clients where each line has a button to redirect to another page with the id of the client. I do not want that it is on the URL, so I want to avoid a GET method, it is why I thought to us a POST method with the buttons. I did something but it is not working, I have an error message "Method Not Allowed (POST)" with the specific URL. html <table id="customers" class="table table-sortable"> <tr> <th>Référence Client</th> <th>Client</th> <th>Edit</th> </tr> {% for client in query_list_client %} <tr> <td>{{ client.id }}</td> <td>{{ client }}</td> <td> <a href="{% url 'modifyclient' uuid_contrat uuid_group % }" class="btn btn-primary" >Modify</a> <form action="{% url 'selectsaletype' uuid_contrat uuid_group %}" method="POST"> {% csrf_token %} <button name = 'client' type ='submit' value="{{ client.id }}" class='btn btn-secondary' > Select </button> </form> <!-- <a href="{% url 'selectsaletype' uuid_contrat uuid_group client.id % }" class="btn btn-secondary" >Selectionner</a> --> </td> </tr> {% endfor %} </table> urls urlpatterns = [ path('<str:uuid_contrat>/<str:uuid_group>/sales/selectclient/', ListSelectClient.as_view(), name="selectclient"), path('<str:uuid_contrat>/<str:uuid_group>/sales/selectsaletype/', SelectSaletType.as_view(), name="selectsaletype"), ] views class SelectSaletType(ListView): model = ListSaleType paginate_by =10 template_name = 'sales/selectsaletype.html' context_object_name = 'query_sale_type' def get_context_data(self, *args, **kwargs) : context = super(SelectSaletType, self).get_context_data(*args, **kwargs) context['uuid_contrat'] = self.kwargs['uuid_contrat'] context['uuid_group'] = self.kwargs['uuid_group'] print(self.request.POST) return … -
Test form_valid() in Createview
I am trying to test one of my CreateViews. The whole view looks like this: class BookCreate(CreateView): model = Book form_class = BookForm template_name = 'base/components/form.html' def form_valid(self, form): form.instance.user = self.request.user form.save() return HttpResponse( status=204, headers={ 'HX-Trigger': json.dumps({ "bookListChanged": None, }) }) The part of the view that needs testing according to coverage.py is this part: form.instance.user = self.request.user form.save() return HttpResponse( My test right now looks like this: class TestBookViews(TestCase): def setUp(self) -> None: self.user = User.objects.create_user(email='test@gmail.com', password='teSTpassword123') self.client.login(email='test@gmail.com', password='teSTpassword123') return super().setUp() def test_book_create(self): response = self.client.post(reverse('base:book-create'), { 'name': 'TestBook', 'user': self.user, 'publishing_date': '2022-08-17', }) self.assertEqual(response.status_code, 204) But this test does not make it covered. What I am missing? -
How to show all the lesson urls present in a lesson list?
I would like to retrieve lesson urls present in lesson model. class Course(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() price = models.FloatField() class Lesson(models.Model): title = models.CharField( max_length=200) course = models.ForeignKey(Course, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) class LessonURL(models.Model): category = models.ForeignKey(Lesson, on_delete=models.CASCADE) title = models.CharField(max_length=200) video_url = models.URLField() Below is my views.py def courseDetail(request, category_slug, course_slug): try: course_detail = Course.objects.get(category__slug=category_slug, slug=course_slug) all_lessons = Lesson.objects.filter(course=course_detail).order_by('created_date') all_lesson_urls = LessonURL.objects.filter(category__id=all_lessons) except Exception as e: raise e context = { 'course_detail': course_detail, 'all_lessons': all_lessons, 'all_lesson_urls': all_lesson_urls, } return render(request, 'course-detail.html', context) Here is my urls.py urlpatterns = [ path('<slug:category_slug>/<slug:course_slug>/', views.courseDetail, name='course-detail'), ] I am trying to explain my issue with the bellow example Ex: Course: "How to Learn Django" In that course i have 3 Lessons i.e Lesson 1, Lesson 2, Lesson 3 And each lesson contains multiple lesson urls. i.e Lesson 1: URL1, URL2, URL3 - Lesson 2 Contains URL4, URL5, URL6, and so on.. So i am facing the issue while extracting the lesson Urls. Now when i run the above code then its showing. Lesson 1 - (URL1, URL2, URL3, URL4, URL5, URL6) Lesson 2 - (URL1, URL2, URL3, URL4, URL5, URL6) But i wanted to show like … -
How do I filter a django model into ChartJS
Im new to Django and Im working on this project where I need to plot the number of employees based on a given hour. Model class Employe(models.Model): name = models.CharField(max_length=20) monday = models.CharField(max_length=20) tuesday = models.CharField(max_length=20) wednesday = models.CharField(max_length=20) thursday = models.CharField(max_length=20) friday = models.CharField(max_length=20) saturday = models.CharField(max_length=20) sunday = models.CharField(max_length=20) def __str__(self): return self.name Every row contains the name of the employee as well as the hour their shift starts at for each day of the week. I want the user to be able to select a certain day (for instance Monday) so that the graph shows how many employees work throughout the day (00:00 -> 23:59) Chart <canvas id="myChart" width="400" height="350"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for emp in employe %} '{{emp.monday}}', {% endfor %}], datasets: [{ label: '# Des employes', data: [], fill: true,}] options: { scales: { y: { beginAtZero: true } } } }); </script> -
What is the best way to transition from imp to importlib for CloudLinux Passenger WSGI files?
I am looking for the best way to transition from imp to importlib with my passenger_wsgi.py file using importlib as recommended by pylint. My passenger file looks like this: import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'core/wsgi.py') application = wsgi.application I have seen some examples using importlib.utils.find_spec(path) and some using importlib.machinery.SourceFileLoader('name','script') Does anyone have an example for their passenger_wsgi.py file that uses the newer method with importlib that would be the new standard they could share? -
import cv2 error on django ImportError: libGL.so.1
i'm working on a django project and i need to use the webcam. i've tried to install opencv-python with pip but python give me back the error ImportError: libGL.so.1: cannot open shared object file: No such file or directory. i've tried to install libGL.so.1 inside Dockerfile: RUN apt-get update RUN apt-get install libgl1 -y but I haven't solved my problem. -
httpd (apache) server django website hosting
I want to host my website on a VPS with Centos 7 I setup httpd (apache) server and set all the configuration in "/etc/httpd/conf/httpd.conf" file but it doesn't work. when i try to access my website in the browser, it will take a lot of time and finally it returns an error 500 & says that there is a problem in your configuration file. can you please check my file, whats wrong with this. # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot … -
Performing group by and aggregrate Django
How can I do the following in Django? SELECT AVG(calories) AS AVG_DAILY_CALORIES FROM ( SELECT date, SUM(calories) FROM products_eaten GROUP BY date ) daily_calories I already have the subquery itself with values and annotate. Adding aggregate after this fails. Thanks in advance! -
DoesNotExist at /settings Profile matching query does not exist. django error
this is the profile model class Profile(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) id_user=models.IntegerField() bio=models.TextField(blank=True) profileimg=models.ImageField(upload_to='profile_images',default='defualtdp.png') location=models.CharField(max_length=100,blank=True) def _str_(self): return self.user.username and in the views.py i tried to get the object like this def settings(request): user_profile=Profile.objects.get(user=request.user) return render(request,'setting.html',{'user_profile':user_profile}) and passed into settings.html <img src="{{user_profile.profileimg.url}}"> <textarea id="about" name="bio" rows="3" class="shadow-none bg-gray-100">{{user_profile.bio}}</textarea> <input type="text" name="location" value="{{user_profile.location}}" class="shadow-none bg-gray-100"> and its showing the error DoesNotExist at /settings Profile matching query does not exist. I am really dont know what to do... -
Use m2m_changed signal on model with related manager
I can set up a m2m_changed signal on one side of the relationship but not both. for example: This works: class Topping(models.Model): # ... pass class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) from django.db.models.signals import m2m_changed def toppings_changed(sender, **kwargs): # Do something pass m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through) But the following gives me the error AttributeError: type object 'Topping' has no attribute 'pizza_set' even though Topping.pizza_set.all() or Topping.pizza_set.through is successful in the shell: class Topping(models.Model): # ... pass class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) from django.db.models.signals import m2m_changed def toppings_changed(sender, **kwargs): # Do something pass m2m_changed.connect(toppings_changed, sender=Topping.pizza_set.through) -
KeyError: 'product_pk' [closed]
Internal Server Error: /store/products/1/images/ Traceback (most recent call last): File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "C:\Users\moaz\Desktop\pythoon\The Ultimate Django Series Part 2[TutsNode.com] - The Ultimate Django Series Part 2\Resources\Code\1- Getting Started\Start\storefront2\store\views.py", line 154, in get_queryset return ProductImage.objects.filter(product_id=self.kwargs['product_pk']) KeyError: 'product_pk' Internal Server Error: /store/products/1/images/ Traceback (most recent call last): File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File … -
How to get a QuerySet with type of a ForeignKey attribute in Django
I have a simple database model in Django that looks like: class Employee(Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class PrizeDraw(Model): winner = models.ForeignKey( Employee, null=True, on_delete=models.SET_NULL, ) What I want now is a QuerySet of type Employee that contains all the winners of all PrizeDraws. I would have thought that to be fairly straightforward by something something like: def get_queryset(self): return PrizeDraw.objects.exclude(winner__isnull=True).values('winner') However, that doesn't actually return me what I want, instead it returns: <QuerySet [{'winner': (Employee1) }, {'winner': (Employee2) }, etc...]> Which makes sense according to the values() documentation it returns a Dictionary of values. But this doesn't work for me in the rest of the code I need, so I want to select only the second (i.e. value) part of the key-value pair and return that as a QuerySet that just looks like <QuerySet[Employee1, Employee2, etc...]>. How can I select the right value as to get that desired QuerySet? -
Django ContentType and generic relationship
I need a proper and detailed explanation and understanding of how Django content type model works and the use and purposes of generic relationships. I am trying to create an anonymous chatting app where users can come and register and other people can send them messages whether registered or not through a link the user created and they would not know who sent it. -
Send data to another django template/view after specific process using ajax
I have a page where I load 2 files. After a click to the load button, this page reload to display a major part of the data, allowing the user to modified it. After a click to lunch button, I want to launch the process and I want to send to another page the path of results files to allow the user to download it. My problem is after clicking on lunch button and send data to the other page. I have 2 versions : The first one, send data to the result page, but I do not find a way to take back in the view the data modified by the user, the ajax seems to be ignored because of the type "summit" for the button launch : <body> <section class="bg-light py-5 border-bottom"> <div class="container px-5 my-5 px-5"> <div> <h1 class="display-5 fw-bolder mb-2"> Convert to Dose </h1> <br> </div> <form id="formCTD" action="{% url 'json:convertToDose' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} ##here some fields to modified one of them following <div class="row gx-5 justify-content-center"> <div class="col-lg-4 col-xl-4"> {% if factors %} <input name="img_path" readonly class="form-control" {{ pathAnalyseForm.img_path }}> {% else %} <input id="btn-submit-form-jsonfile" class="btn btn-lg" {{ formImgFile.imgFile }}> {% endif … -
Django - How to access parent object for passing as URL primary key inside templates?
I have two Django models: class AP(models.Model): room = models.ForeignKey(Room, on_delete=models.SET_NULL, null=True) and class Room(models.Model): name = models.CharField(max_length=20, unique=True) I have passed an object of AP class as ap to the template. In the template, I am trying to create a hyperlink with ID of the room. I am creating hyperlink through the following line: <a href="{% url 'edit_ap' ap.room.id %}">{{ap.room.name}}</a> This is throwing the following error: Reverse for 'edit_ap' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\\-ap/(?P<pk>[^/]+)/$'] The urls.py has the following matching pattern: path('edit-ap/<str:pk>/', views.edit_ap, name='edit_ap'), The hyperlink is working if the primary key is changed from ap.room.id to ap.room, which passes room.name as the primary key to the URL. However, I need to provide ap.room.id as the primary key. I believe it has to do with using two dots in the primary key. Can you please suggest how can I pass ap.room.id as primary key to my URL? Thank you. -
django clean method is not being called when validating form
I tried the simplest way of form validation I could find using the clean method (I need to validate multiple fields). However, it is not working and it is not throwing any errors. forms.py class DOEForm1(ModelForm): class Meta: model = Doe labels = { 'column_parameter': ('Parameter to vary'), 'column_min': ('Minimum value'), 'column_max': ('Maximum value'), 'column_step': ('Step value'), } exclude = ('substrate','row_parameter','row_min','row_max','row_step',) def clean(self): cleaned_data = super().clean() print('test') min = cleaned_data.get('column_min') max = cleaned_data.get('column_max') step = cleaned_data.get('column_step') if min and max and step: if not (int(step) > 10): raise ValidationError( '(!) the parameters you inputted dont go well with the substrate size' ) return cleaned_data template {% extends 'accounts/main.html' %} {% load static %} {% block content %} <br> <div class="row" style = "padding-left: 15px; width: 500px; margin: auto;"> <div class="col" style = "margin: auto; "> <div class="card card-body"> <form style = "margin: auto; width: 400px; padding: 20px; border: 1px solid #270644;" action="" method="POST"> {% csrf_token %} <table> {{ St_form.as_table }} {{ DOE_form.as_table }} </table> {% for error in form.non_field_errors %} <p class = "help is-danger">{{ error }}</p> {% endfor %} <input type="submit" name="Submit" > </form> </div> </div> </div> {% endblock %} views.py def ST_parameters(request): st_form = STForm() doe_form = DOEForm1() … -
working with SQLSERVER database that doesn't have keys using DJANGO
I'm currently doing an internship at a company, they asked me to build an invoice management web app, the process is a little complicated. First I created the login page, home page and the core elements of every web app. I used PostgreSQL for this, but when I wanted to build the main functionalities of the app, I switched to a copy of their database, they are using SQL Server 2012 and the data is coming from an ERP. The problem is when I have connected to database and use inspect DB to get the tables, I discovered that all the tables in the database don't have a Primary Key or Foreign Key. I asked the IT responsible about this and he told me that the ERP is stocking the data without any keys, it uses another method. I would really appreciate it if someone could help me out of this issue. -
Django - making form which contains two related models
I wonder if it is possible to make a django model based form which will allow to create two models which one will be passed as a foreign key to second one. let we have these models: class Book(models.Model): title = models.CharField(max_length=200) published = models.DateField() def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=200) number = models.IntegerField() book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return self.name I'd like to make a view which will contain BookForm and many ChapterForms somehing like: Book.title = [input] Book.published = [input] and below that (still in the same view) Chapter.name = [input] Chapter.number = [input] Chapter.name = [input] Chapter.number = [input] add more chapters After submitting form, Book and related chapters should be created How can I achive it ? Till now I was just making two views: one for making a Book and second one for chapter which gets created book's id as a parameter in url, but I'd like to make it in one view -
Different methods of Django User model
I have been using Django for 4 5 months now and i have been implimenting users by importing the user class like this example 1: from django.db import models from django.contrib.auth.models import User class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_name = models.CharField(max_length=150) desription = models.CharField(max_length=200) image = models.ImageField(upload_to="images/uploads") def __str__(self): return self.desription and i have seen some people use the user model like this : example 2: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=220) description = models.TextField(blank=True, null=True) directions = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) and also like this : example 3: author = models.ForeignKey(get_user_model()) now I have used both example 1 and example 2 for my projects and to mess around in my free time and both seem to work fine , I am wondering what would be the use cases for these different methods and also is there any pros or cons to these methods of using the User Model?