Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create custom button in django template from jquery append() method
After the fetch of data returned by an API, I append data into django template, and I also create a button which contains already the url of the detail page specified in urls.py. The detail page has this url: http://127.0.0.0:8000/blog/<int:user_id>/<int:year>/<int:month>/<int:article_id>, so for example: http://127.0.0.0:8000/blog/1/2022/8/1 I'm trying to add a django url in this way (jquery): for(var i=0; i < data.articles.length; i++){ var item = $('<p>Titolo: '+data.articles[i].title+'<br>Autore: '+data.articles[i].author +'<br>Data: '+data.articles[i].pub_date+'</p><a id="button_' + data.articles[i].id + '"><button class="btn btn-primary">Dettaglio</button></a>'); $('#article_list').append(item); $("#button_" + data.articles[i].id).attr('href', "{% url 'blog:detail' "+ data.path_info.user_id +" "+ data.path_info.year +" "+ data.path_info.month +" "+ data.articles[i].id +"%}"); } Analyzing the html page I see: <a id="button_1" href="{% url 'blog:detail' 1 2022 8 1%}"><button class="btn btn-primary">Dettaglio</button></a>, which is correct When I click the button, Django returns this error: The current path, blog/1/2022/{% url 'blog:detail' 1 2022 8 1%}, didn’t match any of these. http://127.0.0.1:8000/blog/1/2022/%7B%25%20url%20'blog:detail'%201%202022%208%201%25%7D N.B.: data.path_info contains correct info about the path tags to use. How can I do to reach the correct path specifying it into jquery? -
PyJWT Token Cannot Be Decoded [closed]
I'm converting a deviceid to a JWT Token while a user is registering via their deviceid. Then I'm using the same JWTtoken in URL request's header but Django just throws an error jwt.exceptions.DecodeError: Invalid header string: 'utf-8' codec can't decode byte 0xeb in position 1: invalid continuation byte even though I just created the JWTtoken using it. I checked online and some people recommended converting to UTF-8 but not sure if that would work or how to do it. My Django urls.py: urlpatterns=[ path('manual/<str:id>/',views.manualwc), path('deviceregister/<str:id>/',views.deviceregistration)] views.py: def deviceregistration(request,id): import time deviceid=id jwttoken=jwt.encode({'deviceid':deviceid},"test",algorithm="HS256") # print(type(jwttoken)) #here I checked and it's a string not a byte newdevice=models.Anonym(created=time.strftime("%Y-%m-%d"),deviceid=id) newdevice.save() return JsonResponse({'jwttoken':jwttoken}) #it creates the instance and I can see the jwttoken def manualwc(request,id): token=request.headers['token'] #I send a request with Postman with 'token' header and in there {'deviceid':jwttoken I just created} print(token) print(type(token)) #it is still seen as string not byte decoded=jwt.decode(token, "test", algorithms=["HS256"]) #but it crashes here #Then it should do something using decoded['deviceid'] but it crashes here -
ModuleNotFoundError: No module named 'myapp.urls'---terminal has stuck and i can't do anything
hope you are well , I am new , please i need yur help . My terminal has stuck after this msg has show " ModuleNotFoundError: No module named 'myapp.urls' and i cant continue with my runserver. enter image description here -
How do I access django join table data?
I'm trying to access data in a join table using django. I have a list of users and a list of groups in a ManyToMany relationship. class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) groups = models.ManyToManyField(Group, related_name="members") class Team(models.Model): name = models.CharField(max_length=25) creator = models.ForeignKey("footballteamapi.Member", on_delete=models.CASCADE) The join table looks like this: footballteamapi_member_teams id+member_id+team_id 1+1+1 2+1+2 3+2+1 How do I go about accessing that table since there's no coinciding model to reference (i.e. Team.objects.all())? -
Django ModelForm ManyToManyField with Blank=True, Required=False '"" is not a valid value for a primary key' error
I have a Django model for creating an Asset object with an optional m2m field for managers: class Asset(models.Model): name = models.CharField(max_length=100) managers = models.ManyToManyField("users.User", blank=True, related_name="assets") And a custom ModelForm: class AssetForm(forms.ModelForm): managers = forms.ModelMultipleChoiceField(queryset=User.objects.none(), required=False) class Meta: model = Asset fields = [ "id", "name", "managers" ] def save(self, commit=True): instance = super().save(commit) def __init__(self, *args, **kwargs): super(AssetForm, self).__init__(*args, **kwargs) self.fields["managers"].queryset = self.org.get_users_with_management_access_role() def clean(self): cleaned_data = super(AssetForm, self).clean() return cleaned_data With a view to submit the form with: try: if request.method == "POST": if 'asset_id' in request.POST: asset = Asset.objects.get(id=request.POST['asset_id']) asset_form = AssetForm(request.POST, instance=asset) else: asset_form = AssetForm(request.POST) try: if asset_form.is_valid(): asset_form.save() asset_form.save_m2m() else: raise ValueError("form_errors") except: raise ValueError("form_errors") return JsonResponse({"message": "Asset successfully created"}, status=200) I have: Blank=True set on the m2m model field Required=False set on the ModelForm field for managers Calling asset_form.save_m2m() in the view Yet if I leave the field blank and submit the form, it still returns "" is not a valid value for a primary key. What am I missing or what else needs to be done to allow a blank value for managers in the form? thanks -
problem with postgresql after updating updating arch linux
hey guys I don't really what's the problem everything was working fine in my django project, all the pages was rendering correctly, and i guess after updating arch linux, i started to get this error: could not load library "/usr/lib/postgresql/llvmjit.so": libLLVM-13.so: cannot open shared object file: No such file or directory I have tried to turn off jit in postgres.conf file by setting jit to off but it didn't work, I don't really know what happened, the file llvmjit.so, does exist in that specific path -
Django dbbackup - Postgresql .psql.bin file format?
I have been installing and using django-dbbackup extension today (https://github.com/jazzband/django-dbbackup). I use the S3 Storage option. When i run a 'dbbackup', i obtain a file in format 'filename-2022-08-26-171845.psql.bin'. Is there a way to uncompress/read inside this '.psql.bin' file format ? I would like to access the query that have been backup, like i would do with a '.sql' file. Thanks for your explanation. -
django.db.utils.ProgrammingError after git pull
i have question, today i maked 'git pull' to my master branch, and at this time somebody make new migrations, but when i try to open 'http://localhost:9000/admin/' i have error: 'ProgrammingError at /admin/', on docker i have error like this: 'django.db.utils.ProgrammingError: column user does not exist LINE 1: ...user"."name", "user"."parent", "sharep_us...'. When i went back to another branch everything is work, i check many vebpages but sollution cant find, try make 'python manage.py migrate --fake', i try remove 'django_migrations' and do it again but still nothing. One of migrations made i, applyd to base and send to review, and now i pull this migration, maybe thats the problem? If need i can remove local data base, but plis help -
Easy Way To Import A Table from MS SQL Server to Django?
Is there good documentation on importing existing tables from MS SQL Server to Django? Some of the table names don't get along with Python (i.e. # in the column name). Eventually data will by brought into the MS SQL Server and need to be pushed to Django. I am using mssql-django. -
Error Refactoring the views into a single ViewSet
I am completing my first course RESTful Routes on TDD. Now I am on Part 1 Restful Routes and we are asked to refactor the views into a single ViewSet. I have been following the tutorial provided Django REST Framework Views - ViewSets and i've combined my APIView's to a ViewSet in my views.py file: from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework.viewsets import ViewSet class MovieViewSet(ViewSet): movies = Movie.objects.all() def list(self, request): serializer = ItemSerializer(self.queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): item = get_object_or_404(self.queryset, pk=pk) serializer = ItemSerializer(item) return Response(serializer.data) I am struggling with handling the URLs. # urls.py from django.urls import path, include from rest_framework import routers from .views import MovieViewSet router = routers.DefaultRouter() router.register("api/movies/", MovieViewSet) urlpatterns = [ path("api/movies/", MovieViewSet), path('', include(router.urls)), ] Here, we created a router (using DefaultRouter, so we get the default API view) and registered the ItemsViewSet to it. When creating a router, you must provide two arguments: The URL prefix for the views The ViewSet itself Then, we included the router inside urlpatterns. As per these instructions I thought I needed to recreate the url that we had in the APIView i.e http://localhost:8009/api/movies/ but I get the following error. … -
bootstrap 5 - d-flex class changing checkbox width
I have a list of products where there are 3 elements in each row: checkbox, label, and number of components related to this product. I want ot have all elements in 1 row. I have a problem with checkbox width because d-flex is changing the width of the checkbox if the product title is too long. It looks like this: I tried to use the grid system but it moves my span element to the next line when the text is too long. My question is how can I fix this bug and make all checkboxes the same? {% for product in product_list %} <div class="form-check business-challange-item d-flex"> <input class="form-check-input" type="checkbox" value="{{product.title}}" id="{{product.title}}"> <label class="form-check-label px-2" for="{{product.title}}">{{product.title}}</label> <span class="text-muted f-12">{{product.count}}</span> </div> {% endfor %} -
DJANGO - close two collapse buttons with one
I have a little problem with the collapse buttons in my django template, here is what I have : image 1 (button 1) when I click on the button, a second column is created on the table, with another button : image 2 (buttons 1 and 2) and this second button create a third column when clicked : image 3 (buttons 1 and 2, and column 3) The problem is that I want to "close" the columns 2 and 3 when i click on the button 1 (to make it come back like the first image), but it only close the 2nd column and the third stay displayed (I want my button 1 to close the two columns) : image 4 (button 1 and column 3) Here is my code : <tr> <td bgcolor="#FFEC00"> <button type="button" class="btn btn btn-primary float-center" data-toggle="collapse" data-target="#button1">Button 1</button> </td> </tr> <tr id="button1" class="collapse"> <td bgcolor="#00FF00"> <button type="button" class="btn btn btn-primary float-center" data-toggle="collapse" data-target="#button2">Button 2</button> </td> </tr> <tr id="button2" class="collapse"> <td bgcolor="#00C9FF">Hello</td> </tr> Does somebody know how can I do that ? -
I can't save my file through model after base64 encode at django-rest
I have fields named image1 and image2 in my model. I'm getting the base64 content of the files when creating (I'll send this to the remote api for another action). When I do base64 conversion, I cannot record in my model. It gives an error like; ValueError: I/O operation on closed file models.py class HelpDeskDemandModel(models.Model): code = models.CharField(max_length=50, unique=True, null=False, blank=False) image1 = models.ImageField(upload_to="municy_helpdesk_images/%Y/%m/%d/", null=True, blank=True) image2 = models.ImageField(upload_to="municy_helpdesk_images/%Y/%m/%d/", null=True, blank=True) serializers.py class HelpDeskDemandSerializer(serializers.ModelSerializer): class Meta: model = HelpDeskDemandModel fields = [ 'code', 'image1', 'image2' ] def create(self, validated_data): base64_files = [] for i in range(1, 3): img = validated_data.get(f"image{i}", None) if img: with img.open('rb') as f: base64_content = base64.b64encode(f.read()).decode() base64_files.append(base64_content) # the error occurs on this line instance = HelpDeskDemandModel.objects.create(**validated_data) return instance -
Not able to run Django website without port 8000(for eg: website.com:8000) using cyberpanel and openlitespeed
I am trying to host website on cyberpanel with openlitespeed server, centOS operating system. but whenever I am trying to make the project live it is not coming on the specied domain but running only on the example.com:8000. can somebody help me to find out the solutions or if anything that i am missing here. I did all the changes in the settings.py file related to project. -
Django project should host on domain without port in cyberpanel and openliteSpeed server
I am trying to host my web application using CyberPanel with OpenLiteSpeed Server. I have configured every configuration in settings.py and in a cyber panel like Vhost configuration. My problem this that when I am running the server from putty with port only website is running properly but it runs with the port number like www.abc.com:1234. But I want to host a website through the cyber panel and without a running server and it should run with just a domain name like www.abc.com. We have tried to check everything and configure the configurations but it is not working. Can anyone help me with this? -
How to access all gcloud app engine instances?
I am actually deploying a Django app in App Engine Flexible for the first time, so to not have a high bill, I want to delete all the instances that were created when I used gcloud app deploy (2 instances are created every time) By checking in the console I only find two instances, and only when I delete them that the two instances before them appear. I tried then running gcloud app instances list, but I still see only the last two instances. Do you have a method to see all the instances for a given project in App Engine? -
forms.RadioSelect just showing input field
models.py class Trainee(models.Model): TraineeID = models.AutoField(primary_key=True) Name = models.CharField(max_length=50) Course = models.CharField(max_length=40) BatchNo = models.CharField(max_length=15) Gender = models.CharField(max_length=10) DateofBirth = models.CharField(max_length=30) ContactNo = models.CharField(max_length=20) ContactAddress = models.CharField(max_length=80) EmailAddress = models.EmailField() class Meta(): db_table = "Trainee" forms.py class TraineeForm(forms.ModelForm): class Meta(): model = Trainee GENDER_CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Other')] Gender = forms.ChoiceField(widget=forms.RadioSelect, choices=GENDER_CHOICES ) fields = ("__all__") html page <div class="form-group row"> <label class="col-sm-3 col-form-label"> Gender: </label> <div class="col-sm-4"> {{form.Gender}} </div> </div> i am using radioselect for the first time in django. I looked to multiple dicussions on how to use it. I think i have done everything correctly. But in my page the gender does to come as a radio select but rather a normal input field does anyone know why? Any help will be appreciated. enter image description here -
Heroku Failing to Build a Django App using Conda as the Environment
TL:DR: Django app failing build with logs pointing to 'Could not find a suitable TLS CA certificate bundle' & 'No module named 'conda.cli.main_info' Details: Running into a Heroku build failing when pushing a python app (Django) with a conda env. Same code base + environment as the current build running on the Dyno - we have reverted back, made a syntax commit change, and tried pushing but it fails. Buildpack: https://github.com/pl31/heroku-buildpack-conda Error: When I push the logs throw the following error remote: File "/app/.conda/lib/python3.9/site-packages/requests/adapters.py", line 263, in cert_verify remote: OSError: Could not find a suitable TLS CA certificate bundle, invalid path: /app/.conda/lib/python3.9/site-packages/certifi/cacert.pem remote: During handling of the above exception, another exception occurred: ... remote: ModuleNotFoundError: No module named 'conda.cli.main_info' Any help would be really appreciated. -
How to take a right JSON?
i using Django Rest Framework and i wanna create a write JSON Here is my models: class Table(models.Model): date = models.DateField(auto_now=True) table_type = models.BooleanField(default=False) client = models.ForeignKey('users.Client', on_delete=models.DO_NOTHING) operator = models.ForeignKey('users.User', on_delete=models.DO_NOTHING) class TableData(models.Model): date = models.DateField() data = models.FloatField(null=True) data_type = models.TextField(null=False) table = models.ForeignKey('Table', on_delete=models.CASCADE) and my serializers: class DataSerializer(serializers.ModelSerializer): class Meta: model = TableData fields = '__all__' class TableSerializer(serializers.ModelSerializer): table_information = DataSerializer(read_only = True) class Meta: model = Table fields = ['table_type', 'client', 'operator', 'table_information'] and i want to take JSON like this: { "table_type": false, "client": 1, "operator": 1 "table_info": { "tabledata1":{ "date" : 2022-08-10, "data" : 4.0, "data_type": True, }, "tabledata2": { "date" : 2022-08-111, "data" : 5.0, "data_type": False, } , "tabledata3": { "date" : 2022-08-12, "data" : 5.0, "data_type": False, } , }, The problem is i have ForeignKey to my Table class but i dont know how to choose all TableData`s that relate to Table -
Why the manage.py file is not executed in the App Engine Flexible dockerfile?
So the dockerfile that App Engine uses to generate a container for a Django app is as following: FROM gcr.io/google-appengine/python@sha256:c6480acd38ca4605e0b83f5196ab6fe8a8b59a0288a7b8216c42dbc45b5de8f6 LABEL python_version=python3.7 RUN virtualenv --no-download /env -p python3.7 ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH ADD requirements.txt /app/ RUN pip install -r requirements.txt ADD . /app/ CMD exec gunicorn -b :$PORT myteam.wsgi My question is then why don't we see the command : python manage.py runserver And instead we see : gunicorn -b :$PORT myteam.wsgi Does it imply that the gunicorn command runs the server ? -
django.urls.exceptions.NoReverseMatch: 'users' is not a registered namespace inside 'v1'
#main url from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('users.api.urls',namespace='v1')), ] #app url from django.urls import path from .views import ExampleView app_name='users' urlpatterns=[ path("", ExampleView.as_view(), name='home') ] app view from rest_framework.views import Response, APIView class ExampleView(APIView): def get(self, request): return Response({"message": "hello world"}) test app from django.urls import reverse from rest_framework.test import APISimpleTestCase class TestUser(APISimpleTestCase): def setUp(self): self.path1 = reverse('v1:users:home') def test_user_path(self): print(self.path1) what is wrong with this code? why it return django.urls.exceptions.NoReverseMatch: 'users' is not a registered namespace inside 'v1' -
How to filter a query with a string ignoring it's lowercase or uppercase?
I want to create a query for filtering with an input. It's working but I want to filter by ignoring lower or capital cases. For example: input> test --> output listing but when I enter input> Test -->no output I want to get output in any cases. Here is my query alerts = Event.objects.filter(process_type__reporting_group__option__contains=group_search_bar) -
Django: Adding Item to specific list (One page Django list app)
I am trying to make a To-Do list app with Django. My current app webpage: My App page I am showing all the lists on one page, including their list items. I have made a form to make a new list, I have added buttons to delete the lists and their items. So, the final challenge to is add a form to create a new list item for a specific list. I am trying to use the same method as I did for creating a new list, i.e., use a Meta form. My problem: I want to add an item which is specific to the list it is in i.e., the list that the form text box falls under (see webpage again here: My App page) but I am having trouble with this because I don't know how to tell Django that I want to add that item to a specific list. In other words I don't know to add an item to a specify list.id. If anyone could help me, I would much appreciate it <3 The current code for my forms, models, views and index are as follows: models.py from typing_extensions import Required from django.db import models class … -
Get multiple postgresql function returned cursors from Django
I'm new to django and not able to figure out if it is possible to retrieve multiple cursors returned by a postgresql function. I've been searching the net for hours now and haven't been able to find a single example. I plan to write raw sql from django (no ORM) to call the postgresql functions. Anyone to enlight me? Thanks -
How to write a Graphene+Django filter that acts upon two columns at the same time
I am trying to write a filter in Graphene + Django that takes a single input but acts upon two columns at the same time. The two columns represent two numbers a and b, and the filter I want is one that select all element where the product of a and b is greater that some filter value. class MyModel(models.Model): a = models.FloatField() b = models.FloatField() class MultiplicationFilter(Filter): def filter(self, qs, value): # what to do here??? class MyModelCustomFilter(FilterSet): class Meta: model = MyModel multiplication_filter = MultiplicationFilter(field_name=???) # I can't have 2 fields, what do I put here? order_by = OrderingFilter( fields=("a", 'b'), ) class MyModelNode(DjangoObjectType): class Meta: model = MyModel fields = "__all__" filterset_class = MyModelCustomFilter interfaces = (graphene.relay.Node, ) I am aware that Django offers so more elaborate querying functionality by means of a Q() function, but I don't know how to formulate this in the Graphene Filter type of way.