Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery is not consuming with two tasks together
sorry, I am a rookie to celery. I have 3 celery snippet as follows: first define the Task Class in celery_tasks.tasks.py import celery class LoggerDefine(celery.Task): name = 'message-logger' def run(self, payload): pass class PerformanceMeasureDefine(celery.Task): name = 'performance-logger' def run(self, payload, elapseTime):): pass then implement the methods in from consumers.logger import django django.setup() from log_models.models import Level_logs from django.conf import settings from common_functions.logger import * from celery_tasks.tasks import LoggerDefine, PerformanceMeasureDefine class LoggerImpl(LoggerDefine): def run(self, payload): fmt1 = 'Message body: {}' print("-------------------------------- log persistor consuming --------------------------------") Level_logs.objects.create( level=payload.get(LEVEL), date_time=payload.get(DATETIME), file_name=payload.get(FILENAME), line_number=payload.get(LINE_NUMBER), function_name=payload.get(FUNCTION), payload=payload.get(PAYLOAD), ) return fmt1.format(payload) class PerformanceMeasureImpl(PerformanceMeasureDefine): def run(self, payload, elapseTime): fmt1 = 'Message body: {}' print("-------------------------------- performance consuming --------------------------------") print("payload = ", payload) print("elapseTime = ", elapseTime) return fmt1.format(payload) finally, I instantiate them as two consumers from consumers.logger import LoggerImpl, PerformanceMeasureImpl from celery_tasks.utils import create_worker_from logger, _ = create_worker_from(LoggerImpl) logger.worker_main(["worker", "-c", "2"]) performance_measure, _ = create_worker_from(PerformanceMeasureImpl) performance_measure.worker_main(["worker", "-c", "2"]) then it is not working, I tried to comment out performance_measure and leave only logger like: from consumers.logger import LoggerImpl, PerformanceMeasureImpl from celery_tasks.utils import create_worker_from logger, _ = create_worker_from(LoggerImpl) logger.worker_main(["worker", "-c", "2"]) #performance_measure, _ = create_worker_from(PerformanceMeasureImpl) #performance_measure.worker_main(["worker", "-c", "2"]) then logger works properly. I also tried comment out logger and leave … -
Django ORM - 'annotate' and 'order_by' doesn't seem to work equivalently to 'GROUP BY' and 'ORDER BY'?
Summary: ordered_tags = tagged_items.annotate(freq=Count('tag_id')).order_by('-freq') for i in ordered_tags: print(i.tag_id, i.tag, i.freq) This does not work equivalently to GROUP BY tag_id ORDER BY COUNT(tag_id) DESC. Why? Using Django ORM, I am trying to do something like: SELECT tag_id, COUNT(tag_id) AS freq FROM taggit_taggeditem WHERE content_type_id IN ( SELECT id FROM django_content_type WHERE app_label = 'reviews' AND model IN ('problem', 'review', 'comment') ) AND ( object_id = 1 OR object_id IN ( SELECT id FROM review WHERE problem_id = 1 ) OR object_id IN ( SELECT c.id FROM comment AS c INNER JOIN review AS r ON r.id = c.review_id ) ) GROUP BY tag_id ORDER BY freq DESC; So here's what I have contrived: querydict_for_content_type_id = { 'current_app_label_query' : Q(app_label=ReviewsConfig.name), 'model_name_query' : Q(model__in=['problem', 'review', 'comment']) } # used in content_type_query query_for_content_type_id = reduce(operator.__and__, querydict_for_content_type_id.values()) # Query relevant content_type from TaggedItem model. content_type_query = Q(content_type_id__in=ContentType.objects.filter(query_for_content_type_id)) # Query relevant object_id from TaggedItem model. object_query = Q(object_id=pk) | Q(object_id__in=problem.review_set.all()) for review in problem.review_set.all(): object_query |= Q(object_id__in=review.comment_set.all()) tagged_items = TaggedItem.objects.filter(content_type_query&object_query) # JOIN Tag # tags = tagged_items.select_related('tag') # GROUP BY freq ORDER_BY freq DESC; ordered_tags = tagged_items.annotate(freq=Count('tag_id'))#.order_by('-freq') for i in ordered_tags: print(i.tag_id, i.tag, i.freq) Django ORM doesn't work as intended. Calling distinct method on ordered_tags … -
Django ManyToMany relationships not being saved in initial create, but saved on update - how to fix?
en mi archivo models.py tengo dos clases Curso y Carreras, en el primero de ellos tengo un campo que es una relacion del tipo ManyToMany con el segundo. El problema que tengo es que cuando voy a crear un objecto para el modelo Curso y hago las relaciones pertinentes estas no son guardadas en la base de datos, sin embargo cuando ese objeto que creo le quiero modificar la relacion ManyToMany es cuando si guarda en la base de datos la relacion, pero la que guarda e la introduje inicialmente cuando creaba el objeto. lo que quiero es que una vez creado el objeto esta relacion sea guardada correctamente y no se quede asi sin mas en el aire, porque de ella depende un calculo que hago posteriormente -
i am unable to proceed in the cousera course which is django specilization due to some errors
this is the error that I have received I was trying to reload in python everybody as I successfully created my virtual environment, but when I reload in the web, I am getting an error that I attached in the imageries would be thankful if someone help me to proceed this problem. -
Error running multiple Django production sites on Ubuntu 22.04/apache2
I am trying to host two virtual django sites on a ubuntu/apache2 setup. Site number one works great. I mirrored the settings for site number two but I am getting error: [Fri Jun 02 18:27:24.041306 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Shutdown requested 'aww.exodustec.com'. [Fri Jun 02 18:27:24.048138 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Stopping process 'aww.exodustec.com'. [Fri Jun 02 18:27:24.049208 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Destroying interpreters. [Fri Jun 02 18:27:24.049751 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): Destroy interpreter 'aww.exodustec.com|'. [Fri Jun 02 18:27:24.050397 2023] [wsgi:info] [pid 22018:tid 140106201364352] mod_wsgi (pid=22018): End interpreter 'aww.exodustec.com|'. [Fri Jun 02 18:27:27.588319 2023] [wsgi:info] [pid 22145:tid 140106201364352] mod_wsgi (pid=22145): Attach interpreter ''. [Fri Jun 02 18:27:27.668319 2023] [wsgi:info] [pid 22145:tid 140106201364352] mod_wsgi (pid=22145): Adding '/aww/src/' to path. [Fri Jun 02 18:27:55.908422 2023] [wsgi:info] [pid 22145:tid 140106168383040] mod_wsgi (pid=22145): Create interpreter 'aww.exodustec.com|'. [Fri Jun 02 18:27:55.913683 2023] [wsgi:info] [pid 22145:tid 140106168383040] mod_wsgi (pid=22145): Adding '/aww/src/' to path. [Fri Jun 02 18:27:55.914667 2023] [wsgi:info] [pid 22145:tid 140106168383040] [remote] mod_wsgi (pid=22145, process='aww', application='aww.exodustec.com|'): Loading Python script file '/aww/src/awwcollectables/wsgi.py'. [Fri Jun 02 18:27:56.567455 2023] [wsgi:error] [pid 22145:tid 140106168383040] [remote] mod_wsgi (pid=22145): Failed to exec Python script file '/aww/src/awwcollectables/wsgi.py'. [Fri Jun 02 18:27:56.567620 … -
Connection reset by peer on file upload if JWT expires
We have a django app and it supports a file upload request. The entire upload comprises multiple requests. We are authenticating with JWT and we have logic to handle a 401 and in that case use the refresh token to get a new access token and resend the failed request. However if the token expires between 2 requests of the same upload the 401 response never makes it to the client. In the logs I found that before nginx gets the response we get this error: 2023/06/02 16:23:11 [error] 1924925#1924925: *75 readv() failed (104: Connection reset by peer) while reading upstream, client: xx.xx.xx.xx, server: example.com, request: "POST /api/upload/ HTTP/1.1", upstream: "uwsgi://unix:///bar/foo/our_app/app.sock:", host: "", referrer: "http://example.com:8082/" This causes the client to get an empty response body and the browser throws a ERR_CONTENT_LENGTH_MISMATCH error. The entire upload takes under 10 minutes and we have all the timeouts set to 100 minutes: uwsgi_read_timeout 6000; uwsgi_connect_timeout 6000; uwsgi_send_timeout 6000; send_timeout 6000; proxy_read_timeout 6000; proxy_send_timeout 6000; What is causing the socket to get closed? How can I prevent that? Are there other timeouts I could set? Any logging that I can enable to see why the socket is getting closed? Is there a way to … -
Django model: Query of query or filter of filter
I have 2 models, and on the function, I need to filter in 'x' the users which has the id's equal the id's received. And secondly, I need to filter in another query (let's say 'y'), the description from model Detail, which has the person_id equal to the id's already filtered in 'x'. It's like a filter of a filter, or a query of a query. class Person(models.Model): user = models.ForeingKey(Users, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Detail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) description = models.TextField() def test(request, id_user): x = Person.objects.filter(user_id = id_user) I don't know how to do it. I'm new to Python and Django. It would be something like this: y = Detail.objects.filter(person_id = id_x). But of course, this isn't right. Can someone help me? -
Object of type Product is not JSON serializable django
I have an ecommerce website and every time I try anything it gives me this error Object of type Product is not JSON serializable I've tried everything on stackoverflow, github and everything I could find on google but I didn't find anything and PickleSerializer just broke everything -
ModuleNotFoundError when importing my module and models.py from a Django app
I have an issue with this code import os from parser_main.parser_main.security_values import access_token os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parser_main.parser_main.settings') from parser_main.art_parser_app import models It raises an error ModuleNotFoundError: No module named 'security_values' The script works fine if I remove the line from parser_main.art_parser_app import models But I need both these modules -
Do I need a default authentication system even I know pretty much
I can create user table and use it as a default login activity. I don't have hands on experiance of django's conf.auth. I am using my own login system. I can create session object, can manage session timeout as well . I can delete session whenever logout. I can create a decorator by my own do I still need still go for auth. explain me why and how I can improve my experiance of it. or what else I am missing to dodge default auth and login mechanism -
How to process every line of an output in python django
Sorry if the subject is not clear enough. This is my urls.py in Django: from django.contrib import admin from django.urls import path # imported views from cron import views urlpatterns = [ path('admin/', admin.site.urls), # configured the url path('',views.index, name="homepage") ] This is views.py: from django.http import HttpResponse from subprocess import * import codecs def index(request): with open('/home/python/django/sites.txt', 'r') as file: for site in file: with open('output.html', 'a') as file2: out = run(["ssh", "-o StrictHostKeyChecking=accept-new", "-p1994", f"root@{site}".strip(), "crontab", "-l"], capture_output=True) out = out.stdout out = codecs.decode(out, 'unicode_escape') file2.write(str(f'Server is: <span style=\'font-weight:bold\'>{site.strip()}</span>')) file2.write(str(rf'<p>{out}</p>')) file2.write('\n') with open('output.html', 'r') as new: return HttpResponse(new) This is sites.txt: 1.1.1.1 2.2.2.2 3.3.3.3 This is the output.html in text editor: Server is: <span style='font-weight:bold'>1.1.1.1</span><p>#30 16 * * * /usr/bin/bash /home/backup/ftp 0 0 * * * /usr/bin/bash /home/backup/ftp > /dev/null 2>&1 </p> Server is: <span style='font-weight:bold'>2.2.2.2</span><p>#30 16 * * * /usr/bin/bash /home/backup/ftp 0 0 * * * /usr/bin/bash /home/backup/ftp > /dev/null 2>&1 </p> Server is: <span style='font-weight:bold'>3.3.3.3</span><p>#30 16 * * * /usr/bin/bash /home/backup/ftp 0 0 * * * /usr/bin/bash /home/backup/ftp > /dev/null 2>&1 </p> I know this HTML format is not correct to show properly in web, but I don't know how to make it better so that … -
Should I use regular SQL instead of an ORM to reduce bandwith usage and fetching time?
I'm building a ethereum explorer for fun with django ORM (never used it before). here is a part of my schema : class AddressModel(models.Model): id = models.BigIntegerField(primary_key=True) first_seen = models.DateTimeField(db_index=True) addr = models.CharField(max_length=42, db_index=True, on_delete=models.PROTECT) is_contract = models.BooleanField() is_token = models.BooleanField() is_wallet = models.BooleanField() class BlockModel(models.Model): id = models.BigIntegerField(primary_key=True) number = models.BigIntegerField() status = models.CharField(max_length=20) timestamp = models.DateTimeField(db_index=True) epoch_proposal = models.IntegerField() slot_proposal = models.IntegerField() fee_recipient = models.ForeignKey(AddressModel, on_delete=models.PROTECT) block_reward = models.BigIntegerField() total_difficulty = models.CharField(max_length=100) size = models.IntegerField() gas_used = models.BigIntegerField() gas_limit = models.BigIntegerField() base_fee_per_gas = models.BigIntegerField() burnt_fee = models.BigIntegerField() extra_data = models.TextField() hash = models.CharField(max_length=66) parent_hash = models.CharField(max_length=66) state_root = models.CharField(max_length=66) withdrawal_root = models.CharField(max_length=66) Nonce = models.CharField(max_length=20) # you can do address_model_instance.transactionmodel_set.objects.all() since there is a FK in Transaction model class TransactionModel(models.Model): id = models.BigIntegerField(primary_key=True) hash = models.CharField(max_length=66) block = models.ForeignKey(BlockModel, on_delete=models.PROTECT) from_addr = models.ForeignKey('AddressModel', related_name='from_addr', on_delete=models.PROTECT) to_addr = models.ForeignKey('AddressModel', related_name='to_addr', on_delete=models.PROTECT) input = models.TextField() is_valid = models.BooleanField() What concerns me here is that if I want to retrieve every transaction related to a specific from_addr it will also retrieve the bloc data in the returned object, if the from_addr has 10K transaction that is 10K block data that I don't need. with regular SQL I would only get a … -
django-nested-admin nested model initial values
I've been working with django-nested-admin for editing admin models that have foreign key relationships to other tables. Frankly it's beautiful. I love it. But I have a pair of models here I'm having a bit of trouble with. I have a Chapter, representing a chapter of a club. Each chapter has a one or more useful links to things like their web page or wiki articles or whatever. Both classes have a field of 'registrar' which is the user that created them. Basically whoever was logged in to the system when the instance was created. For Chapter, this went fairly easily. I just added def get_changeform_initial_data(self, request): get_data = super(ChapterAdmin, self).get_changeform_initial_data(request) get_data['registrar'] = request.user.pk return get_data To the ChapterAdmin class. It pre-populates just fine. But when I tried to do the same with the UsefulLinksInline, that ChapterAdmin uses. I've been down a rabbit hole of googling and break-point surfing trying to figure out how to pre-populate the UsefulLink class's registrar field with the current user. In UsefulLinksInline, if I remove the registrar field from the fields=() list, I get an error stating that the null constraint on registrar was being violeted. If I leave it in, however, the Registrar combo … -
Where to host Django project files on deployment server
New to Django here. I have developed a minimum working django website with Postgres as database back-end and nginx/gunicorn as web server on Ubuntu linux. Currently all the files are on my laptop in ~/workspace/djangoapp/src$ in my home directory. I want to now deploy the project to GCP. Which directory, on the production server, the files would go in? It can't be my home directory on the production server. Shouldn't they go in one of the system directories like /opt? -
How to prevent auto-filling of other Django forms when updating a specific form and how to make them not required to fill?
I have some Django forms each one with an update button that I'm rendering on a template. When I try to submit something through the button I can't because It says I have to fill every form. I also run into the problem that when I try to update a form the value in the other forms changes and auto-fills. forms.py class ImageUpdateForm(forms.ModelForm): image = forms.ImageField(widget=forms.FileInput) class Meta: model = User fields = ['image', 'mnemonic'] def clean(self): super(ImageUpdateForm, self).clean() mnemonic = self.cleaned_data.get('mnemonic') if mnemonic != self.instance.mnemonic: self._errors['mnemonic'] = self.error_class([ 'The mnemonic is wrong!']) return self.cleaned_data class PasswordUpdateForm(forms.ModelForm): class Meta: model = User fields = ['password', 'mnemonic'] def clean(self): super(PasswordUpdateForm, self).clean() mnemonic = self.cleaned_data.get('mnemonic') if mnemonic != self.instance.mnemonic: self._errors['mnemonic'] = self.error_class([ 'The mnemonic is wrong!']) return self.cleaned_data class PinUpdateForm(forms.ModelForm): class Meta: model = User fields = ['pin', 'mnemonic'] def clean(self): super(PinUpdateForm, self).clean() mnemonic = self.cleaned_data.get('mnemonic') if mnemonic != self.instance.mnemonic: self._errors['mnemonic'] = self.error_class([ 'The mnemonic is wrong!']) return self.cleaned_data class MnemonicUpdateForm(forms.ModelForm): class Meta: model = User fields = ['mnemonic', 'password'] def clean(self): super(MnemonicUpdateForm, self).clean() password = self.cleaned_data.get('password') if password != self.instance.password: self._errors['password'] = self.error_class([ 'The password is wrong!']) return self.cleaned_data views.py def UpdateView(request): user = request.user if request.method == 'POST': mnemonic_form = … -
Implementing Name Synchronization and Money Transfers in Transactions Model with Account Number Input
I have the following models in my Django application: class Transaction (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) account_number = models.IntegerField() name = models.CharField(max_length=50) amount = models.DecimalField() created_on = models.DateTimeField() class Wallet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) account_balance = models.DecimalField(default=0) class AccountNum(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) account_number = models.IntegerField() slug = models.SlugField(unique=True) I want to implement a feature where the name field in the Transactions model gets synchronized with the account owner's name based on the provided account_number input. Additionally, I want to enable money transfers using the current user's wallet and the specified amount in the Transactions model. To provide some context, I have a post-save signal generate_account_number which generates a random 6-digit account number and creates an AccountNum object for a newly created user. What are some recommended techniques or approaches to achieve this synchronization of the name field with the account owner's name and enable money transfers using the wallet model and specified amount in the Transaction model? -
ImportError: PyO3 modules may only be initialized once per interpreter process
I am working on a Django project which includes DRF. The application is dockerized. Everything was working fine then suddenly I got the following error in my logs and I am completely clueless how it arrived patients | [uWSGI] getting INI configuration from /patients/src/_settings/local-test/uwsgi.ini patients | [uwsgi-static] added mapping for /static/ => /static/ patients | *** Starting uWSGI 2.0.21 (64bit) on [Fri Jun 2 13:59:34 2023] *** patients | compiled with version: 10.2.1 20210110 on 02 June 2023 10:11:18 patients | os: Linux-5.19.0-42-generic #43~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Apr 21 16:51:08 UTC 2 patients | nodename: 9be86066078d patients | machine: x86_64 patients | clock source: unix patients | pcre jit disabled patients | detected number of CPU cores: 8 patients | current working directory: /patients/src patients | detected binary path: /usr/local/bin/uwsgi patients | uWSGI running as root, you can use --uid/--gid/--chroot options patients | setgid() to 33 patients | *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** patients | chdir() to /patients/src patients | your memory page size is 4096 bytes patients | detected max file descriptor number: 1048576 patients | building mime-types dictionary from file /etc/mime.types...1476 entry found patients | lock engine: pthread robust … -
Advice for developing a ticket selling platform for events
I'm a junior developer with little experience from Argentina. I have done courses in JavaScript, CSS, React, python, django and SQL. I want to develop a platform for selling tickets for events. In the beginning, it will be basic to show in my portfolio but I want to continue developing until it gets fully functional and advanced to be used as a real business. The platform need user registration with many profiles like “Promoters” who can create events, manage them, take statistics, “Final users” who can buy tickets from all the events already created, see all the bought tickets, transfer tickets to another users and “Sellers” who can be assigned to events by promoters to sell tickets through a personalized link (which can be traceable). When users log-in there should be a kind of a dashboard with all the functions mentioned before (and more). The home page will be basic, with cards of all the uploaded events. Before I start the project, I want to be sure that I'm using the correct technologies and that everything is scalable because like I said before the mid-term objective is that it gets real. I was thinking of using React and maybe Next.JS … -
How can we host a django project using aws, s3 and dynamo dB
Help me to deploy and host a Django project on AWS using S3 and DynamoDB without running any codes manually, how to set up an S3 bucket to store static files, configure Django settings to use the S3 bucket for static files, set up a DynamoDB table for data storage, configure Django settings to use DynamoDB as the database, deploy the Django project using AWS Elastic Beanstalk, and ensure 24/7 availability of the hosted project? created a python django project.I want to host using aws, s3 and dynamo db.Already created an aws account -
Python show output of remote SSH command in web page in Django
I have a simple Django app to show the output of an SSH remote command. views.py: from django.http import HttpResponse from subprocess import * def index(request): with open('/home/python/django/cron/sites.txt', 'r') as file: for site in file: # out = getoutput(f"ssh -o StrictHostKeyChecking=accept-new -p1994 root@{site} crontab -l") out = run(["ssh", "-o StrictHostKeyChecking=accept-new", "-p1994", f"root@{site}".strip(), "crontab", "-l"]) return HttpResponse(out) urls.py: from django.contrib import admin from django.urls import path # imported views from cron import views urlpatterns = [ path('admin/', admin.site.urls), # configured the url path('',views.index, name="homepage") ] sites.txt: 1.1.1.1 2.2.2.2 3.3.3.3 The issue is when I run localhost:5000, I see this: CompletedProcess(args=['ssh', '-o StrictHostKeyChecking=accept-new', '-p1994', 'root@3.3.3.3', 'crontab', '-l'], returncode=0) While I should see something like this: * * * * * ls * * * * * date * * * * * pwd I tried with both run and getoutput, but they either don't connect or the output is shown in terminal only. How can I run this and show the output in the webpage? -
DJANGO Get First, Second and Thrid most found Value in a Model
I got a Dashboard model that is filled by a schduled Job. dashboard model class dashboard(models.Model): topvul1=models.IntegerField(default=0) topvul2=models.IntegerField(default=0) topvul3=models.IntegerField(default=0) I want to show the most found, second most found and third most found VID from the clientvul model. And fill it once per Day to my dashboard model. clientvul model class clientvul(models.Model): client= models.ForeignKey(client, on_delete=models.CASCADE) vid=models.ForeignKey(vul, on_delete=models.CASCADE) path=models.CharField(max_length=1000) product=models.CharField(max_length=1000) isactive=models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint( fields=['client', 'VID'], name='unique_migration_host_combination' # legt client und VID als Primarykey fest ) ] -
Why does django url tag with argument work in VS Code but not Visual Studio 2019?
I have a simple django app built in Visual Studio 2019 using python. I am trying to use a url template tag to open a record in a form on another page in order to update that record but it always returns: 'reverse not found...' This is the template tag (uform.id is the argument): <td><a href="{% url 'app:form-update' uform.id %}">{{ obj.form_name }}</a></td> The url paths: from django.urls import path from app import views app_name = 'app' urlpatterns = [ path('', views.home, name='home'), path('form-create/', views.create_form, name='form_create'), path('form-update/<str:pk>/', views.updateForm, name='form-update'), ] The view: def updateForm(request, pk): uform = Forms.objects.get(id=pk) form = FormRegisterForm(instance=uform) if request.method == 'POST': form = FormRegisterForm(request.POST, instance=uform) if form.is_valid(): form.save() return redirect('app:form_register') context = {'form': form} return render(request, 'app/form_create.html', context) When I replace the id argument in the url template tag with an id such as 19, it works without error. This suggests the syntax of the url template tag is wrong, however the same syntax works in other apps I have created using VS Code. I don't understand why it won't work in Visual Studio 2019. Any help would be greatly appreciated. -
Django admin interface custom logo not found 404
I have just started with django I created a new project and installed Django admin-interface also installed the bootstrap theme then tried to upload my logo in the theme settings but the logo doesn't appear , also I get this error in the terminal "GET /admin-interface/logo/logo.png HTTP/1.1" 404 2164 I haven't changed anything in the default code -
How to specify qantity of multiple model objects by form
So, im making my first pet project with django and im struggling with cart in my store. Many guides are doing quantity in cart by buttons, but i want to enter a value by number form like this: enter image description here So, i`ve come up with something like this: views.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items forms = [] form = QuantityForm() if request.method == 'POST': for item in items: if item.quantity <= 0: item.delete() else: item_id = OrderItem.objects.get(id=item.id) form = QuantityForm(request.POST, instance=item_id, initial={'quantity':item.quantity}) else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} cartItems = order['get_cart_items'] context = {"items": items, "title": "Cart ◦ Shoppica", "order": order, "form":form, 'cartItems': cartItems} return render(request, 'store/cart.html', context) forms.py class QuantityForm(ModelForm): class Meta: model = OrderItem fields = ['quantity'] cart.html {% for item in items %} <tr class="even"> <td valign="middle"><input type="checkbox" /></td> <td valign="middle"><a href="{% url 'Product' item.product.slug %}"><img src="{{ item.product.photo_front.url }}" width="60" height="60" alt="{{ item.product.title }}" /></a></td> <td valign="middle"><a href="{% url 'Product' item.product.slug %}"><strong>{{ item.product.title }}</strong></a></td> <td valign="middle">{{ form.quantity }}</td> <td valign="middle">${{ item.product.price }}<span class="s_currency s_after"> </span></td> <td valign="middle">${{ item.get_total }}<span class="s_currency s_after"></span></td> </tr> {% endfor %} But when post form all … -
I created a file using "django-admin startproject <filename>", but can't find it on my system
I used the following commands in this process-- pip install virtualenv cd desktop virtualenv env env\Scripts\activate pip install django django-admin startproject But i cant find the file on my desktop even though it got created successfully.