Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I authenticate with tokens from the remote database?
I am building a REST API that uses 2 postgresql databases: db1 (default) and db2 (remote, read_only). I want to get users from db2 and create a profile for them to store in db1. The custom User and MyToken models are in the db2. Is it possible to do such that Users authenticate using their token from the db2? When I use ObtainAuthToken in my view, it creates new model named Token in db1. -
I'm merging multiple forms, and geting ValueError/ at Registration form in django while interlinking to another form database
I'm getting a ValueError at /Register. The view Capp.views.Insertrecord didn't return an HttpResponse object. It returned None instead. I'm merging various html forms. Even checked for the variables, its the same everywhere. enter image description here [ITS ss of models.py for the same code][1] -
How to avoid sending error from a specific Python library to sentry?
I'm using django and logging errors to sentry via sentry_sdk. However, I do not want to log errors from specific library. For example, libraries such as elastic apm generate various errors(Like TransportException, ..., etc) depending on the state. import sentry_sdk from elasticapm.transport.exceptions import TransportException sentry_dsk.init( dsn='SENTRY_DSN', ignore_errors=[ TransportException() ] ) The example above is how to write down a specific error and ignore it. Is there a way to ignore errors that occur in a specific library other than this way? -
ajax selecting specific part of a HTML
I am trying to AJAX load a chained dropdown list using django, where the dropdown choices are based on the choice of another field... I have more than one element which needs to be chained, So I tried to chain multiple Ajax requests one after the other which I wasnt able to ... Now I am trying to to bring in the ajax response of different choice fields in single html and render the ajax response based on the id of the div's... Can you please let me know if I can explicitly specify the part of the data(div) that can be replaced... Thanks! AJAX PART store_dropdown_list_options.html: <div id="div1"> <option value="">---------</option> {% for store in stores %} <option value="{{ store.id }}">{{ store.StoreNM }}</option> {% endfor %} </div> views: def load_store(request): ReadingAreaNo_id = request.GET.get('ReadingArea') print('value is ', ReadingAreaNo_id) stores = StoreMaster.objects.filter(ReadingAreaNo_id=ReadingAreaNo_id).order_by('StoreNO') print('stores are ', stores) return render(request, 'rateshare/store_dropdown_list_options.html', {'stores': stores}) URLS: path('ajax/load-stores/', views.load_store, name='ajax_load_stores'), script: <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_ReadingAreaNo").change(function () { var url = $("#personForm").attr("data-cities-url"); var ReadingAreaNo = $(this).val(); $.ajax({ url: url, data: { 'ReadingArea': ReadingAreaNo }, success: function (data) { $("#id_StoreNO").html(data); } }); }); </script> There will be different div's rendered in the ajax html and so I am looking … -
How to use 2 engines with the same database in Django?
Note: This question is NOT about using 2 databases. So I have been using timescaledb with my django project and my DATABASE portion in my settings.py file is something like this: DATABASES = { 'default': { 'ENGINE': 'timescale.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER' : os.getenv('DB_USER'), 'PASSWORD' : os.getenv('DB_PASSWORD'), 'HOST' : os.getenv('DB_HOST'), 'PORT' : os.getenv('DB_PORT'), }, } Now, I want to use postigs with the same database. Under the hood, i can just install the postgis extension to postgres but how should i configure the settings in django? All the documentation of using postgis suggests to use different settings for the 'ENGINE' property, but i have to use timescale too. This article shows it is possible to use both with single DB. But I am just not sure how to do it with django? -
Return user object along side token using rest_framework_simplejwt
I am using django_rest_passwordreset for my authentication on Django rest framework. I followed the tutorial on their official documentation and login, registration works well. Login returns the access and refresh token. What I want to do is also return the user object alongside the access and refresh token. I have a custom model # auth/models.py # Inherited from user class MUser(AbstractUser, models.Model): email = models.EmailField(unique=True) role = models.CharField(max_length=40, default="student") USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username', 'role'] Serializers # auth/serializers.py class TokenObtainPairSerializer(TokenObtainSerializer): @classmethod def get_token(cls, user): return RefreshToken.for_user(user) def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data My view # auth/views.py class TokenObtainPairView(TokenViewBase): """ Takes a set of user credentials and returns access and refresh JSON web token pair to prove the authentication of those credentials. """ serializer_class = serializers.TokenObtainPairSerializer So in summary, upon successful login, I receive { access: xxx, refresh: xxx, # I want to add this user: {username, first_name, last_name, email, ...} } -
Connect html form with models in dango to submit data
I wanted to know how to connect the below html form with a specific model. Also how can I connect multiple forms to multiple forms to multiple models ( or rather tables in the database) to submit data. html <form action='register' method="POST" > {% csrf_token %} <table> <tr> <td><label for="name">NAME :</label></td> <td><input type="text" id="first_name" name="name" maxlength="50" ></td> </tr> <tr> <td><label for="email">EMAIL :</label></td> <td><input type="email" id="email" name="email" placeholder="This will be your User ID"></td> </tr> <tr> <td><label for="phone">MOBILE NUMBER :</label></td> <td><input type="tel" id="phone" name="phone" maxlength="10" pattern="[0-9]{10}" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" ></td> </tr> <tr> <td><label for="join_as">JOIN AS :</label></td> <td><select id="join_as" name="join_as" > <option value="select" disabled selected hidden>Select...</option> <option value="individual" >INDIVIDUAL</option> <option value="firm" >FIRM</option> <option value="company" >COMPANY</option> <option value="consultancy">CONSULTANCY</option> <option value="students" >STUDENTS</option> <option value="others" >OTHERS</option> </td> </select> </tr> <tr> <td><label for="passpwrd">PASSWORD:</label></td> <td><input type="password" id="password" name="password" maxlength="10" placeholder="max 10 characters" ></td> </tr> <tr> <td><label for="con_passpwrd">CONFIRM PASSWORD :</label></td> <td><input type="password" id="con_password" name="con_password" maxlength="10" ></td> </tr> </table> </form> model.py class Regd3(models.Model): name= models.CharField(max_length=100) username= models.EmailField(max_length=254, primary_key= True) #email mobile_number= models.CharField(max_length=10) category = models.CharField(max_length=10) password= models.CharField(max_length=10) agreed= models.BooleanField(default=False) what shall i write in views.py or how to submit data exactly? -
Django static file not loaded with gunicorn
When I run my Django project with python mange.py runserver it runs fine without broke and CSS or javascript file but when I try with gunicorn it's not able to load any static file CSS or js file shows 404. Here are my Django settings.py PROJECT_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__))) LOCALE_PATHS = (os.path.join(PROJECT_DIR, "../locale"),) RESOURCES_DIR = os.path.join(PROJECT_DIR, "../resources") FIXTURE_DIRS = (os.path.join(PROJECT_DIR, "../fixtures"),) TESTFILES_DIR = os.path.join(PROJECT_DIR, "../testfiles") STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, "../static"), os.path.join(PROJECT_DIR, "../media"), os.path.join(PROJECT_DIR, "../node_modules"), os.path.join(PROJECT_DIR, "../node_modules/react/umd"), os.path.join(PROJECT_DIR, "../node_modules/react-dom/umd"), ) STATIC_ROOT = os.path.join(PROJECT_DIR, "../sitestatic") STATIC_URL = "/sitestatic/" COMPRESS_ROOT = os.path.join(PROJECT_DIR, "../sitestatic") MEDIA_ROOT = os.path.join(PROJECT_DIR, "../media") MEDIA_URL = "/media/" I configure my Nginx in a lot of different ways but it's doesn't work with gunicorn. 1. server { listen 80 default_server; server_name 52.3.225.81; location = /favicon.ico { access_log off; log_not_found off; } location /static { autoindex on; alias /home/ubuntu/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myproject.sock; } } location /static/ { root /home/ubuntu/myproject; } location /myproject/static/ { root /home/ubuntu; } location /myproject/static/ { alias /home/ubuntu; } I am not understanding why this is happening. My static folder in myproject/static. any idea why I getting 404? -
django fileuploader chunk method not working as expected
the Django chunks method on the fileuploader handler accepts chunk_size with this desc in the source code "" Read the file and yield chunks of ``chunk_size`` bytes (defaults to ``File.DEFAULT_CHUNK_SIZE``). """ so i have this view function, def simple_upload(request): if request.method == 'POST' and request.FILES['image']: file = request.FILES['image'] print(sys.getsizeof(file)) chunk_size = 0 dd = list(file.chunks(chunk_size=20000)) print(len(dd[0])) // this gives me some figures like the size of the image print('...') for chunk in list(file.chunks(chunk_size=10000)): chunk_size += sys.getsizeof(chunk) print(chunk_size) return redirect('index') return render(request, 'upload.html') generally, my expectation is that if the image is 50000bytes and i choose a chunk_size of 10000 the length of the generator should be 5. i dont know if i am missing something. -
How do i provide a default image for a django project
In my project, I want users to be able to create a post without an image and if they create it, the default dummy image would be there rather than it Beign blank In my models.py related_image = models.ImageField(default='defaultimg.jpg', upload_to='images/’, null=True) Now if I create a post in the admin section, it would put the default image but if I create it from the users point of view(the form), it does not upload or use the default image forms.py class BlogPostForm(forms.ModelForm): related_image = forms.ImageField(label='', required=False) views.py def uploadPost(request): form = BlogPostForm() if request.method == 'POST': form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') The problem is that when a user create a post, the related image would be empty but from the admin section, the default image would show. I want the default image when a user don't provide an image to be 'defaultimg.jpg' Thanks for your contribution -
Could not find a version that satisfies requirements aptural==0.5.2 in heroku
I trying to deploy heroku my django app and got a error like this I don’t know why the says that could not find version in apturl version in requirements.txt but there is apturl in there.And also I’m using a ubuntu os to deploy to deploy this app.I have found a previous question like this I tried that also and it didn’t work either. ERROR: Could not find a version that satisfies the requirement (from -r /tmp/build_750f707f/requirements.txt (line 1)) (from versions: none) And also in my requirements.txt file has apturl==0.5.2 in first line.Please help in advance thanks. -
How do I run previously set up environment in django?
I am very new to django I set up an environment and now later when I try open the environment it is not running. Please help. Sorry if this a noob question I am very new with django -
How to display image in python docx template (docxtpl)? Django Python
I am using python-docx-template (docxtpl) to generate a .docx file. With this data: docente= { "id":145, "cedula":"1102904313", "primer_apellido":"Salcedo", "segundo_apellido":"Viteri", "primer_nombre":"Karina", "segundo_nombre":"Soledad", "lugar_de_nacimiento":"Loja", "fecha_de_nacimiento":"1973-04-14", "ciudad":"Loja", "direccion":"Juan Montalvo 2235 y George Washington", "telefono_institucion":"072570275", "email_principal":"kssalcedo@utpl.edu.ec", "foto_web_low":"https://sica.utpl.edu.ec/media/uploads/docentes/fotos/web/low/1102904313_low.jpg", "nacionalidad":"Ecuatoriana", "pais_de_residencia":"Ecuador", "apellido":"Salcedo Viteri", "nombre":"Karina Soledad" } I have a function where I pass the data docente to the context and the path of the template: from docxtpl import DocxTemplate def generaraDocumento(request): response = HttpResponse(content_type='application/msword') response['Content-Disposition'] = 'attachment; filename="cv.docx"' doc = DocxTemplate(str(settings.BASE_DIR) + '/cv_api/templates/docx_filename.docx') context = {'docente': docente} doc.render(context) doc.save(response) return response The template where I have the data that I want to show docx_filename.docx has this: {{ docente.foto_web_low }} {{docente.nombre}} {{docente.apellido}} Fecha de Nacimiento: {{docente.fecha_de_nacimiento}} Lugar de Nacimiento: {{docente.lugar_de_nacimiento}} Dirección: {{docente.direccion}} Teléfono: {{docente.telefono_institucion}} Correo: {{docente.email_principal}} Nacionalidad: {{docente.nacionalidad}} Cédula: {{docente.cedula}} My field {{ docente.foto_web_low }} has a url where the image is, but when generating the file it only shows me the URL and not the image. How can I make the image appear in the document .docx How image can be displayed in python docx template (docxtpl). Thanks in advance. -
Oauth vs Auth0 in Django Rest Framework
Wanted to ask what is the difference between the two auth0 and oauth plus what is best (pros and cons) for application built using django rest framework. -
SearchFilter for multiple models -- Django
Using Django 3.2 with Restframework. I'm trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. I found a blog on how to use multiple Models together? I tried for following from that: Views.py class GlobalSearchList(generics.ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): query = self.request.query_params.get('query', None) users = MasterUser.objects.filter(Q(firstname__icontains=query) | Q(lastname__icontains=query) | Q(email__icontains=query) | Q(category__icontains=query)) webinar = MasterWebinar.objects.filter(Q(host__icontains=query) | Q(title__icontains=query)) section = ResourceSection.objects.filter(Q(resource_name__icontains=query)) item = SectionItem.objects.filter(Q(item_title__icontains=query)) all_results = list(chain(users,webinar,section,item)) serialize_obj = serializers.serialize('json',all_results) print(serialize_obj) #Json response is printed in console return JsonResponse(json.loads(serialize_obj), safe=False) #nothing as output In here, while printing the output it does print a json object, but doesn't return anything as output. Any cause why there is no output, where am I doing wrong? serializers.py class GlobalSearchSerializer(serializers.Serialize): def to_native(self, obj): if isinstance(obj, MasterIndividualMembers): serializer = MasterIndividualMembersSerializer(obj) elif isinstance(obj, MasterUser): serializer = MasterUserSerializer(obj) elif isinstance(obj, MasterWebinar): serializer = MasterWebinarSerializer(obj) elif isinstance(obj, MasterResource): serializer = MasterResourceSerializer(obj) elif isinstance(obj, ResourceSection): serializer = ResourceSectionSerializer(obj) elif isinstance(obj, SectionItem): serializer = SectionItemSerializer(obj) else: raise Exception("Not found in any instance!") return serializer.data … -
Django multiwidget not showing queryset
I'm trying to combine 2 modelchoicefield into a single modelchoicefield using multiwidget but the queryset is not showing up. Here's the current code that works season_1 = forms.ModelChoiceField( label='', required=False, queryset=Season.objects.all(), widget=forms.Select() ), ) season_2 = forms.ModelChoiceField( label='', required=False, queryset=Season.objects.all(), widget=forms.Select() ), ) What I've tried to do is season = forms.ModelMultipleChoiceField( label='Season', required=False, queryset=Season.objects.all(), widget=forms.MultiWidget( widgets=( forms.Select(), forms.Select(), ), ), ) -
Cannot integrate image in vue.js using django
Models has been shown and absolute url has been sent from here -
Django get request does not pass the tz_zone param
I have a client having an issue that the Django get request does not contain the tz_zone param. It seems to occur on some specific browsers. I guess it relates to the browser settings but have no way to reproduce it on my local. Is there anyone got the same issue and knows how to fix it? Thanks, Thanh Tran -
DRF: How to access "context" inside custom DecimalField class?
I am subclassing the DecimalField class from Django RestFramework and need to access context. Formatting for decimal fields includes settings that are user-selectable, so I need to access the user object (which, I assume, should be inside context) inside the to_representation() method. Via debug, I've looked at all properties of self inside my CustomDecimalField class, but, of course, I can't see class methods, so I don't know if there's an appropriate "get" method to get context. I've tried self.context (as a property), self.get_context(), and self.getcontext(), but none worked. I found this announcement re: require_context: https://www.django-rest-framework.org/community/3.11-announcement/ ...but it seems to be valid only for validation and default value methods. This seems like such a simple thing; hard to believe it is so difficult. -
Why would 15-20 minute website scrapes work at first but after a couple scrapes stop working?
By "stop working" I mean it has errors which stop the scrape. I'm thinking it's a sysadmin problem but I don't know what it is. The site is run at digital ocean on a python/django stack. I'm using selenium to scrape, python-rq for the task queue. I'm using nginx and gunicorn to run django. the rq worker has it's on .service as does the django app itself. Can anyone help? this is for a client so it's important -
submit form with multiple images
User are able to create posts via a model form. I am attempting to add a feature so once the post is created they can go on the post an and upload multiple images, but I am having some issues implementing it properly. forms.py class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } When the user uploads an image I would receive the error 'PostImages' object is not iterable and only one image would get uploaded to the database views.py def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) formImages = PostImagesForm if request.method == 'POST': formImages = PostImagesForm(request.POST, request.FILES) if formImages.is_valid(): formImages = formImages.save(commit=False) formImages.post = Post.objects.get(pk=pk) formImages.save() else: print(formImages.errors) context = { 'post':post, 'formImages':formImages, } return render(request, 'blog/post_detail.html', context) html <div class="content-section"> <form method="post" enctype="multipart/form-data" novalidate> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Testing image upload</legend> {{ formImages|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> I figured the issue was because I was only having the form submit once and it needs to submit once for each image (I could be completely wrong) Where I am currently stuck is attempting to setup a loop. I figured the … -
Django Rest Framework - How to create a custom serializer for GoogleSheets
I have some data on a Google Sheet that I'd like to serialize. I've been working on using a Django server to create a REST API that makes it easy for other apps to use. My use case is that we have several different Google Sheet Documents with data about devices we want to serialize. Python has a lot of neat libraries, like SheetFu, that basically do what we want, so I'd like to integrate that functionality with a REST API to do things like search, filter, etc. I did find a Django app, django-gsheets that combined with the Django-Rest-Framework does almost what I want, but it looks like models are fixed to a single Google Sheet Document - I need to be able to work with, and add multiple documents. I can use SheetFu to write a serializer, but I'm not sure how to integrate that with Django, and it's REST framework - can anyone point me in the right direction for this? Thanks! -
Django after login failed page is not redirecting to next
If user do successfull login then it is redirecting to next but if user can not do login then I wants to change template and wants to redirect to next page but it is not working. Views.py if request.method == 'POST': if request.META['HTTP_REFERER'].split('/')[-1] == 'bs5': template_path = 'theme/bs5_theme.html' response = LoginView.as_view( template_name=template_path, redirect_field_name='next', form_class=EmailAuthenticationForm, )(request) login.html {% if form.non_field_errors %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> Login failed. Email and password case-sensitive. </div> {% endif %} <form id="formLogin" action="{% url 'login' %}" method="post" role="form"> <input type="hidden" name="csrfmiddlewaretoken"> <input type="hidden" name="next" value="/bs5" /> <label for="id_username" class="form-label">Email address</label> <input type="username" class="form-control" id="id_username" name="username" value="{{ form.username.value }}"> <label for="id_password" class="form-label">Password</label> <input type="password" class="form-control" id="id_password" name="password"> <button class="btn btn-primary btn-lg" type="submit">Log In</button> </form> I have also try with return HttpResponseRedirect('/bs5') But then it is not showing login error. Any help would be appreciated. -
TypeError: conversion from DecimalField to Decimal is not supported
I am building a bidding website using Django. I found a problem in the models.py. I cannot execute the shell command migrate and don't know why. Could anyone help on it? Thanks in advance. models.py is as below: class User(AbstractUser): pass def __str__(self): return f"{self.username}" class AuctionItem(models.Model): ''' Description of Auction Item ''' category_choices = [ ("Fa", "Fashion"), ("To", "Toys"), ("Fo", "Food"), ("El", "Electronics"), ("Ho", "Home") ] title = models.CharField(max_length=16) description = models.CharField(max_length=128) image = models.URLField() category = models.CharField(max_length=16, choices=category_choices) create_time = models.DateTimeField(auto_now_add=True) seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="owned") initial_price = models.DecimalField(max_digits=10, decimal_places=2, null=True) current_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, default=0) class BiddingPrice(models.Model): ''' Bidding price of each item ''' bid_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) bidder = models.ForeignKey(User, on_delete=models.CASCADE, null=True) auction_item = models.ForeignKey(AuctionItem, on_delete=models.CASCADE, null=True, related_name="bidding_price") class Comments(models.Model): ''' Comments made by different users ''' comments = models.CharField(max_length=200) commentor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="comments_given") connected_item = models.ManyToManyField(AuctionItem) The error message is: TypeError: conversion from DecimalField to Decimal is not supported -
Using fixtures in django.test.TestCase
I try to use fixtures in django.test.TestCase. It works correctly, but I do it for the first time. What is the best practice in this case? from django.test import Client, TestCase class SomeTestClass(TestCase): fixtures = ['fixtures.json',] @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.get(id=1) # from fixtures cls.authorized_client = Client() cls.authorized_client.force_login(cls.user) cls.someobject = Someclass.objects.get(id=1) # from fixtures cls.anotherobject = Anotherclass.objects.get(id=1) # from fixtures def test(self): ...