Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Video stored in Firebase not playing in Iphones
I have a 5 Mb .mp4 video in firebase storage, using the below code it loads well in all web browsers. However it does not load in iPhone. .mp4s didn't work in safari but .mov did. However both .mp4 and .mov do not work on an iPhone. What can I do or video format to use? <video width='100%' height='315' poster='{{ value.image }}' controls loop muted playsinline> <source type='video/mp4' src='{{ value.video }}'> </video> -
Django redundant user relation in related models for permission purposes
I am pretty new to django and backend, I made two models Car & Service which have a relation to user (to check permissions, while operating on them) and now I am trying to relate one with another, I have noticed they have both user relation, but Service can't exists without Car, so I start wondering if there is any sense of having user relation in Service just for permissions puroposes, or is it better to create separete permissions for every Model: Car Model: class Car(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) ... and Service Mode: class Service(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) car = models.ForeignKey( "cars.Car", on_delete=models.CASCADE, related_name="services", ) and permission used in both API views for those models: class isAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user What would be your advice in this scenario ? -
upload shape file in geodjango
i am Trying to upload a shape file to postgres by django and geopandas. but it return this error: (psycopg2.errors.DuplicateTable) relation "idx_Village_kcnT1Uu_geom" already exists this is my model: class ShapeFile(models.Model): name = models.CharField(max_length=45) description = models.TextField() file = models.FileField(upload_to='user_shape_file') date = models.DateTimeField(auto_now_add=True) and i am using this signal to upload it: @receiver(post_save, sender=ShapeFile) def post_save_r(instance, **kwargs): file = instance.file.path file_format = os.path.basename(file).split('.')[-1] file_name = os.path.basename(file).split('.')[0] file_path = os.path.dirname(file) name = instance.name connection = 'postgresql://postgres:1234@localhost:5432/geoapp' with zipfile.ZipFile(file, 'r') as opened_zip: opened_zip.extractall(file_path) shape_file = glob.glob(r'{}/**/*.shp'.format(file_path), recursive=True)[0] gfr = gpd.read_file(shape_file) epsg = 4326 engine_ = create_engine(connection) gfr['geom'] = gfr['geometry'].apply(lambda x: WKTElement(x.wkt, srid=epsg)) gfr.to_sql(name, engine_, 'public', if_exists='replace', index=False, dtype={'geom': Geometry('Geometry', srid=epsg)}) but it return this error: -
Deploying Django to production correct way to do it?
I am developing Django Wagtail application on my local machine connected to a local postgres server. I have a test server and a production server. However when I develop locally and try upload it there is always some issue with makemigration and migrate e.g. KeyError etc. What are the best practices of ensuring I do not get run into these issues? What files do I need to port across? -
Django model instance default value
I have Django model name = models.CharField(max_length=255) excerpt = models.TextField() desc = models.TextField() due_date = models.DateTimeField() created_at = models.DateTimeField() priority = models.IntegerField(default = 1) When I create model instance, I want to set priority value to maximum value among all instances incremented by one. (max(priority)+1). Thank you. -
Crispy Forms - How to pass a helper to both a form and a formset?
I'm using Csripy Forms to render a formset and I'd like to use a helper to modify the forms themselves. How do I pass both the form helper and the formset helper to the crispy tag? My form class ModelForm(ModelForm): class Meta: model = MyModel exclude = ['key'] labels = { 'name': 'Stage', } The formset class ModelFormSetHelper(FormHelper): # see https://django-crispy-forms.readthedocs.io/en/latest/layouts.html def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_tag = False self.layout = Layout( Row( Column('name', css_class='col'), Column('conversion_rate', css_class='col-md-3 col-4'), css_class='formset-row' ) ) self.disable_csrf = True My tag {% crispy mymodel_formset formset_helper %} -
how to enable prometheus custom metrics for Django backend process (realtime kafka consumer) and access web endpoint
I have django app for kafka consumer which consumed realtime events and I have added custom prometheus metrics to track consumed events but when my app is running i don't see custom metrics at the web endpoint /metrics. I am getting 504 gateway timeout error because my consumer is running in the background and no response gets send out. I tried with Django health check but its the same issue. I tried running my consumer using Django custom management command, but then web endpoint didn't work. So is there a way to run consumer app in background and exposed prometheus metrics and access web endpoint -
Return the response from ListCreateAPIView
I want to return the custom json response after perform_create class MyObjList(generics.ListCreateAPIView): def get_serializer_class(self): if self.request.method == 'GET': return MyObjListSerializer return MyObjCreateSerializer def perform_create(self, serializer): // do something here. return Response({'isDraft': 1}) class MyObjCreateSerializer(serializers.Serializer): class Meta: fields = ('answer') However this dosen't return the any response,for my Javasctipt axios.post(API_URL, data, config).then(({ data }) => { console.log(data); // just show {} }).catch(error => { console.log(error); }); What I want to do is create object in perform_create and return the keyname to the client. However currently in my code it doesn't return anything. I wonder if Serializer class is relevant, but I am not sure the role of serializer class for POST> -
Django ORM bulk_update
I have stuck on this task. I have Professor model and i need to update from 2 queries but i have 6 queries in my DB. from django.db import models class Professor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField(default=18) My function. def update_professor_first_names(): first_name_updates = [(1, 'freddie'), (2, 'mady'), (3, 'hady'), (4, 'michael'), (5, 'rose')] tmp = [] for prof_id, new_first_name in first_name_updates: prof = Professor.objects.get(id=prof_id) prof.first_name = new_first_name tmp.append(prof) Professor.objects.bulk_update(tmp, ['first_name']) Please give me some advices. -
how to serialize data with python after getting it from firebase in django?
i'm working with Django and i want to retrieve data from firebase and make it readable and serializable when retrieving data from the default database (sqlite) i use this function : @api_view([('GET')]) def getPatients(request): patients = Patient.objects.all() serializer = PatientSerializer(patients , many = True) return Response(serializer.data) i want to change this function to get and serialize the data from firebase . i tried to get data from firebase and send it in the response but it is not showing in the web view page . the solution i tried : @api_view([('GET')]) def getPatients(request): patients = database.child('patients').get().val() serializer = PatientSerializer(patients , many = True) return Response(serializer.data) -
pipenv install django fail
I am using pipenv to install django, but I get an Error. Usage: pipenv install [OPTIONS] [PACKAGES]... ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting. -
Django / Python - change does not save in database - AttributeError: 'QuerySet' object has no attribute 'reload'
I have a setting that a user can change: send email automatically or manually. For this, I created a database with only 1 row that has the following columns: class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") def get(self): new_self = self.__class__.objects.get(pk=self.pk) # You may want to clear out the old dict first or perform a selective merge self.__dict__.update(new_self.__dict__) return reverse("core:autosend", kwargs={"auto": self.auto}) def reload(self): new_self = self.__class__.objects.get(pk=self.pk) # You may want to clear out the old dict first or perform a selective merge self.__dict__.update(new_self.__dict__) In this, either 'auto' or 'manual' is True, and the other one is False. The 'type' is set to 'auto' or 'manual' accordingly. This setting is used in the rest of the code. The code I have now in my view is: class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} model = AutoSendMail.objects.get(id=1) model.refresh_from_db() autoSetting = int(model.auto == True) manualSetting = int(model.manual == True) def post(self, request, *args, **kwargs): id_ = self.kwargs.get("pk") update_type = self.request.POST.get('update_type') if update_type == 'manual': logger.info("Set to: manual email send") model = AutoSendMail.objects.filter(id=1) model.manual = True model.auto = False model.type = "manual" for object … -
Can I use django as frontend and have a login system with Token Authentication
Well, this question is for the ones who has experience in working with Django. I'm new to Django and I have been studying Django, still I want to build an webapi with Django as backend and frontend, with a token authentication. Is that possible, and logical? I have been watching tutorial and reading documentation. Everyone who creates an api full django, creates a basic authentication. And, I want to know if is possible to create a more secure authentication with django as frontend. Thank you. -
Django exclude users with same email
I have 2 user models in my django project. So it set up like this: UserModel1 has 500 users with email and UserModel2 has 2000 users with email. And 300 users are both registered inn UserModel1 and UserModel2. So that means the two models share 300 users. UserModel1 has 200 excluding the users they both have in common, and UserModel2 has 1700 users exluded the users they have in common. I wanted to make a query that gets all the useres from UserModel2 that are not registered in UserModel1. So i want to get the 1700 useres they dont have in common. After som research i landed on this: from django.db.models import Q not_matching = UserModel2.objects.filter(~Q((email__in=UserModel1.objects.values('email'))) but no luck, any ideas? -
DJANGO - How to display multiple database rows in one row in view
I'm working with a 1-N relationship (1 ticket has N messages), in the admin view I'm trying to pull things from the database, but the N msg's related to ticket X, are coming as N lines (one line for each msg from ticket X) in the view (I display it in a table), I need the N messages to be passed in one line only, below is an example of how this is happening and how I need it to be. Current output: | Ticket id | Msg id | Content | Status | |:---------:|:-------:|:-----------------:|:------:| | 1 | 1 | msg 1 of ticket 1 | Open | | 2 | 2 | msg 1 of ticket 2 | Closed | | 2 | 3 | msg 2 of ticket 2 | Closed | | 3 | 4 | ticket 3 - msg 1 | Open | | 4 | 5 | msg 1 of ticket 2 | Closed | | 3 | 6 | ticket 3 - msg 2 | Open | How I need it to be: | Ticket id | Msg id | Content | Status | |:---------:|:-------:|:------------------------------------:|:------:| | 1 | 1 | msg 1 of ticket … -
Remove of alphabet letters from Charfield Django
How I can remove letters from charfield. The charfield is already implemented now i have to remove the letters how i should do that. source[enter image description here][1] = models.CharField(max_length=1, help_text=_("A, B, C, ...")) -
Python Setup on NameCheap showing Error 503. Service Unavailable
I am new to NameCheap and I need help deploying a Django application. I just tried installing python on Namecheap's Cpanel using Python 3.7.12 with the desired Application URL, but I get the Error 503. Service Unavailable when I visit the Application URL after creating the python app. From the resources I have seen, I am supposed to get a python signification that the python app works and not an error. Thanks in advance. python app setup on Namecheap's Cpanel error page when i visit the application's Url -
How to display the keys of a python dictionary as HTML table headers and values of each key as a row under that table header?
I'm currently working in a django project in which I do some data analysis using pandas library and want to display the data (which is converted into a dictionary) as a HTML table. dictionary that I want to display: my_dict = { 'id': [1, 2, 3, 4, 5], 'product_name': [product1, product2, product3, product4, product5], 'value': [200, 400, 600, 800, 1000], 'available_qty': [1, 2, 3, 2, 4] } I want to display the above dictionary like this table in django template. id product_name value available_qty 1 product1 200 1 2 product2 400 2 3 product3 600 3 4 product4 800 2 5 product5 1000 4 I have tried the below code. <table> <thead><h2><b>my dictionary</b></h2></thead> {% for key, values in my_dict.items %} <th><b>{{ key }}</b></th> {% for value in values %} <tr> {{value}} </tr> {% endfor %} {% endfor %} </table> I get the results as, (There is some space between each row displayed in the table) -
How to allow REST filters for non-DB fields in django
My problem is this: I'm working on a django project that has a lot of DB tables representing many different objects. This project has a GUI interface that is mostly a table that is a rough representation of each DB table. This table I got from google images can be used as an example Unlike this table, mine has filters on top of each column so for example you can type a name you're looking for and it will only show relevant rows. The problem starts here - Not all columns in the GUI are really columns in the DB. For example let's say the "Location" column isn't a DB column, but a property on the django model like this @property def location(self): return f"{self.city}, {self.state}" So obviously sending to my django backend this URL won't work just like that https://mywebsite/api/people/?location__icontains=Chicago My workaround for this is going to the View and overriding filter_queryset to handle this specific case . Something like this: def filter_queryset(self, queryset): if "location__icontains" in self.request.query_params: filter = self.request.query_params["location__icontains"] q = Q(city__icontains=filter ) | Q(state__icontains=filter) queryset = queryset.filter(q) The issue is that this doesn't even really cover all cases, it only works if the user filter input … -
Django: Is a super user without a password safe?
I'm trying to create an interactive website with Django for a chat bot. I have a model that stores the chat logs, ChatLogs. It has two fields: sender and message. sender, as the name might suggest, is a foreign key denoting who the sender of message is. It can be either the bot or a user. Here's how I have it set up: class ChatLogs(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=255) Since the sender can be the bot or a user, I thought to create a record in the User table for the bot: $ python3 manage.py shell >>> from django.contrib.auth.models import User >>> User.objects.create_user("Bot") I created the user without a password because, according to the Django documentation for createsuperuser, an account created as such can't be used to login. Which I think is a secure way to handle this. My question is, is there any reason I should not be doing this? From the Django documentation (for createsuperuser): When run non-interactively, you can provide a password by setting the DJANGO_SUPERUSER_PASSWORD environment variable. Otherwise, no password will be set, and the superuser account will not be able to log in until a password has been manually set for it. -
How to format Error message in Json Django
So, I want to format error messages in a json format instead of the HTML it is coming in. models.py # AUTH = Regex specified class Player(models.Model): CHEERING_MODE_CHOICES = [ (1, "Before FFPQ"), (2, "After FFPQ"), (3, "In exercise"), ] SEX = [ (1, "Male"), (2, "Female"), ] FFPQ_READY = [("Yes", "YES"), ("No", "NO")] auth = models.CharField( max_length=36, null=True, unique=True, validators=[AUTH, MinLengthValidator(36)], ) area = models.ForeignKey( "master.UserType", on_delete=models.PROTECT, validators=[MinValueValidator(1)] ) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' The error format I want { "type": "validation_error", "code": "invalid_input", "detail": "Crossing the maximum length", "attr": "auth" } It is coming in HTML format -
How it is possible to implement full-fledged search in several models and in several fields of each model in Django-based web-app?
I'm working on an admin panel for a site with courses And I need to implement a search by users, plans, exercises, etc. Maybe there are ready-made modules for this? Of course, I found solutions for StackOverflow, but I don’t understand how to insert this data into the template later Btw , here is link for this solution: Django search fields in multiple models -
Change django-ckeditor UI language to Persian
I'm trying to change the UI language of django-ckeditor in Admin site to Persian which is an rtl language. I'm expecting to see the tooltip of toolbar icons in Persian and the editor area ready for RTL. One option of course is to change the LANGUAGE_CODE of my project to fa-ir but this will switch the whole Admin site to Persian with a - in my opinion - dull translation. So I study the documentation and make the following changes to my project: SETTINGS.PY MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] from django.utils.translation import gettext_lazy as _ LANGUAGES = [ ('en', _('English')), ('fa', -('Persian')), CKEDITOR CONFIG (INSIDE SETTINGS.PY): Add 'Language' to the toolbar -> It appears on the toolbar. Add fa:Persian:rtl and en:English to language_list -> I see them in the dropdown when I click on the Language toolbar. Still, The editor area is English and even when I switch the language to Persian nothing happens on the UI - but if I check the source code I see <span lang="fa" dir="rtl"> is added. That's good and useful but not what I need. I'm sure its possible to achieve what I want because I see it in action on CKEditor's … -
Django bulk_create not setting the field with choices
In my model.py file, I have basic and premium coupon like below. coupon_types = ( ("Basic", "basic"), ("Premium", "premium"), ) class Coupon(Stamp): ... type = models.CharField(choices=coupon_types, max_length=256, default=coupon_types[0], null=True, blank=True) In the code below, I am trying to create the coupon objects in the database class ClassName: ... # Some attributes and methods ... def __construct_initiator_object(self, **kwargs): objs = [ self.initiator( ... ... type=coupon_types[0] if self.coupon_type.lower() == 'basic' else coupon_types[1] ) for code in self.coupons ] return objs @transaction.atomic def __create__(self): objs = self.__construct_initiator_object() create_objs = Coupon.objects.bulk_create(objs) return create_objs My problem now is that whenever I call the create method, the bulk_create sets every other field but not the type field. I don't know if it's because I have the choices=coupon_types in the type field. Any help on how to overcome this? -
I am getting None as output, but I want output as 10, 20 30?
<select name="dropdown" method="post" enctype="multipart/form-data"> <option selected="selected" disabled>Objects on page:</option> <option value= 1 >10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> def dropdown(request): print(request.POST.get('dropdown')) return render(request, 'ndtgui/dropdown.html') The above one is my html file and below is view in django. Blockquote