Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a shopping cart in Django Rest Framework
I want to implement shopping cart in Django Rest Framework. I store information about the shopping cart inside the models. I don't want to use a session for this and I want to save it in the database. users must be logged in to create and add products to the cart. But I want them to be able to add the product to the cart without logging in. I would be very grateful if you could guide me. Thanks My Model : class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() My View: class AddToCartApi(APIView): serializer_class = AddToCartSerializer permission_classes = [IsAuthenticated] def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user_id = request.user.id data = serializer.validated_data Cart.objects.create( user_id=user_id, product_id=data['product_id'], quantity=data['quantity'], ) return Response(....) -
Trying to understand how sql query is generated by django framework?
I am using django debugger in pycharm to see how ORM does the magic. I have a simple model and a very basic query. Model.objects.get(id=1). The first step in click (debugger) takes me to django.db.models.manager.py. The get method of ManagerDescriptor class in this module is called. Then the pointer goes to django.db.models.query and as soon as the init method is complete the query is generated out of nowhere. Where did the query select Model.name, Model.age ... from Model come from? I am sure I am missing something here, if anyone knows the internal working or can direct me to any tutorials on this please guide me. Thank you Model.objects.get(id=1) -
Does not get the url from reverse with DRF DefaultRouter
I am trying to get the urls for writing the tests using the reverse function. But I'm getting the error Errors :- Reverse for 'notes' not found. 'notes' is not a valid view function or pattern name. urls.py file from django.contrib import admin from django.urls import path, include from core import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register("notes",views.NoteModelViewSet) urlpatterns = [ path("",include(router.urls)), ] and test.py file def test_get_all_notes_path(self): url = reverse('notes') response = self.client.get(url) self.assertEqual(response.status_code, 200) I'm getting error for line url = reverse('notes') that I have mentioned above. My Model and routes everything working fine. Only I'm not get the url in reverse funtion. -
In Django Template how to get all grand child object using single object?
I have a models like : class Invoice(models.Model): created_date = models.DateTimeField(auto_now_add=True) class Sell(models.Model): invoice = models.OneToOneField(Invoice, on_delete=models.CASCADE) class SellItems(models.Model): sell = models.ForeignKey( Sell, related_name='sell_item', on_delete=models.CASCADE) item = models.CharField(max_length=200) In template, how can I get SellItems using Invoice object. -
NameError at /register name 'random_key' is not defined
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/register Django Version: 4.1.3 Python Version: 3.11.0 Installed Applications: ['ritpay', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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 (most recent call last): File "C:\Users\Manoj\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Manoj\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Manoj\Desktop\ritconnwallet\ritpay\views.py", line 84, in register private_key = random_key(private_key) Exception Type: NameError at /register Exception Value: name 'random_key' is not defined import random_key.. I am currently developing a blockchain wallet with python. My register page is not loading and i am not getting any public address and i cannot register any new user. When i load the register.htm , the page says random_key is not defined. -
How can i create unique together based on a field in Django
This is my code class Address(models.Model): customer = models.ForeignKey(Customer, related_name='addresses', on_delete=models.CASCADE) lat = models.FloatField() long = models.FloatField() class Meta: constraints = [ UniqueConstraint(fields=['lat', 'long'], name='lat_long_unique') I want the field lat long unique together but just with the same customer, how can i achieve that? -
save data to database from multiple APIs django
there are over 20 APIs that are differentiated by name query string argument at the end of them like:(https/.../?name=121). now i am just hard coding them in my code for example: response1 = requests.get ..... response2 = requests.get ..... with this approach i should write 20 lines .is there any better way to do this? note: i need all these APIs at the same time cause they get updated every 5 minutes and i should store them into database separately -
How to save Django Form and Formset at the same time
I have page in which I use a form and formset at the same time. The form is for the thesis information and the formset if for the author. This the code in my models.py ` class thesisDB(Model): thesis_id = models.AutoField(primary_key=True, blank=True, null=False) title = models.CharField(max_length=200, blank=True, null=True, unique=True) published_date = models.DateField(blank=True, null=True) pdf = models.FileField(upload_to='pdf/', blank=True, null=True ,validators=[FileExtensionValidator(['pdf'])],) course = models.ForeignKey(ColCourse, default=None, on_delete=models.CASCADE, verbose_name='Course') tags = TaggableManager() date_created = models.DateField(auto_now_add=True, blank=True, null=True ) uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None) published_status = models.CharField(max_length=10, choices= THESIS_DECISION, default='Pending') abstract = models.TextField(blank=True, null=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') reason = models.TextField(blank=True, null=True) slug = models.SlugField(max_length = 250, null = True, blank = True) def save(self, *args, **kwargs): self.title = self.title.title() #self.author = self.author.title() self.slug = slugify(self.title + "-" + self.author + "-" + str(self.published_date)) super().save(*args, **kwargs) class Meta: db_table = 'thesis_storage' initial_validator = RegexValidator('[A-Z]+.', 'Initial must contain period') class Authors(Model): thesis = models.ForeignKey(thesisDB, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, blank=True, null=True) last_name = models.CharField(max_length=200, blank=True, null=True) middle_initial = models.CharField(max_length=2, blank=True, null=True, validators=[initial_validator]) ` This is the code in my forms.py ` class AuthorForm(forms.ModelForm): class Meta: model = Authors exclude = () widgets = { 'first_name': forms.TextInput(attrs= {'placeholder': 'First Name', 'class':'form-control', 'required': 'required'}), 'last_name': forms.TextInput(attrs= {'placeholder': 'Last … -
{% load gTTS %} in template make mistake 'gTTS' is not a registered tag library
hi everybody i make a quiz with django i want to add text to speech advantage with google i recive erroe mesaage gTTS' is not a registered tag library when i write in template {% load gTTS %} <audio src="{% say 'en-us' {{question.question}} %}" controls i install gTTS and i add aline in setting.py INSTALLED_APPS = [ 'gTTS', i make the application without any code i depend in this page enter link description here why did not work -
Coverage is showing different for full pytest and single app in django using pytest
I have created a project in Django, and I'm writting testcases in pytest. Now, to use coverage I generally use cmd coverage run -m pytest. And to check coverage for specific app, i report/create html files with coverage html , so this will create html files with red and green markers. Recently, I am experementing with different combinations of configurations of coverage and pytest, and found that when run full pytest with coverage like coverage run -m pytest it will not cover all lines, and mark some lines as missing which is actually running while pytest. But when I use pytest with some argument with coverage like coverage run -m pytest accounts , it is covering all perfectly and not showing missing file as I expected. I have tried running whole project with coverage run -m pytest and then run coverage html to see in browser. I got all file's coverage, and to see coverage of specific app for example restaurant , i searched in top right search box and its showing as below. Full Pytest Coverage Full pytest coverage with searched result Now, I have to run coverage for specific app so i can do it like coverage run … -
Trying to run a app in vs code in ubuntu using django, and getting connection error at / (newbie here)
made a app and project using django in vs code and used the covid9api also i am using ubuntu in oracle vm ConnectionError at / HTTPSConnectionPool(host='api.covid9api.com', port=443): Max retries exceeded with url: /countries (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f306d7cca90>: Failed to establish a new connection: [Errno -2] Name or service not known')) Request Method: GET Request URL: http://127.0.0.1:6000/ Django Version: 4.1.4 Exception Type: ConnectionError Exception Value: HTTPSConnectionPool(host='api.covid9api.com', port=443): Max retries exceeded with url: /countries (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f306d7cca90>: Failed to establish a new connection: [Errno -2] Name or service not known')) Exception Location: /usr/lib/python3/dist-packages/requests/adapters.py, line 516, in send Raised during: newapp.views.home Python Executable: /usr/bin/python3 Python Version: 3.10.6 Python Path: ['/home/void/python/newproject/sports', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/void/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Mon, 19 Dec 2022 07:16:23 +0000 [this is the error](https://i.stack.imgur.com/yNWHs.png) -
how to successfully start the server in django?
Whenever I put the command "python manage.py runserver" it through an error. from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (C:\JavaScript\DR_BRO\backend\venv\Lib\site-packages\django\utils\encoding.py) I was trying to run the server in Django. But it's thorough an error like from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (C:\JavaScript\DR_BRO\backend\venv\Lib\site-packages\django\utils\encoding.py) -
Django is asking to delete column, which does not even exists
I tried applying migrations, but django ask me to delete a column which does not exist. Please help The error which i get is - OperationalError at /admin/location/location/ (1054, "Unknown column 'location_location.id' in 'field list'") models.py class Location(models.Model): city = models.CharField(max_length=255) state = models.CharField(max_length=255) country = models.CharField(max_length=255) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) views.py def add_location(request): if request.method == 'POST': form = LocationForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = LocationForm() return render(request, 'add_location.html', {'form': form}) admin.py from django.contrib import admin from .models import Location # Register your models here. admin.site.register(Location) I tried using migrations --fake but it made it even worse. Please help me out. this is urgent :( -
cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed on Amazon Linux 2
I am trying to upload my project on AWS and while deploying it via ElasticBeanStalk I get the follwing error: cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed The project was already deployed on AWS and is working without any problem, there are no changes in .ebextensions files as well db-migrate.config: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true Error stack: 2022-12-19 06:16:50,685 [INFO] Running configSets: Infra-EmbeddedPostBuild 2022-12-19 06:16:50,688 [INFO] Running configSet Infra-EmbeddedPostBuild 2022-12-19 06:16:50,691 [INFO] Running config postbuild_0_Trakkia_al2 2022-12-19 06:16:53,613 [ERROR] Command 01_migrate (source /var/app/venv/*/bin/activate && python3 manage.py migrate) failed 2022-12-19 06:16:53,614 [ERROR] Error encountered during build of postbuild_0_Trakkia_al2: Command 01_migrate failed Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 576, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 276, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed 2022-12-19 06:16:53,617 [ERROR] -----------------------BUILD FAILED!------------------------ 2022-12-19 06:16:53,617 [ERROR] Unhandled exception during build: Command 01_migrate failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata).build(configSets, self) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 564, in build self.run_config(config, worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 576, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 276, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line … -
Hello Please Help Me. I cannot change my company
here is my view please help me # VIEWING THE TABLE def display_companies (request): items = Paginator(Companies.objects.all(),10) page = request.GET.get('page') items = items.get_page(page) nums = "a" * items.paginator.num_pages context = { 'items' : items, 'header' : 'Tashkilotlarni', 'nums' : nums } return render (request, 'home.html', context) # CHANGING THE COMPANY def change_company(request,pk): item = get_object_or_404(Companies, pk=pk) form = CompaniesForm(instance=item) if request.method == "POST": form = CompaniesForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('display_companies') return render(request, 'change_company.html', {'form':form}) HERE IS MY HTML DOCUMENT {% extends 'base.html' %} {% block content %} <div class="container"> <form method="POST"> {% csrf_token %} {% for field in form %} <div class="form-group row"> <label for="id_{{field.STIR}}" class="col-2 col-form-label">{{ field.label }}</label> <div class="col-10"> {{ field }} </div> </div> {% endfor %} <button type="submit" class="btn btn-outline-primary" name="button">O'zgartirish</button> </form> </div> {% endblock %} i click on change company button but nothing changes it renders me to my form not to my home.html page PLEASE HELP ME GUYS. TY VERY MUCH. -
How to make column appear when condition satisfied in jinja2 templating
I have a table, where some column are condition specific. I want if the condition is satisfied only then show the column, otherwise, remove the column. How can i do that with jinja2 templating? -
how to take average of every 10 minutes of a model django
I am using multiple APIs and save them to the database. I have one model called Station(it has datetime field and some other fields ) and every API is for one station. these APIs come from devices that measure some variables and they get updated every 3 minutes. so I wrote a backend task that calls a saveToDB function and stores them in database. for example: station A "some variables" 2022/10/1 13:10 station B "some variables" 2022/10/1 13:10 station A "some variables" 2022/10/1 13:13 station B "some variables" 2022/10/1 13:13 now I need to take average of every station every 10 minutes,2 hours,week, month, year. there are 30 stations. how can i do this? -
Multiple same requests in django rest class based view
I recently began using class-based views in the development of Django rest APIs. While discussing this with a friend, he inquired, "What if I have the same type of request multiple times in the same class?" because, as stated in the rest documentation, I created post functions for POST requests and get functions for GET requests. So, how to write two GET or other types of requests within the same class? -
How can I Deploy a Django App as a .war file or in any other packaged way?
I have a Django Project for which I am trying to find a way to deploy as a .war file. My objective is to not reveal the source code during deployment to De-Couple Django App from Database and deploy as a .war file. This will help me to update the app without re-initializing database. As Jython is not supported for Python3, is there an alternative? I also tried to create an exe through PyIntsaller but it acts as a malicious executable. -
Django crontab can’t connect database(Postgresql) with docker; no such table err
I am using django and postgresql. I am using django-crontab to change the data. It runs well in the local environment, but we use docker to deploy and watch, and I confirmed that when cron runs, we refer to sqlite3. I also made a separate cron container in docker composite and ran it, I am using it incorrectly because I am a beginner. Help me #goods/cron.py from goods.models import Goods def test(): print(Goods.objects.all()) ./docker-compose.yml version: '3.8' volumes: postgres: {} django_media: {} django_static: {} static_volume: {} services: postgres: container_name: postgres image: postgres:14.5 volumes: - postgres:/var/lib/postgresql/data/ environment: - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_DB restart: always nginx: container_name: nginx image: nginx:1.23.2 ports: - "80:80" - "443:443" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - django_media:/media/ - django_static:/static/ depends_on: - asgiserver - backend restart: always django_backend:/app/media backend: host:container container_name: django_backend build: . entrypoint: sh -c "python manage.py migrate && gunicorn handsup.wsgi --workers=5 -b 0.0.0.0:8000" restart: always volumes: - ./:/app/ - /etc/localtime:/etc/localtime:ro - django_media:/app/media/ - django_static:/app/static/ environment: # - DEBUG - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_HOST - POSTGRES_PORT depends_on: - postgres redis: image: redis:5 asgiserver: build: . command: daphne -b 0.0.0.0 -p 8080 handsup.asgi:application volumes: - ./:/app/ restart: always environment: - DEBUG - POSTGRES_DB - POSTGRES_USER - … -
what is the quickest way to style django model form fields one by one
I have ModelForm which renders successfully. this is my forms.py form class UploadPostsForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'description', 'date', 'file'] this is how it looks in templates I want it to look like below using bootstrap5 what is the fastest and easiest way to do it? I have found three ways. adding custom template tags defining styles in each form fields or all at once overriding __init__ method what is the best way to do this? -
Redirect after saving site setting
I'm trying to redirect the user to a custom HTML page after saving a BaseSiteSetting model in Wagtail 4.1.1 I'm not sure how to accomplish this, the BaseSiteSetting inherits from django models.Model which means it's possible to override the save() function but how would I do the actual redirect without having access to the request? Another acceptable solution would be to add an extra button in the CMS by overriding the default BaseSiteSetting HTML template but I can't seem to get that working either, except for ModelAdmin templates. I've opened a stackoverflow question about that here. My view with the custom HTML page: def sync(request): return render(request, "import.html", {"WS_PROTOCOL": settings.WS_PROTOCOL}) My BaseSiteSetting model: @register_setting class AnonymousSuccessStoryImportSetting(BaseSiteSetting): """ Setting for importing anonymous success stories. """ file = models.FileField( upload_to="success_story_imports/%Y/%m/%d/", validators=[validate_file_extension], help_text="Upload a CSV file, then click 'Save' afterwards", blank=True, null=True, ) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Importer" I've looked around for possible solutions, and found some wagtail hooks but these only apply to the Wagtail Page model, for example: after_publish_page. It's unfortunate that there's no hook for standard django models. -
How to set the queryset in forms.Form(ModelChoiceField) for Drop Down city List?
I have set a ForeignKey() for class Town in the models file. Ideally, when I select a state, all towns belonging to this state will be listed in town. #models.py class State(models.Model): state = models.CharField(max_length=50) code = models.CharField(max_length=3) def __str__(self): return self.state class Town(models.Model): town = models.CharField(max_length=50) code = models.CharField(max_length=4) state = models.ForeignKey(State, on_delete=models.CASCADE) def __str__(self): return self.town Now I can only use all() in queryset to display all towns. I feel like I should use filter(), but I can't find a way to do it。 #forms.py class Location(forms.Form): state = forms.ModelChoiceField( required = True, label = "State", queryset = State.objects.all(), widget = forms.Select(attrs = { "class": "form-list-field"} )) town = forms.ModelChoiceField( required = True, label = "Town", queryset = Town.objects.filter( ??? ).order_by('town'), widget = forms.Select(attrs = { "class": "form-list-field"} )) -
Trying to find a way to pass a list to an item in request.POST. How do I do it?
This is my html code in django project: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <script src="{% static 'jquery-3.6.2.min.js' %}" ></script> </head> <body> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <button id="button1" name="action" value="">button2</button> <script> $("#button1").click( function(){ arr = ["one", "two"] $("#button1").attr('value',arr) } ) </script> </form> </body> </html> By clicking the button I run JQuery that assigns an array: arr to button1's value. This is request.POST afterwards: <QueryDict: {'csrfmiddlewaretoken': ['Rws3PVVBVOGsoXm720M5YbuZNTYMin6CxklI78in2PWdrxAYKxw3XqV7cba2xt7P'], 'action': ['one,two']}> Instead of 'action': ['one,two'] I want to get 'action': ['one', 'two'], or 'action': [['one', 'two']] How do I do it? -
Why is Django's client.post nesting arg values in lists?
I'm unit testing my api with Django like this: result = self.client.post( reverse(path), { "arg1":"value" }) Inside the view, I breakpoint. @api_view(["POST"]) def post_arg(request): breakpoint() But when I print the POST data, the values have been added to lists. (Pdb) request.POST { 'arg1': ['value'] } This example only has one arg, but if I add more they are each added to a list. I don't think this happens when my frontend posts data, so why does it here? And is there a way to not have the values added to a list?