Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to combine two queries after doing a group by
GOAL: Group by ITEM all INCOMING and its OUTGOING then SUM the quantity to come up with a simple table in my template like this: Item | Total In | Total Out| Stock 1. Cement | 400 | 300 | 100 My models.py class Incoming(models.Model): ... project_site = models.ForeignKey(ProjectSite, related_name='in_project_site', default=7, null=True, on_delete = models.SET_NULL) item = models.ForeignKey(Item, related_name='item_in', null=True, on_delete = models.SET_NULL) quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0) ... class Outgoing(models.Model): ... base_in = models.ForeignKey('warehouse.Incoming', related_name='out', on_delete = models.SET_NULL, null=True) quantity = models.DecimalField('Quantity', db_index=True, max_digits=20, decimal_places=2, default=0) ... Okay so the goal is to group all incoming by ITEM, then annotate the current total Incoming and Outgoing. So naturally I did this in my views.py incoming = Incoming.objects.filter(project_site__id=self.object.id) context['inventory'] = incoming.values('item__item_name')\ .annotate(tot_in=Sum('quantity'))\ .annotate(tot_out=Sum('out__quantity')) This does not give the proper SUM for the total_in, now after some search this is apparently an issue. One suggestion I found was to separate the query into to so this is what I did. context['current_in'] = incoming.values('item__item_name').annotate(tot_in=Sum('quantity')) context['current_out'] = incoming.values('item__item_name').annotate(tot_out=Sum('out__quantity')) This gives me the correct SUM for each In and Out, now my problem is how to UNITE/COMBINE the two again so I could easily loop through it on my template? I did … -
Mock A Folder Including Its Contents For Unit Test
I am unit testing a function which generates a pdf and stores it in the MEDIA folder. This means my MEDIA folder fills with files generated during unit testing which I must then manually delete. To overcome this I decided to mock the media folder from django.test import override_settings import tempfile @override_settings(MEDIA_ROOT=tempfile.gettempdir()) def test_redirects_after_POST(self): # user is created # POST is tested (pdf is generated within this view) # assertions made This seems like it should work. My problem is that during the first step - where the user is created for the test, the user is given a default profile picture, which is stored in the MEDIA folder. Since I am mocking this folder, the image doesnt exist I get the following error FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Acer\\AppData\\Local\\Temp\\profile_pics\\default.jpg' My question is how can I mock the default profile image in the MEDIA folder OR otherwise work around this? Thank you -
Unable to iterate a dictionary in django templating language
I have not been able to iterate (key and values) in a nested dictionary generated from views.py where context = { "orders_current": orders_current } with return render(request, "orders/cart.html", context) orders_current is a result from a query in views.py: orders_current = Orders.objects.values('def', 'abc', 'toppings') 'toppings' is stored in the database as JSON data but converted (loads) back to a dictionary in the class method: def __str__(self) in models.py. I did this since I read somewhere this is a recommend way of storing a dictionary in the postgresql. Note that orders_current has multiple and nested dictionaries e.g.: < QuerySet [{'category_name': 'Regular Pizza', 'size': 'small', 'item_name': 'Cheese', 'item_price': Decimal('12.70'), 'toppings_selected': True, 'toppings': '{"Mushrooms": 1.5, "Canadian Bacon": 1.5}'}] > The dictionary {{ order.toppings }} passed to the html, cart.html is shown to have the value (in verbatim) e.g.: {"Mushrooms": 1.5, "Canadian Bacon": 1.5} So my latest attempt to extract the topping name and the corresponding price (key, value) from the dictionary is: {% for order in orders_current %} ... <table> {% for name, price in order.toppings.items %} <tr> <td>{{ name }}:</td> <td>${{ price }}</td> </tr> {% endfor %} </table> I got no values (name, price)from this code snippet. Based on my web searches, I've … -
How to pass varibles from javascript to django views file
I am uploading CSV and print it on the webpage and later I am trying to pass the variable to Django view.py function but I can't able do that so please someone help me to fix this issue <input type="file" id="fileinput" /> <script> function readSingleFile(evt) { var f = evt.target.files[0]; if (f) { var r = new FileReader(); r.onload = function(e) { var contents = e.target.result; <!--document.write("File Uploaded! <br />" + "name: " + f.name + "<br />" + "content: " + contents + "<br />" + "type: " + f.type + "<br />" + "size: " + f.size + " bytes <br />");--> var lines = contents.split("\n"), output = []; for (var i=0; i<lines.length; i++){ output.push("<tr><td>" + lines[i].split(",").join("</td><td>") + "</td></tr>"); } output = "<table>" + output.join("") + "</table>"; document.write(output); <!--$.post(output);--> exportTableToCSV(null,'test.csv') } r.readAsText(f); document.write(output); <!--$.post(output)--> } else { alert("Failed to load file"); } } document.getElementById('fileinput').addEventListener('change', readSingleFile); </script> view.py code def read(request): if request.method == 'POST': count = request.POST.get['ouput'] print(count) return -
AWS Elastic Beanstalk Django Migration
I have an EC2 instance set up through Beanstalk, but I cannot get the config to run migration my .ebextension/django.config option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: my_app.settings aws:elasticbeanstalk:container:python: WSGIPath: my_app.wsgi:application NumProcesses: 3 NumThreads: 20 container_commands: 00_test_output: command: "echo 'testing.....'" 01_migrate: command: "python manage.py migrate" leader_only: true After checking the logs, it says Invalid HTTP_HOST header: '52.37.179.147'. You may need to add '52.37.179.147' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '172.31.0.249'. You may need to add '172.31.0.249' to ALLOWED_HOSTS. Now even if I add these ip's to ALLOWED_HOSTS in my settings.py, the problem remains. I searched around here and found no answer to this specific issue Without the migration commands, my server is built successfully and is running. Anyone know why? -
Left Join to the latest row using django
I have two tables. Products [id, name, category] Sales [product, date, price] I want to get every Product with the latest row from Sales. If there is no row in sales, I still want to get that product row. The rows are foreign key related. What is the Django way of doing such a left join? -
Can I rely on RAM Objects? Django
I'm very new in Django. And I'm building a web app that uses a lot of calculations in the backend with numpy matrixes and other libraries, it's a scientific application solving a np-hard problem. I've created a simple database and I'm saving the matrixes in the database and a Global Object I created in views.py.The issue is that I first save the matrixes in the Global Object (It means is saved in RAM memory) because I have to do a lot of calculations and then save the results in the matrix, and later in other view func I will take the matrixes with the calculations and save them in the database. Here is some of my code: views.py import PesosObjetivos as po #PesosObjetivos is a module where many calculations are made import numpy as np #other imports that are not important to write here nombre_met_MAN="Método Manual" nombre_met_GMWM="Método Media Geométrica" nombre_met_SDWM="Método Desviación Estándar" nombre_met_CRITICM="Método Matriz de Correlaciones" nombresMets = np.array([nombre_met_MAN,nombre_met_GMWM,nombre_met_SDWM,nombre_met_CRITICM]) class ObjetoVistas(): """ Class to create the Global Object """ def __init__( self, nombresMetodos=np.array([]), metodosUsados=np.array([]), matrices=np.array([]), pesosMAN=np.array([]) ): self.nombresMetodos = nombresMetodos self.metodosUsados = metodosUsados self.matrices = matrices self.pesosMAN = pesosMAN #Object for the view which saves the matrixes and other numpy … -
Pasar valores por defecto en class (CreateView) de Django al crear nuevos modelos [closed]
El código es para una biblioteca en la que un libro puede tener varias copias con distintos autores o idiomas. Quiero crear un nuevo modelo (instancia de libro) que está relacionado con otro por medio de un ForeingKey (libro). Al usar class BookInstanceCreate(CreateView) me guarda el nuevo registro sin inconveniente, pero tengo dos problemas. Necesito retornar a el detalle del libro, no al de la instancia del libro. AL usar success_url='/books_details// que es a donde quiero retornar tengo que mi url necesita una pk, pero no sé cómo pasársela. Me renderiza un formulario para escoger entre todos los libros y es muy dispendioso tener que buscar el libro al que quiero crearle una instancia, me gustaría que este valor esté por defecto (obtenido desde el template anterior que es el detalle del libro a instanciar) para solo modificar los que me interesan con fields =[...] Dejo el código que tengo con los campos de interés: models.py: import uuid class Book(models.Model): title=models.CharField( max_length=100, help_text="enter the book's name" ) summary=models.TextField( max_length=1000, help_text="insert a short description" ) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) class BookInstance(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text="ID único para este libro particular en toda la biblioteca" … -
Uploading and viewing pdf in django
I am making a Webapp using django. In the app, users can login and upload one pdf file. Then others users can visit their profile and view/download the uploaded pdf file. I know how to upload the pdf. But how do I make it viewable and downloadable from the site?? -
(Python) How do I pass the variable in a decorator to functions?
I have been trying to use a decorator for web token like so: def login_required(func): def wrapper(self, request, *args, **kwargs): header_token = request.META.get('HTTP_AUTHORIZATION') decoded_token = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['email'] user = Customer.objects.get(email=decoded_token) customer_id = user.id try: if Customer.objects.filter(email=decoded_token).exists(): return func(self, request, *args, **kwargs) else: return JsonResponse({"message": "customer does not exist"}) except jwt.DecodeError: return JsonResponse({"message": "WRONG_TOKEN!"}, status=403) except KeyError: return JsonResponse({"message": "Key Error"}, status=405) except Customer.objects.filter(email=decoded_token).DoesNotExist: return JsonResponse({"message": "User Not Found"}, status=406) return wrapper class CartView(View): @login_required def post(self, request): import pdb; pdb.set_trace() try: body = json.loads(request.body) # below is when the customer's order is still active if user.order_set.all().last().order_status_id == 2: # update the order by just adding carts order = user.order_set.all().last() order_id = order.id However, when I check with 'import pdb' the variables 'header_token', 'decoded_token', 'user' and 'customer_id' does not turn up in the 'post' function, thus resulting in 500 error. Here is what I find via pdb. (Pdb) decoded_token *** NameError: name 'decoded_token' is not defined (Pdb) user *** NameError: name 'user' is not defined (Pdb) Performing system checks... What should I do to make them pass onto the function rather than disappear as soon as the interpreter exits the decorator? Thanks! -
I leave a question regarding DRF multi-image processing
class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = "image" class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True) class Meta: model = Post fields = ( "id", "author", "content", "images", ) I'd like to get the results the following response from the above communication codes. (위 코드로 GET 통신에서 아래와 같은 응답 결과를 얻고 싶은데요.) { "id": 53, "author": 1, "post": "awesome", "images": { "image": "abc.png", "image": "def.jpg", } } The images field does not apply and appears like below. (images 필드가 적용되지 않고 아래와 같이 나오는 상황입니다.) { "id": 53, "author": 1, "post": "awesome", } Which part should I fix? I also attach the code for the model. (어떤 부분을 고쳐야할까요? 모델 단 코드도 같이 첨부합니다.) class Post(models.Model): author = models.ForeignKey("User", on_delete=models.CASCADE) post = models.CharField(max_length=100) class PostImage(models.Model): post = ForeignKey("Post", on_delete=models.CASCADE) image = models.ImageField(upload_to="image", blank=True) -
TypeError at /admin/mainapp/newsadmodel/add/ expected string or bytes-like object
I'm using django storages to access aws s3 bucket. While adding images to the model NewsAdModel using admin panel, I'm getting this error. TypeError at /admin/mainapp/newsadmodel/add/ expected string or bytes-like object. It does not give me any error hint. What could be wrong here? models.py class NewsAdModel(models.Model): name = models.CharField(max_length=255) pic = models.FileField(storage=PublicMediaStorage(),upload_to='ads') class Meta: verbose_name = 'News Ad' verbose_name_plural = 'News Ads' def __str__(self): return self.name Error message: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/mainapp/newsadmodel/add/ Django Version: 2.2.12 Python Version: 3.7.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'mainapp', 'storages'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in add_view 1645. return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\optimus\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\admin\options.py" in changeform_view 1529. … -
How to fix Unexpected token error, expected “}”
I keep on getting an error saying unexpected token but have no idea where that unexpected token is at? Please help Code is below import React from 'react'; import react, { Component } from 'react' import { Plateform, StyleSheet, View,Text } from 'react-native'; function Header() { return ( <div> <this.View style={style}/> <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text> <header className="header"> <div className="col1"> </div> <div className="col2"> <div className="menu"> <h3>About</h3> <h3>Cars</h3> <h3>Contact</h3> <h3>Search</h3> <header/> <View/> </div> </div> **Here is where the error seems to be happing** ); } export default Header; App = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center' }, setFontSize: { fontSize: 20, fontWeight : 'bold' }, setColorRed : { color: '#f44336' } }); Error is below as well Line 37:12: Parsing error: Unexpected token, expected "}" 35 | 36 | App = StyleSheet.create({ 37 | container: { | ^ 38 | flex: 1, 39 | justifyContent: 'center', 40 | alignItems: 'center' -
Django: Attempting to create custom 2 password confirmation in my registration form. Form is not valid?
my name is Paul, I am an early high school beginner working on my first "independent" project. "Independent" meaning without tutorial guidance. My goal is to make a calendar website, just to keep track of a list of events such as homework, meetings, and such. Currently, I am working on the registration form. At first, I used the built in UserCreationForm but I decided to create my own HTML form. I am working on recreating this 2 password confirmation form which would take in the two inputs, make sure there aren't any forbidden keys, make sure that the two passwords are matching, and then save that password into the User model's password, along with a username, first_name, and last_name(this would happen in my view.py file). When I first tried registering, nothing would pop up and as I checked the admin page it turns out no new Users were made. So I put up messages throughout my view if statements to see where the code was getting cut off. It turns out that the form.is_valid was returning false, and I'm not too sure why. I want to believe it may be that my HTML form inputs do not match my forms.py … -
Is it possible to have an external file input for choicefields in django?
I have ChoiceField in my Django model which consist of several choices and i am using the CheckboxSelectMultiple widget in forms to have multiple select options. models- BREAKFAST_CHOICES = (('fruits', 'A bowl of fruits with nuts'), ('tofu', 'Tofu Omlette'), ('1', 'Option 1'), ('2', 'Option 2'), ('3', 'Option 3'),) breakfast = MultiSelectField(choices=VBREAKFAST_CHOICES, null=True, blank=True, default=False) forms- widgets = { 'breakfast': forms.CheckboxSelectMultiple, } Now, in the future if I want to change the existing choice (options) with some other or add and delete options,how can i do this? Is there an easier way for a non programmer to just externally update a file and achieve this? i.e can my choicefield take an external file containing the list of options which can be edited as and when required. -
Apache2 + mod_wsgi + multiple virtual hosts for subdomains
I'm trying to setup two websites on a single server: domain.com subdomain.domain.com I am using Ubuntu 18.04.4 LTS, Apache/2.4.29, mod_wsgi/4.7.1, Python/3.8. Both the websites are Django applications. I created two virtual environments and installed mod_wsgi in each using the PyPi package and created two files in the mods-available directory and enabled the mods as described here: app1.load app2.load I created two configuration files under sites-available. The first configuration file is: <VirtualHost *:80> ServerName domain.com ServerAlias www.domain.com ServerAdmin abc@xyz.com #DocumentRoot /var/www/html LogLevel info ErrorLog ${APACHE_LOG_DIR}/error_app1.log CustomLog ${APACHE_LOG_DIR}/access_app1.log combined WSGIDaemonProcess app1 python-path=/home/ubuntu/app1 python-home=/home/ubuntu/anaconda3/envs/env1 WSGIProcessGroup app1 WSGIScriptAlias / /home/ubuntu/app1/app1site/wsgi.py <Directory /home/ubuntu/app1/app1site> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The second configuration file is: <VirtualHost *:80> ServerName subdomain.domain.com ServerAlias www.subdomain.domain.com ServerAdmin abc@xyz.com #DocumentRoot /var/www/html LogLevel info ErrorLog ${APACHE_LOG_DIR}/error_app2.log CustomLog ${APACHE_LOG_DIR}/access_app2.log combined WSGIDaemonProcess app2 python-path=/home/ubuntu/app2 python-home=/home/ubuntu/anaconda3/envs/env2 WSGIProcessGroup app2 WSGIScriptAlias / /home/ubuntu/app2/app2site/wsgi.py <Directory /home/ubuntu/app2/app2site> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> I get the following error logs: error.log [so:warn] [pid 8720:tid 140180032101312] AH01574: module wsgi_module is already loaded, skipping [mpm_event:notice] [pid 8727:tid 140180032101312] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.7.1 Python/3.8 OpenSSL/1.1.1 configured -- resuming normal operations [core:notice] [pid 8727:tid 140180032101312] AH00094: Command line: '/usr/sbin/apache2' [ssl:info] [pid 8733:tid 140179895777024] [client 73.16.240.233:49414] AH01964: Connection to child 66 established … -
How to customize form django with fields of the diferents Models
I need to display a field on a form and another field on a Model in html page. class CatracaForm(forms.Form): ra = forms.CharField(label='RA', max_length=30) class MotivoForm(forms.ModelForm): class Meta: model = Motivo fields = ['descrmotivo', 'obs'] In my HTML page I want show ra and descrmotivo field. The descrmotivo field should be a combobox component. How to make this? -
Calling a function inside a handler function | Razorpay | Django
I am not able to call a function inside a handler function. If I call the function complete() outside the handler function it throws me an errorJSONDecodeError. I want to call this function after the user pays and send the response data i.e razorpay_payment_id to the function complete(), so that I can parse the data in my server side/ success view. <script> var orderID = '{{order_id}}' var oID = '{{object.order_id}}' var name = '{{fullname}}' var email = '{{object.billing_profile}}' var keyID = '{{key_id}}' var orderAmount = '{{order_amount}}' function complete(){ var url = /success/ fetch(url, { method:'POST', headers:{ 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'razorpay_payment_id':razorpay_payment_id}) }) } var options = { "key": keyID, // Enter the Key ID generated from the Dashboard "amount": orderAmount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Monday", "description": "Test Transaction", "image": 'https://i.imgur.com/n5tjHFD.png', "order_id": orderID, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "handler": function (response){ // alert(response.razorpay_payment_id); // alert(response.razorpay_order_id); // alert(response.razorpay_signature) var razorpay_order_id = response.razorpay_order_id var razorpay_payment_id = response.razorpay_payment_id var razorpay_signature = response.razorpay_signature var secret = '{{keySecret}}' var generated_signature = CryptoJS.HmacSHA256(razorpay_order_id + "|" + razorpay_payment_id, secret); // … -
Push rejected, failed to compile Python app. Push failed
I think the error is in requirement.txt but I don't know what My requirement.txt: asgiref==3.2.7 astroid==2.3.3 colorama==0.4.3 dj-database-url==0.5.0 dj-static==0.0.6 Django==3.0.5 django-cors-headers==3.2.1 djangorestframework==3.11.0 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 Pillow==7.1.1 pylint==2.4.4 python-decouple==3.3 pytz==2019.3 six==1.14.0 sqlparse==0.3.1 static3==0.7.0 wrapt==1.11.2 -
Django: retrieving values of ManyToMany Relationship
I am attempting to implement a 'download csv' action in the django admin, to download the data associated with any model. To handle all models together, and to prevent the need for code changes if the model is changed, I am trying to implement one function (download_csv) that programmatically gets the fields associated with the model, and then saves a row for each object with the values of each field filled in. However, ManyToMany relationships result in an error such as: ManyToManyRel' object has no attribute 'value_from_object. How can I retrieve the values of these fields? The function works when downloading Lectures, but not Speakers, since the ManyToMany relationship is "reversed" (i.e. contained in the model Lecture). models.py class Speaker(models.Model): first_name = models.CharField(max_length=200) class Lecture(models.Model): lecture_title = models.CharField(max_length=200) speaker = models.ManyToManyField(Speaker) admin.py def download_csv(modeladmin, request, queryset): ''' Download CSV of all objects in queryset ''' try: main_model = modeladmin.corresponding_model except AttributeError: modeladmin.message_user(request, 'That action cannot be performed on these objects.') return fields = main_model._meta.get_fields() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=data.csv' writer = csv.writer(response, csv.excel) writer.writerow(fields) for obj in queryset: writer.writerow([field.value_from_object(obj) for field in fields]) return response admin.site.register(Speaker, SpeakerAdmin) admin.site.add_action(download_csv, 'export_csv') -
How to get a value passed throuhgt url to a class Create View in django?
Salutations good people of stack overflow, I read the docs and I been duckduckgoing this and I can't find and answer. I am pretty new to Django so if my approach is totally wrong please let me know. ^^ I am using Django 3.0 and I want to get a Primay Key of a model for a Post into a create view for a Comment Model with a foreign Key Post field, so that each Comment knows to which Post it belong in a one to many relationship. To accomplish I am defining the template as: <a href="{% url 'comment_new' post.pk %}"> <p class="text-center">Write a Comment</p> </a> In my urls.py I have: urlpatterns = [ path('<int:post>/new', CommentCreateView.as_view(), name='comment_new'), ] and in my views.py I have: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'Comment_new.html' fields = ('writing',) login_url = 'login' def get_object(self, **kwargs ): return models.objects.get(id=self.kwargs['post']) def form_valid(self, form): ''' Set the user which send the request as the form 'creator' ''' form.instance.user = self.request.user return super().form_valid(form) I'm trying to access the post int by overwriting get_object with return models.objects.get(id=self.kwargs['post']) , and the setting it to the comment model field in the form_valid with form.instance.post = self.post as I did … -
Why is my formset with filefield always valid?
I have an inlineformset_factory containing a filefield. Every time I submit the form, whether or not a file is attached, the formset is_valid() always returns True. I have set the blank parameter as False for the filefield. When I test the same formset by replacing the filefield with a charfield or just by the form itself (without inlineformset_factory), the code works as expected. Why is this formset always returning True for is_valid()? # models.py class Author(models.Model): author = models.CharField(max_length=128) description = models.CharField(max_length=1000) class BooksFile(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) books_file = models.FileField(blank=False) # forms.py class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('author', 'description') class BooksFileForm(forms.ModelForm): class Meta: model = BooksFile fields = ('books_file',) BooksFileFormSet = forms.inlineformset_factory( Author, BooksFile, form=BooksFileForm, fields=('books_file',), extra=1, can_delete=False, can_order=False ) # views.py class CreateAuthorView(CreateView): template_name = "author_create.html" model = Author form_class = AuthorForm def get_context_data(self, **kwargs): context = super(CreateAuthorView, self).get_context_data(**kwargs) if self.request.POST: form = self.get_form(self.form_class) context["books_file"] = BooksFileFormSet( self.request.POST, self.request.FILES, instance=form.instance ) else: context["books_file"] = BooksFileFormSet() return context def form_valid(self, form): context = self.get_context_data() books_file = context["books_file"] print(form.data.get("author")) print("books_file.is_valid()", books_file.is_valid()) # ***This always prints True*** return redirect(self.get_success_url()) def get_success_url(self): return reverse("author_list") # author_create.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div> {{ form }} </div> <div> … -
How can I combine three inputs into one variable and use it to fetch data from a database using Django?
all! I am working on my first Django project and learning a lot along the way. So far, I have set up a very simple website and am having trouble with the next steps. Through this project, I am hoping to achieve a website that provides users with reliable resources based on how they answer the three questions they are asked. Website Explanation: The user opens the website and is prompted to click a button to go to the first step. The first step asks the user to choose the subject they would like a resource on (for now, all of the listed subjects are related to cooking). Then, they choose their level of expertise (beginner, intermediate, advanced). Finally, they choose a preferred medium for their resource (article/blog, video, book). Based on the subject, their level of expertise, and their preferred medium, the last page will give the user a resource that is retrieved from a linked database. Where I Am Stuck: So far, I have created five pages (home page, one page for each question, and a results page) and have set up the choices for each question. Now, I am having trouble finding a way to combine the … -
Django sum() function
I have a Cart model and I want to sum all the item values. I can successfully sum all the items subtotal individually but when I try to make the Grand Total I get the following error maximum recursion depth exceeded while getting the str of an object This is my model class class CartItem(models.Model): ... def get_cart_item_subtotal(self): meal_price = self.meal.price if self.options: options = self.options.price else: options = 0 if self.ingredients: ingredients = sum( [ingredient.price for ingredient in self.ingredients.all()] ) else: ingredients = 0 return (meal_price + options + ingredients) * self.quantity class Cart(models.Model): items = models.ManyToManyField("CartItem", blank=False) ... def get_cart_subtotal(self): return sum([item.get_cart_item_subtotal for item in self.items.all()]) If possible I would like to keep the sum in the Cart model since then I have to check if the minimum order is met. Thanks in advance for any help which could be provided -
Question about overriding the __init__ method of models.Model in Django
I created an app to keep track of inventory and modify it with a form. The updated_by field changes to the current logged in user when the update button is pressed. The only issue is that every instance's 'updated_by' field is changing. I great post suggested to override the init method of the models.Model. I am both new to django and python and do not what to write in my conditional. Also if someone could explain or reference what is going on i would be very greatful. Views.py def inventory_update(request): title = 'Update Inventory' UserInventoryFormset = modelformset_factory(Inventory, form=InventoryUpdateForm, extra=0) if request.method == 'POST': formset = UserInventoryFormset(request.POST) if formset.is_valid(): for form in formset: updated = form.save(commit=False) updated.updated_by = request.user updated.save() else: formset = UserInventoryFormset() context = {'formset': formset, 'title': title } return render(request, 'main/inventory_form.html', context) Models.py class Inventory(models.Model): item = models.CharField(max_length=50, unique=True) stock = models.IntegerField() par = models.IntegerField() date_updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.item __original_stock = None __original_par = None __original_updatedBy = None def __init__(self, *args, **kwargs): super(Inventory, self).__init__(*args, **kwargs) self.__original_par = self.par self.__original_stock = self.stock self.__original_updatedBy = self.updated_by def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.par != self.__original_par or self.stock != self.__original_stock: # what goes …