Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
two packages require two different python versions on django deployment on centos7?
I'm trying to deploy my django project on Centos 7. While installing pip -r install requirements.txt I got error and I somehow tried to solve it. First of all it is said that asgiref==3.5.0 can't be installed in Python 3.7 below. Default installed python version is 3.6.8. Then I install python 3.7 and asgiref problem is solved, but I got another error on coreschema==0.0.4 (which is in requirements.txt). I upload image below, but looking at pypi I thought that coreschema is not supported on python 3.6 above. If this is the issue, how to solve it? It is possible to install coreschema with pip or pip3, because their python version is below than 3.7 -
Yum Cache failed. Error : amzn2-core/2/x86_64/group_gz FAILED
Can anyone help here when I deploy an EC2 instance on aws when yum makecache: amzn2-core | 3.7 kB 00:00:00 amzn2extra-docker | 3.0 kB 00:00:00 amzn2extra-nginx1 | 3.0 kB 00:00:00 amzn2extra-postgresql11 | 3.0 kB 00:00:00 amzn2extra-python3.8 | 3.0 kB 00:00:00 amzn2-core/2/x86_64/group_gz FAILED https://amazonlinux-2-repos-eu-central-1.s3.dualstack.eu-central-1.amazonaws.com/2/core/2.0/x86_64/da64f79d533a70e6036c814aff5d1e823eeeb815054a7a3785d2d5198ff2eabc/repodata/comps.xml.gz?instance_id=i-08792031e5dac83de&region=eu-central-1: [Errno 14] curl#6 - "getaddrinfo() thread failed to start" Trying other mirror. amzn2-core/2/x86_64/filelists_ FAILED https://amazonlinux-2-repos-eu-central-1.s3.dualstack.eu-central-1.amazonaws.com/2/core/2.0/x86_64/da64f79d533a70e6036c814aff5d1e823eeeb815054a7a3785d2d5198ff2eabc/repodata/filelists.sqlite.gz?instance_id=i-08792031e5dac83de&region=eu-central-1: [Errno 14] curl#6 - "getaddrinfo() thread failed to start" Trying other mirror. amzn2-core/2/x86_64/updateinfo FAILED https://amazonlinux-2-repos-eu-central-1.s3.dualstack.eu-central-1.amazonaws.com/2/core/2.0/x86_64/da64f79d533a70e6036c814aff5d1e823eeeb815054a7a3785d2d5198ff2eabc/repodata/updateinfo.xml.gz?instance_id=i-08792031e5dac83de&region=eu-central-1: [Errno 14] curl#6 - "getaddrinfo() thread failed to start" Trying other mirror. (1/21): amzn2-core/2/x86_64/primary_db | 66 MB 00:00:03 (2/21): amzn2-core/2/x86_64/other_db | 505 B 00:00:00 no mem for new parser Traceback (most recent call last): File "/usr/libexec/urlgrabber-ext-down", line 22, in <module> from urlgrabber.grabber import \ File "/usr/lib/python2.7/site-packages/urlgrabber/__init__.py", line 55, in <module> from grabber import urlgrab, urlopen, urlread File "/usr/lib/python2.7/site-packages/urlgrabber/grabber.py", line 543, in <module> import urllib File "/usr/lib64/python2.7/urllib.py", line 1225, in <module> for a in _hexdig for b in _hexdig) MemoryError Traceback (most recent call last): File "/usr/libexec/urlgrabber-ext-down", line 22, in <module> Traceback (most recent call last): File "/usr/libexec/urlgrabber-ext-down", line 22, in <module> from urlgrabber.grabber import \ File "/usr/lib/python2.7/site-packages/urlgrabber/__init__.py", line 55, in <module> from urlgrabber.grabber import \ File "/usr/lib/python2.7/site-packages/urlgrabber/__init__.py", line 55, in <module> from grabber import urlgrab, urlopen, urlread … -
Fetch ((response) => {response.json()} replacing page with Json in Django App [closed]
I'm calling Fetch in a django app and it's getting the dict that I want, but it ends up replacing my page with the dict. I think I've written something wrong in the fetch call, but I'm not entirely sure cause it's my first time using fetch. Please help! I've been watching tutorials for two days now around Ajax and Fetch! Does anyone know what is happening here? Any help would be greatly appreciated! My page ends up like this after getting the response.json() which is correct cause that's what it's supposed to return as shown here in the views It's just supposed to return that one thing, total_votes .views def vote(request, poopfact_id): ... data = {"total_votes": total_votes} return JsonResponse(data, safe=False) I think the issue is here somewhere, does someone know if I'm missing something? .script fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, } body: JSON.stringify(data) }); .then((response) => { response.json() }); .then((data) => { console.log(data) }); .catch((error) => { console.log(error) }); -
Checking Form Uploading Progress in Django
Is it possible to track the user form upload progress in the current page before browser redirects to the form's actions attribute? In Django's template, I have a form like below; It accepts user data such as name, age and multiple images from input field. If I upload large image here, I need to wait for more time before it redirects to success page. If i can see progress bar or something that confirms the remaining time for form's successful submission page, it will be better {% extends "base.html" %} {% block content %} {% if form.errors %} <p style="color: red;"> Please correct the error{{ form.errors|pluralize }} below. </p> {% endif %} <div data-role="content" style="padding: 15px"> <form action="{% url success %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.errors }} {{ form.non_field_errors }} {{ form.as_table }} <input type="submit" value="Submit" id="Save"> </form> </div> {% endblock %} -
I'm doing a study assignment. when checking, the teacher made a remark, what did he mean?
` I'm doing a study assignment. when checking, the teacher made a remark, what did he mean? I left a comment in the code ''' Views for 'users' API application. ''' class SubscriptionsViewSet(viewsets.GenericViewSet): ''' ViewSet for user subscription actions. ''' serializer_class = UserSubscriptionSerializer def get_queryset(self): return self.request.user.subscriptions.all() @action(detail=True, methods=['post', 'delete'], name='subscribe') def subscribe(self, request, pk=None): ''' Process user subscription actions.. ''' subscribed = get_object_or_404(get_user_model(), id=pk) if self.request.method == 'DELETE': request.user.subscriptions.remove(subscribed) return Response(status=status.HTTP_204_NO_CONTENT) if request.user.subscriptions.filter(id=subscribed.id).exist(): #! Here, most likely, you need to return Response raise validators.ValidationError( _('The subscription already exists.') ) request.user.subscriptions.add(subscribed) serializer = self.get_serializer(instance=subscribed) return Response(serializer.data, status=status.HTTP_201_CREATED) ` -
How to get data from terminal Python Django
I have a Django application in which, on the click of a html button, I launch a third-party Python script. This script in the terminal displays a lot of information - messages, progress bar, and more. How can I intercept this information for later display on the pages of the Django web application? How, for example, to save this information to a file? Help me to understand. I don't even have ideas. I dug into the code of a third-party script, but I can’t understand how information is displayed there in the terminal. -
TypeError: Unable to serialize datetime.time. Django, Dsl elasticsearch, Python
i have a document with late_delivery = ObJectField() "City": { "delivery_time": TimeField, "order_time": TimeField, } example: "late_delivery": { "SomeCity": { "delivery_time": "23:00:00", "order_time": "22:00:00", }, and i wanna filter queryset by datetime.time, that less than now i tried class LateDeliveryFilter(BaseFilterBackend): def filter_queryset(self, request, queryset, view): late_delivery_requested = request.data.get("late_delivery", None) if not late_delivery_requested: return queryset now = datetime.now().time() queryset = queryset.filter(fulfillment=RB_STOCK) kwargs = { f"late_delivery__{settings.CITY_NAME}__order_time": {"lt": now} } return queryset.filter("range", **kwargs) but i'm getting an error TypeError("Unable to serialize datetime.time(12, 51, 22, 708584) (type: <class 'datetime.time'>)")) can anyone help with this? -
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?