Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add Postgres extension when pushing local database to Heroku
I have a Django application which relies upon the postgis Postgres extension. I want to copy my local Database to Heroku using pg:push, but I get numerous django.db.utils.ProgrammingError: relation does not exist errors, following on from: pg_restore: error: could not execute query: ERROR: type "public.geography" does not exist LINE 6: coords public.geography(Point,4326), ^ Command was: CREATE TABLE public.outreach_localcompanylocation ( id bigint NOT NULL, long_name character varying(200) NOT NULL, city character varying(200) NOT NULL, country character varying(3) NOT NULL, coords public.geography(Point,4326), google_location_id bigint, state character varying(200) ); This seems to be because pg:push does not enable the postgis extension (typically enabled by running the SQL command CREATE EXTENSION postgis;). If I try to enable it manually on a new Heroku database, then run pg:push, I get this error: Remote database is not empty. Please create a new database or use heroku pg:reset So is there a way to run CREATE EXTENSION postgis; as part of the pg:push process? -
How to filter a django queryset using case insensitive __in?
I have a model: class Skill(models.Model): name = models.CharField(max_length=120) icon = models.CharField(max_length=20) color = models.CharField(max_length=7) I want to do the following filter, but case insensitive: skill_names = ['Code Quality', 'Analytical Thinking', 'Productivity', 'Communication'] Skill.objects.filter(name__in=skill_names) -
OAuth 2 for authentication in native apps
Is it good to use OAuth for self-authentication in native apps? For example, I have a site and want to create a native application for that Now is it a good idea to use OAuth (OpenID Connect) to log in and register users in the app to use API on my site? Another example, Facebook use OAuth in the Facebook application login page -
Heroku Deployed Django App displaying ProgrammingError
I used Django Default Database Sqlite but when deploying I used Postgresql but I get this error below... I need help please I have made migrations but still meanwhile it is working perfectly on localhost with sqlite database. The Error -
djangorestframework: use kwargs instead of requests
My code is littered with a lot of parsing keys from request.data objects inside functions, which makes it hard to follow data flow. How can I change from from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated @api_view(["POST"]) @permission_classes([IsAuthenticated]) def greet(request): # FYI for Character.AI we use the chat and not this stateless_chat view. payload = request.data user = payload.get("user", "test") friend = payload.get("friend", "bart") num_friends = int(payload.get("num_friends", 16)) return None to @api_view(["POST"]) @permission_classes([IsAuthenticated]) def greet(user:str='test', friend:str='bart', num_friends:int=16): return None -
removing more than a character using cut
So I'm trying to search for Elements using query selector, the problem is, due to the way theses IDs are generated (with the name of regions, stores, and sale type, from the context) some of then includes spaces or dots on them which don't let them be searched. I have identified the spaces were breaking my searches before and used cut to remove the spaces from IDs. Is there a way to use cut to remove diferent characters as if I'm using cascaded replaces (in python) or replaceAlls (in JS) to make these ids don't have any spaces or dots? I tried using pipes but it didn't work. how can I do it? Snippet of the formation of the elements: {% if data.nivel == "N0" %} <tr id="family_{{ data.familia_produto|cut:" " }}" class="bu_name_line {{ data.nivel }} title0" data-level="{{ data.nivel }}" data-family="{{ data.familia_produto }}" data-regional="{{ data.nome_regional }}" data-segment="{{ data.segmento }}" data-bu-name="{{ data.nome_filial }}" onclick="show_lines('N1','{{ data.familia_produto }}')"> <td id='bu_name' onmouseenter='hight_light(this)' onmouseleave='hight_light(this)'> {{ data.familia_produto }} </td> {% elif data.nivel == "N1" %} <tr id="regional_{{ data.familia_produto|cut:" " }}_{{ data.nome_regional|cut:" " }}" class="bu_name_line {{ data.nivel }} title1 hide" data-level="{{ data.nivel }}" data-family="{{ data.familia_produto }}" data-regional="{{ data.nome_regional }}" data-segment="{{ data.segmento }}" data-bu-name="{{ data.nome_filial }}" onclick="show_lines('N2A','{{ data.familia_produto }}','{{ … -
Django conventional filestore location for miscellaneous files read by an app's views?
Is there a convention for where to put miscellaneous files which are opened and read by Django views, but which aren't python code or html templates and aren't processed by the temmplate renderer? (In my case, I have a View which returns an application/excel .xlsx file to the user. It is generated by reading in a "template" xlsx file with lots of tricky formatting and formulae but no data values. Openpyxl is used to insert selected data from the db, and the resulting workbook is saved and sent to the user.) -
I'm trying to open the admin website for my project but it isn't coming up, rather it shows the Django install worked successfully page. What can I do
I've created superuser and I've also ran the server yet it keeps showing the django "install worked successfully" page. Please what can I do? -
Add ID field to ModelForm
I need to add ID field to my form, and I'm getting so mad Currently I have : class ProductVideoForm(forms.ModelForm): class Meta: model = ProductVideo translatable_fields = get_translatable_fields(ProductVideoTranslation) fields = [ "product", "id", #added!!!! "type", "placeholder", ] + translatable_fields widgets = { "placeholder": ImageInput(), } trans_fields_per_lang = get_trans_fields_per_lang(translatable_fields) I added ID to fields, and the template is: {{ video_formset.management_form }} Why Is ID not displayed ?? actually, I just need display it, not updated. -
How to set cookie on DRF viewset?
I'd like to know how to set a cookie on Django rest framework ViewSet/ModelViewSet. I read some SO posts that say you can use Response({serializer.data}), but in retrieve it may be okay, but for create() like the following one, doesn't Response() affect its following processing? Actually when I used HttpResponse() like HttpResponse(status=401, reason="you cannot post anymore.") replacing the raise PermissionDenied() line in the below one, I got a 500 error (error says AttributeError: 'collections.OrderedDict' object has no attribute 'pk' or such) but not the specified 401 code. So basically the following explains what I want to do, that is denies when the user's post count is >= 4, but otherwise continues perform_create() and the following DRF script, with attaching a cookie, that tells browser "you have n post slots left". class PostViewSet(viewsets.ModelViewSet): .. def perform_create(self, serializer): role = self.request.user.userproperty.role if role == "guest": post_count = self.request.user.posts.count() if post_count >= 4: raise PermissionDenied({"message": "you cannot post anymore."}) else: response = // anyhow gets response here // response.set_cookie("notify", "your post slot is " + str(3 - post_count) + "left now.") serializer.save(user=self.request.user) But I don't know how can I possibly get response from something, or calling Response() without harming consequences script. I tried, … -
How to manually connect postgres database (inside container) from django container? [closed]
I am not able to connect a database from another container in Django(inside a container). The database container is from another compose file. Currently, I am defining DATABASE_URL as postgres://db_user:password@localhost:5432/db_name in Django settings configuration. But, it's not working. Any idea how to resolve it? -
Django models not returning property value
I'm making an API with DRF and now still making database but i got a problem with a field from models.py my script of models.py class Inflasi(models.Model): sandang = models.FloatField(null=True) sembako = models.FloatField(null=True) perumahan = models.FloatField(null=True) kesehatan = models.FloatField(null=True) transportasi = models.FloatField(null=True) informasi = models.FloatField(null=True) rekreasi = models.FloatField(null=True) pendidikan = models.FloatField(null=True) penyedia_pangan = models.FloatField(null=True) perawatan_pribadi = models.FloatField(null=True) total_inflasi = models.FloatField(null=True) tanggal = models.DateField(null=True) @property def total_inflasi(self): return self.sandang + self.sembako + self.perumahan + self.kesehatan + \ self.transportasi + self.informasi + self.rekreasi + \ self.pendidikan + self.penyedia_pangan + self.perawatan_pribadi def __str__(self): return str(self.tanggal) class Meta: verbose_name = "Inflasi" verbose_name_plural = "Inflasi" and that not return the property value in Django admin dashboard and this my admin.py script @admin.register(Inflasi) class InflasiModelAdmin(ImportExportModelAdmin): class Meta: model = Inflasi fields = '__all__' what must i do for fix that? -
auto download the pdf file right after payment is done
what could be the function to automatically download pdf file automatically right after payment is done and page loads. Actually algorithm guides are there in the media folder but i dont know how to make it download right after payment is made. i am totally clue less help me out please.. views.py def payForAlgorithmGuide(request): print('---------payForAlgorithmGuide--------------') if request.method == 'POST': algoName = request.POST.get('algoName') print('algoName:', algoName) return render(request, 'pay-for-algo-guide.html') models.py class AlgorithmGuide(models.Model): id = models.AutoField(primary_key=True) # buyer_id = models.IntegerField(blank=True, null=True) algorithm_name = models.CharField(max_length=200, blank=True, null=True) guide_data = models.FileField(upload_to=user_directory_path2, null=True, verbose_name="", validators=[FileExtensionValidator(allowed_extensions=['doc', 'docx','pdf'])]) class Meta: db_table = 'AlgorithmGuide' -
how to use two tables inside a query? django
I am trying to use two tables inside one django query. But my query is resulting as "invalid JSON" format. I want to filter data in Request table by (status="Aprv"). The Request table contains attributes 'from_id' and 'to_id'. The uid is the id of the user who is currently logged in. If the current user(uid) is having the 'from_id' of Requests table, the query should return data of 'to_id' from the 'RegUsers' table. If the current user(uid) is having the 'to_id' of Requests table, the query should return data of 'from_id' from the 'RegUsers' table. class frnds(APIView): def post(self, request): uid = request.data['uid'] ob = Requests.objects.filter(status="Aprv") fid = ob.value('from_id') tid = ob.value('to_id') if fid == uid: obj = RegUsers.objects.filter(u_id=tid) else: obj = RegUsers.objects.filter(u_id=fid) ser = android_serialiser(obj, many=True) return Response(ser.data) I dont want to use foreign keys. Please Do Help me Currect the syntax. -
How to get instance of Parent Object and Create Related Child at the same time
Let's say we have: class Parent(Model): pass class Child(Model): parent = ForeignKey(Parent, related_name='children') Now on Child Creation: parent = Parent.objects.get(id=id) Child.objects.create(parent=parent) Here I can see 2 things happening, getting an instance of a parent object and then creating the child object. How I can process it at a time? on child creating. Is it fine to follow the above approach? or we can make it better. -
djagno management command as a package?
I'm trying to have a directory structure for my Django custom commands. According to the Django tutorial commands are created as modules under management/commands directory. e.g. management/commands/closepoll.py I have many commands so I'm trying to split them into packages. I want to have a package structure, like: management/commands/closepoll/closepoll.py <-- contains the Command class. management/commands/closepoll/closepoll_utils.py management/commands/closepoll/__init__.py Tried that, but Django does not recognize the command. -
Send Request From Nextjs to Django Served From Unix Socket
I have a nextjs app and django app running on a linux server. For the purposes of SSR, I am trying to get data from the django app to the nextjs app using getServerSideProps. The easiest I would do this is to send a request from the nextjs app to the django app. This was relatively easy for me to do in development. Requests would be sent to http://localhost:8000, since the django app was using port 8000, from port 3000 which is the port the nextjs app is using. However, in our production server, the django app run on a unix socket, served via gunicorn. upstream app_server { server unix:/path/to/gunicorn.sock fail_timeout=0; } How can I request for data from the django app to the nextjs app when the django app is accessible via unix socket? -
Running kafka consumer with Django
I've setup a kafka server on AWS and I already have a Django project acting as the producer, using kafka-python. I've also setup a second Django project to act as the consumer (kafka-python), but I'm trying to figure out a way to run the consumer automatically after the server has started without having to trigger the consumer through an API call. Everything I've tried so far either runs the consumer and blocks the server from starting or runs the server and blocks the consumer. -
How to modify DateRangeFilter in django admin section?
There is one prebuilt filter DateRangeFilter in django. How to modify the result of filtering data. -
How to restrict a list of fields for a django model generated using _meta.fields by use of a filter
In my project I am trying to retrieve field names of a model which has been selected using a dropdown list. The idea is to list all underlying fields of the selected model, select one of the fields and save the combination in a model for use in a scenario later. To generate the list of fields I am using: model_fields = [fld.name for fld in modelSelected._meta.fields] where modelSelected is the previously selected model (as sent from template using an Ajax function). The set up is working as intended with one caveat. When I start to type in the input field for model field name (using jQuery autocomplete), all the fields of the model are shown in the (selection) list. Is there a way to restrict the field names in what I am attempting to do here? For example, to accomplish an autocomplete on a model HoldingCoy I would be doing: parent_coy = HoldingCoy.objects.filter(name__icontains=q).annotate(value=F('name'), label=F('name')).values('holding_coy', 'value', 'label') How can I apply filter to restrict number of fields displayed in the drop down list and achieve a similar effect as used for querying a model instance (as in the above example)? -
Django path didn’t match any of these when adding query param to the endpoint
I am using django 4.1 I have a product model class Product(models.Model): product_id = models.CharField( blank=False, null=False, max_length=50, verbose_name="stock ID", ) name = models.CharField(max_length=30, blank=False) price = models.IntegerField(blank=False) availability = models.IntegerField(verbose_name="product availability") timestamp = models.DateTimeField(auto_now=True) product/urls.py router = routers.DefaultRouter() router.register("product/<slug:product_id>", productViewset, basename="productPrice") urlpatterns = [ path("", include(router.urls)), ] and in project urls.py api_patterns = [ path("", include("product.urls")), ] urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(api_patterns)), ] when I try to call this endpoint"http://127.0.0.1:8000/api/product/2048cf23-6bb2-4532-a140-b13dd1361c4/" it doesn't match any of the paths in my project! NB:product_id is not the primary key as there are more than one row for the same product but at different time and price. I tried to use < str:product_id > < string:product_id > < uuid:product_id > but nothing works,I am not sure why it's happening but when I change the url in product urls.py to router.register("product", productViewset, basename="productPrice") it works but I need to path that id to filter the queryset. the error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/api/product/2048cf23-6bb2-4532-a140-b13dd1361c4/ Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: admin/ api/ ^product/<slug:product_id>//$ [name='productPrice-list'] api/ ^product/<slug:product_id>\.(?P<format>[a-z0-9]+)/?$ [name='productPrice-list'] api/ ^product/<slug:product_id>//(?P<pk>[^/.]+)/$ [name='productPrice-detail'] api/ ^product/<slug:product_id>//(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='productPrice-detail'] api/ ^$ [name='api-root'] api/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] … -
Trouble combining CustomUser and Profile into single endpoint in django
I have a CustomUser model and two separate Models for profile two types of User. I'm trying to combine the attribute of CustomUser and one of the Profile into single endpoint from which the user can see/update/delete the user/profile. For instance there are 2 types of users, doctor & patient. so if the user is doc then the endpoint will return the attributes of CustomUser+DoctorProfile and same for the Patient CustomUser+PatientProfile. Below is the code. I will explain the issue in the code base with comments. I will enormously appreciate any suggestion. One thing to mention is that I split the models.py file into 3 different folder and imported all of them into __init__.py of models folder. CustomUser Model: class CustomUser(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): DOCTOR = "DOCTOR", "Doctor" PATIENT = "PATIENT", "Patient" # what type of user type = models.CharField(_("Type"), max_length=50, choices=Types.choices, null=True, blank=False) avatar = models.ImageField(upload_to="avatars/", null=True, blank=True) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomBaseUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'type'] #email is required by default def get_full_name(self): return self.name def __str__(self): return self.email DoctorProfile Model: class DoctorProfile(models.Model): class DoctorType(models.TextChoices): """Doctor will choose profession category from enum""" PSYCHIATRIST = … -
How to correctly write view for saving file?
My model looks like this: class Document(models.Model): id: int = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # type: ignore order_id: str = models.CharField(max_length=255) # type: ignore publicated_at: datetime = models.DateTimeField(null=True) # type: ignore expired_at: datetime = models.DateTimeField(null=True) # type: ignore created_at: datetime = models.DateTimeField(auto_now_add=True) # type: ignore updated_at: datetime = models.DateTimeField(auto_now=True) # type: ignore department: Department = models.ForeignKey(Department, on_delete=models.DO_NOTHING, null=True, blank=True) # type: ignore file_name: str = models.CharField(max_length=255) # type: ignore owner: CustomUser = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, null=True, related_name='owned_documents') # type: ignore loaded_by: CustomUser = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='loaded_documents') # type: ignore file_id: str = models.CharField(max_length=255, null=True, blank=False) # type: ignore metrics: Metric = models.ManyToManyField(Metric, through="DocumentsMetrics", related_name="documents") # type: ignore document_status: DocumentStatus = models.ForeignKey(DocumentStatus, on_delete=models.SET_NULL, null=True) # type: ignore issue: str = models.TextField(null=True, blank=True) # type: ignore suggestion: str = models.TextField(null=True, blank=True) # type: ignore class Meta: app_label = 'library' mongo_file_key = 'file_id' def upsert_document(self, buffer: IStream) -> None: file_ms.update_from_bytes(self, self.mongo_file_key, buffer) def get_document_bytes(self) -> IStream | None: return file_ms.get_bytes(self, self.mongo_file_key) def save_document(self, path: str) -> None: with open(path, 'wb') as f: I am storing a "Document" object in PostgreSQL. In the file_id field, I insert the id from mongoDB. My model has method upsert_document to save file to mongo which returns mongo_id. … -
Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<slug>[^/]+)/\\Z']
Been stuck at this trying to delete data from the database, i'm clearly lost with the logic somewhere i'd grately appreciate any assistance. resume-detail.html <div class="row"> {% if educations %} {% for education in educations %} <div class="col-lg-12 mt-4 pt-2"> <div class="component-wrapper rounded shadow"> <div class="p-4 border-bottom bg-light"> <h4 class="title mb-0">{{education.institution}}</h4> </div> <div class="p-4"> <div class="row"> <div class="col"> <p><strong>Qualification: </strong> {{education.qualification}}</p> </div> <div class="col"> <p><strong>Level of Qualification: </strong> {{education.level}}</p> </div> </div> <div class="row"> <div class="col"> <a href="{% url 'delete' educations.slug %}" class="btn btn-danger">Delete Qualification </a> <!-- <button class="btn btn-danger">Delete Qualification</button> --> </div> </div> </div> </div> </div> {% endfor %} {% endif %} </div> <div class="row"> <div class="col-lg-12 mt-4 pt-2"> <h4 class="text-dark"><button type="button" class="btn btn-secondary-outline btn-outline-success" data-toggle="modal" data-target="#addEducation"><span class="mr-2">+</span> Add Education</button></h4> </div> </div> i'm using a modal to capture this data <div class="modal fade" id="addEducation" tabindex="-1" aria-labelledby="addEducationLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <form action="{% url 'delete' educations.slug %}" method="POST"> {% csrf_token %}.... urls.py path('userapp/view/<slug:slug>/', user_views.resume_detail, name='resume-detail'), path('delete/<str:slug>/', user_views.delete_view, name='delete' ) views.py def delete_view(request, slug): obj = Resume.objects.get(id = slug) if request.method =="POST": obj.delete() messages.success(request,"Information Deleted Successfully") return redirect('resume-detail', id = slug) educations = Education.objects.get(resume = obj) experiences = Experience.objects.get(resume = obj) context = {} context['object'] = obj context['educations'] = educations context['experiences'] … -
Not getting results from searched in Django app
I am traying to create a simple search option in Django. But I am not getting any results after the search from the model. files: model.py class ChoresPost(models.Model): # Job post ChoresPost_TYPE_CHOICE = ( # job category ('1', 'Vodoinstalater\ka'), ('2', 'Eelektricar\ka'), ('3', 'Moler\ka'), ('4', 'Stolar\ka'), ('5', 'IT'), ('6', 'Zidar\ka'), ('7', 'Cistac\ica') ) user_of_post = models.ForeignKey(ClientsUsers, null=True, on_delete=models.CASCADE) post_id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50, null=False, blank=False, db_index=True) bio = models.TextField(null=False, blank=False) date_of_post = models.DateTimeField(auto_now=True) category = models.CharField(max_length=100, choices=ChoresPost_TYPE_CHOICE) budget = models.IntegerField(default=0) date = models.DateField(null=True) view.py def search_venues(request): if request.method == "POST": searched = request.POST['searched'] venues = ChoresPost.objects.filter(name__icontains=searched) return render(request, 'search_venues.html', {'searched': searched, 'venues': venues}) else: return render(request, 'search_venues.html', {}) urls.py urlpatterns = [ path('AddNewOffer/', AddOfferPage, name='AddNewOffer'), path('Offers/', OfferView, name='OfferView'), path('Offer/<int:pk>', ShowOffer.as_view(), name='ShowOffer'), path('search_venues/', search_venues, name='searchvenues'), ] In project.html, I set my search fields: <form class="d-flax" method="POST" action="{% url 'searchvenues' %}"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" name="searched"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> A page for displaying the result search_venues.html {% block content %} {% if user.is_authenticated %} {% if searched %} <h1>You searched for {{ searched }}</h1> {% for venue in venues %} <p>{{venue}}</p> #here I am not getting any results {% endfor%} {% else %} <h1>No result</h1> …