Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customize the return object from django rest framework serializer
I want to customize the django rest framework serializer return object to a specific requirement. right now it returns the fields in a single object that is not nested. { "id": 9, "namespace": "steve", "path": "something/another", "value": "this is a value" }, and this is what I want the outcome to look like: { "id": 6, "namespace": "tempnamespaced", "path": "randompath", "value": "anothertest", "user": { "userId": "testUser1" } } So i want to add a nested object named user and add the userID value within the user. the data that is returned in the userId is actually person.username person is a model username so the data is going to look like this when it is assigned and returned: "user": { "userId": {{person.username}} } I will attach mmy code below: serializer: from rest_framework import serializers from .models import Preference from django.contrib.auth.models import User class PreferenceSerializer(serializers.ModelSerializer): # person = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),) class Meta: model = Preference fields = ('id', 'namespace', 'path', 'value') here is the get viewset: @permission_classes((IsAuthenticated)) def get_queryset(self): namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: queryset = Preference.objects.all().filter(user_id=1) if namespace and path is None: queryset = Preference.objects.all().filter(user_id=1, namespace=namespace) if namespace and path: queryset … -
Is it possible to perform mathematical operations on information entered into a Django form?
I'm trying to make a pretty simple web app with a few pages. On one of the pages, let's say I take in 6 numbers from the user. I then want to perform mathematical operations on these inputs e.g., +,-,*,/. After these operations, I want to output a single number for the user to see. Is this possible using Django forms and if so how? If it isn't possible, please recommend an alternative method in Django. -
How to fix data that is not displayed on site Heroku?
I deployed site on Django in Heroku. I've Connected PostgreSQL (also have locally), created migrations (I've checked, all tables exist). But on the site I haven't any data. What should I do, that fix this? -
How to properly run virtualenv via .sh run script (django)
I am having an issue via an apache Nearly Free Speech server (I have been following the NFS guide via this link: https://blog.nearlyfreespeech.net/2014/11/17/how-to-django-on-nearlyfreespeech-net/. I have created a run-django.sh file to properly run the application which also opens a virtualenv (I have named the folder 'venv'). These are the contents of my run-django.sh file: #!/bin/sh . venv/bin/activate exec python3 manage.py runserver On the current step of the guide I am attempting to run the run-django.sh as follows: [questionanswer /home/protected]$ ls question_answer run-django.sh venv [questionanswer /home/protected]$ cd question_answer/ [questionanswer /home/protected/question_answer]$ ../run-django.sh .: cannot open bin/activate: No such file or directory How is this not detecting my directory of 'venv/bin/activate' ? -
Refreshing OAuth2 Access Tokens in Serverless Application
I'm creating a project in Django (v2.2) with a REST backend though Django Rest Framework (v3.9.4). This REST API is consumed by both SPAs and headless applications running on external servers. All views require user authentication with appropriate permissions. The front-end SPAs are able to use Session Authentication and pass this along to the REST API no problem. However, Session Authentication is not appropriate for headless servers and autonomous functions that we want to be able to consume the API as well. I've settled on using Django OAuth Toolkit (v1.2.0) to provide authentication using OAuth2. My issue is as follows. Developers who wish to consume the API from some headless environment can generate an access token using password-based or client credentials grant type (or any of the other types, really). This gives them an access token, an expiry time, and a refresh token. For applications which have a stateful server, they can store the access and refresh tokens in a file, environment variable, etc. When the token expires, they can use the refresh token to acquire a new access token, and overwrite the file or environment variable so that it is available going forward. However, some of our applications exist … -
SelectRelatedMixin in braces
How to use select_related attribute in the braces module in django. Please explain. I looked into the docs but it was pretty difficult to understand. Thanks -
Django Singal Populating one model if another model is populated
I have a Django project with two apps.. one is contact and annother is contactus my contact model is: project/contact/models.py below: from django.db import models class ContactList(models.Model): phone = models.CharField(max_length=15) email = models.EmailField() and my contactus model is: project/contactus/models.py below: from django.db import models class ContactUs(models.Model): subject = models.CharField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField() message = models.TextField() I want when ContactUs class gets data by user input, in the same time, ContactUs's phone and email should be populated in ContactList class I created two signal.py file in my two apps but tried a lost with some code, i failed.. i think this is the very easiest task for expert.. Can anyone help me to solve this problem? -
Django Form not saving
I am relatively new to django and i'm trying to implement some modelforms. My page consists of two views, a Politics section and a Sports section, each one with the same form for making comments (my comment model is named Comentario). It has a field for the content and a field for the section the comment belongs to. Both views are basically the same so I'm going to showcase just the politics one: from django.contrib import messages from django.shortcuts import render from django.views.generic import CreateView from usuarios.models import Usuario from .forms import CrearComentario from .models import Comentario usuarios = Usuario.objects.all() comentarios = Comentario.objects.all() pag = '' def politics(request): if request.user.is_authenticated: if request.method == 'POST': form = CrearComentario(request.POST, instance=request.user) if form.is_valid(): messages.success(request, 'Publicado!') pag = 'politics' form.save() form = CrearComentario() else: form = CrearComentario(request.POST,instance=request.user) else: messages.warning(request, 'Comentario no válido') form = CrearComentario(request.POST) return render(request, 'main/politics.html', {'usuarios': usuarios, 'comentarios': comentarios, 'form': form}) In case you're wondering, 'pag' is a control variable that is checked by my signals.py file to update the 'pagina' field I had trouble with the submit buttons in my custom modelsforms, the form displays correctly, and when I write something in the form and submit it, it displays a … -
organize urls in django
I have a problem with my urls, first of all here my urls.py: from .views import ( CouponListView, CouponDetailView, buy_coupon, UserCouponListView, CouponOnResaleCreateView, CouponOnResaleListView, ) from django.urls import path coupons_patterns = ([ path('', CouponListView.as_view(), name = 'list'), path('<int:pk>/<slug:slug>/', CouponDetailView.as_view(), name = 'detail'), path('create/<int:pk>/<slug:slug>/', CouponOnResaleCreateView.as_view(), name = 'create'), path('<slug:slug>/', UserCouponListView.as_view(), name = 'user'), path('coupon/<int:pk>/<slug:slug>/buy/', buy_coupon, name = 'buy_coupon'), ], 'coupons') Well, I want to add another "pattern" of urls so to speak, that is, the "pattern" of urls that I have is: coupons: name and I want to add one like this: coupons_on_resale: name, but without having to create another app. How should I do it? It occurs to me to create other patterns like the one I showed before and include it, but is it good practice? Are there other ways? I want a scalable, clean and easy to maintain structure in my urls. Thanks for your suggestions in advance! -
Django-Rest-Framework POST request to ManyToMany Field
I have a django model that is a message. It has a name which is a CharField, then also an array of users which is a ManyToManyField. So This is what my API looks like: [ { "id": 13, "content": "hej", "date": "2019-07-09", "sender": { "id": 1, "username": "william" } }, { "id": 14, "content": "hej william", "date": "2019-07-09", "sender": { "id": 3, "username": "ryan" } } ] What I've tried to send via postman POST: { "content": "Hello", "sender": {"username": "william"}, "date": "2019-09-02" } The Error I get: sqlite3.IntegrityError: NOT NULL constraint failed: chat_message.sender_id ManyToManyField(Userprofile=User): class Message(models.Model): sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sendermessage") content = models.CharField(max_length=500) date = models.DateField(default=date.today) canview = models.ManyToManyField(UserProfile, blank=True, related_name="messagecanview") class Meta: verbose_name_plural = 'Messages' def __str__(self): return "{sender}".format(sender=self.sender) -
Return existing record rather than creating Rest API framework
In my API, I have a create view tied that references another record OneToOne. However, occasionally it seems that users send through two requests at once and the second fails due to a duplicate record clash: class CreateProfileLink(generics.CreateAPIView): def perform_create(self, serializer): ins = serializer.save(user=self.request.user) serializer_class = ProfileLinkSerializer Is there a way I could override the create method to return the record if it already exists rather than creating it? -
How to reload a custom command from inside shell?
I'm looking to test some custom commands and wondering if there's a way to reload a command once I'm already inside shell? ie: > python manage.py shell > from django.core import management > management.call_command('get_embeds') > # make some changes to file > # reload command > management.call_command('get_embeds') We're running on a vagrant VM so running something such as python manage.py get_embeds takes a bit of time to load each time I want to test the script. -
How to do many to one relationship in Django
I am doing a many to one relationship but I get a prompt that the field person in the report is without a default. I tried setting the default to an empty space, I get an IntegrityError: NOT NULL constraint failed class Person(models.Model): person_name = models.CharField(max_length=255) person_location = models.CharField(max_length=255, null=True) classReport (models.Model): person = models.ForeignKey( Person, related_name='people', default="", on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_description = models.CharField(max_length=255) -
Could not parse the remainder: '{{' from '{{' , while inside html if loop
I am creating a table in html, but if the value that will be outputted is equal to the value above I want to merge the cells. I am sure that all the variables work as they are correct later. However, when I use them in the if loop I get an error <table> <tr> <th>id</th> <th>peptide_id</th> <th>protein_id</th> <th>group_id</th> <th>search_id</th> <th>peptide_parsimony</th> </tr> {% for elem in elem_list %} <tr> {% for sub_elem in elem %} elem.2 = {% if {{ elem.2 }} == {{sub_elem}} %} <td> </td> {% else %} <td onclick="location.href='/protein/proteinseq/{{ elem.1}}/{{ elem.2 }}/{{ elem.4 }}/'" style = " text-decoration: underline; cursor: pointer" >{{ sub_elem }}</td> {% endif %} {% endfor %} </tr> {% endfor %} </table> This gives me the error : Could not parse the remainder: '{{' from '{{' Does anybody know how to merge cells in a specific column if they have the same value, preferably with an example as I am new to html and JS? Thanks! -
Cannot get send_mail to work in Django 2.3. No error message. No log message indicating email is sent or not sent
So I have been scouring the internet trying to get my code to work and i feel like I've read every post about this issue and still haven't figured out why I can't get my form to send me an email. I created a class based view which inherits FormView and have written a method that should send an email to me anytime there is a post-request. For the life of me, I can't get it to work. For those who are in the same boat, this is one post that seemed promising so hopefully this will help you even if it doesn't help me: Django sending email My views.py: (both email addresses are the same. It should simulate me sending an email to myself.) class CandRegisterView(FormView): template_name = 'website/candidate_register.html' form_class = UploadResumeForm def contact_email(self, request): first_name = request.POST.get('first_name') if first_name: try: send_mail(first_name, 'Their message', 'myemail@gmail.com', ['myemail@gmail.com'], fail_silently=False) return HttpResponse('Success!') except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('') else: return HttpResponse('Makes sure all fields are entered and valid.') my forms.py: from django import forms class UploadResumeForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'First Name', }), required=True) my settings.py (the variables are stored in a .env file and … -
How to fix 'CustomUser' object has no attribute 'get'
I am trying to get some data from the database to display on the view, but I shows me an error that I have code that is not even there. I have the model CustomCliente: class CustomCliente(AbstractUser): email = models.EmailField(unique=True, null=False, blank=False) full_name = models.CharField(max_length=120, null=False, blank=False) password = models.CharField(max_length=40, null=False, blank=False) username = models.CharField(max_length=110, unique=True, null=False, blank=False) And I have a view with the following method: def mostrar_relatorio(request, id): aluguel = Aluguel.objects.get(cliente=CustomCliente.objects.get(id=id)) if aluguel is not None : context = {'aluguel', aluguel} template_name = 'relatorio.html' else: raise Http404 return render(request, template_name, context) And my urls patterns from that model is: urlpatterns = [ path('cliente/<int:id>', CustomCliente, name='relatorio'), ] What happens is that when I try to access the following url 127.0.0.1:8000/cliente/2, I get the error: 'CustomCliente' object has no attribute 'get. Even though I don't even have anywhere in my code calling CustomCliente.get. I have tried shutting down the server and trying again, rewrited the code, but it doesn't seem to work. -
Import error: oracle client library with python wsgi
When I deployment don't get any problem to run, but when I trying run with apache wsgi got this error: DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open shared object file: No such file or directory" Tried to use ldconfig and setup on environment LD_LIBRARY_PATH but didn't worked. The server is a linux x64 with cx_oracle 7.2.0 and django 1.11.22 with python 2.7.15+ and installing libaio. root@webservice:/opt/instantclient_11_2# ls -la lrwxrwxrwx 1 root root 17 Jul 10 15:41 libclntsh.so -> libclntsh.so.11.1 -rwxrwxr-x 1 root root 53865194 Aug 24 2013 libclntsh.so.11.1 -r-xr-xr-x 1 root root 7996693 Aug 24 2013 libnnz11.so lrwxrwxrwx 1 root root 15 Jul 10 15:41 libocci.so -> libocci.so.11.1 -rwxrwxr-x 1 root root 1973074 Aug 24 2013 libocci.so.11.1 -rwxrwxr-x 1 root root 118738042 Aug 24 2013 libociei.so -r-xr-xr-x 1 root root 164942 Aug 24 2013 libocijdbc11.so -r--r--r-- 1 root root 2091135 Aug 24 2013 ojdbc5.jar -r--r--r-- 1 root root 2739616 Aug 24 2013 ojdbc6.jar -rwxrwxr-x 1 root root 192365 Aug 24 2013 uidrvci -rw-rw-r-- 1 root root 66779 Aug 24 2013 xstreams.jarre root@webservice:/opt/instantclient_11_2# cat /etc/ld.so.conf.d/oracle-instantclient.conf /opt/instantclient_11_2 -
DRF - How to correctly Update a Foreing Key
I'm having trouble updating my User object since my request send a "customer id" (example: 12) but my serializer y waiting for a dict To be more clear, here is the message I get: Invalid data. Expected a dictionary, but got int. What I'm trying to acomplish is to update my customer field from my user which is a ForeingKey here is my viewset.py: def update(self, request, *args, **kwargs): try: customer = BankCustomer.objects.filter(id=request.data.get('customer')) serializer = UserSerializer(customer, data=request.data) except BankCustomer.DoesNotExist: return Response(None, status=status.HTTP_400_BAD_REQUEST) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_200_OK) user serializers.py: class UserSerializer(serializers.ModelSerializer): customer = BankCustomerSerializer() email = serializers.EmailField() class Meta: model = User fields = ('id', 'email', 'name', 'lastname', 'type', 'customer', 'is_blocked') def update(self, instance, validated_data): instance.customer = validated_data.get("customer", instance.customer) instance.email = validated_data.get("title", instance.email) instance.name = validated_data.get("name", instance.name) instance.lastname = validated_data.get("lastname", instance.lastname) return instance customer serializer: class BankCustomerSerializer(serializers.ModelSerializer): users = serializers.PrimaryKeyRelatedField(many=True, source='customer_r', queryset=User.objects.all(), default='') class Meta: model = BankCustomer fields = ('id', 'customer', 'ruc', 'address', 'phone', 'users') -
Requested setting INSTALLED_APPS, but settings are not configured
When I try to run my scraper in Django I get the following error. This happened when I tried to put the scraped data into the database using the built-in Django models. traceback and error: /usr/bin/python3.6 /home/xxxxxx/Desktop/project/teo/movierater/scrap.py Traceback (most recent call last): File "/home/xxxxxx/Desktop/project/teo/movierater/scrap.py", line 7, in <module> from teo.movierater.api.models import * File "/home/xxxxxx/Desktop/project/teo/movierater/api/models.py", line 3, in <module> class Author(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I put it in bin/activate: export DJANGO_SETTINGS_MODULE=mysite.settings Here is the code snippet from scraper.py: import django import os import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from teo.movierater.api.models import * os.environ['DJANGO_SETTINGS_MODULE'] = 'movierater.settings' django.setup() My project structure and the settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'movierater.api', ] wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movierater.settings') application = get_wsgi_application() -
Axios POST request from Vuejs to Django rest framework
I create a rest api with vuejs and django rest framework. The probleme is when i made a post request. With a get request he works but not with a post request. axios .get('http://127.0.0.1:8000/api/users/') .then(response => (this.info = response.data)) axios .post('http://127.0.0.1:8000/api/users/', { params : { email : "test@gmail.com", username : 'test' } }) .then(response => (this.info = response.data)) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('', include(router.urls)), ] My get request works but not my post request. In my console i have : http://127.0.0.1:8000/api/users/?username=test&email=test@gmail.com 400 (Bad Request) And when i watch network i have {"username":["This field is required."]} I don't uderstand why i have this error. -
Passing Django Model to Javascript
I'm trying to pass my complete model with it fields because I need to use it on a Javascript function. I've tried everything I've seen (using json.dumps(), serializers..) and anything worked for me. I've donde the query this way: cancion = Cancion.objects.get(pk = cancion_id) The reason is because I need specific data depending on the id. Doing this, it throws me the following error: 'Cancion' object is not iterable So I don't find the correct way I have to do this stuff and use the model field in my javascript function. The field I want to use is a .mid file. If you have any doubts about the code feel free to ask anything -
How do I greet the user when they log into my website?
I'm trying to greet the user when they log into my django website, but using the django login has made it too difficult to send a message to my template and redirect to the new url behind the scenes. How can I greet the user(preferrably with that user's name) on the template of the url I redirect to? I've tried working with messages, but redirecting to the new url always overrides the message and it never appears. Regular logging in and out works fine, I'm just trying to figure out how to display welcome text to the user to let them know they have successfully logged in and are using their own account. views.py def loginPage(request): return render(request, "registration/login.html") def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: #Success! messages.success(request, "Welcome " + user) #NOT WORKING :( login(request, user) else: return HttpReponseRedirect("/DataApp/accounts/login/") settings.py LOGIN_URL = "/DataApp/accounts/login/" LOGIN_REDIRECT_URL = "/DataApp/search/" base.html <!-- This is nested in a div tag inside of the html class body --> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}" {% endif %}> {{ message }}</li> {% … -
How to fix django model manager to work with serializer
I have used model managers in my app to do the heavy lifting. Was able to use it well for the web version but having difficulty with the serialization of the Query to move data into a mobile app via an API. The model manager works fine for the web based interface. Trying to serialize so data can get into React Native for mobile app. The override of the queryset seems to be the way to go. here is the code in the serializer: class UserBeltsSerializer(serializers.ModelSerializer): class Meta: model = UserBelts fields = ('__all__') here is the code in .api: class SingleUserBeltViewSet(generics.ListAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserBeltsSerializer def get_queryset(self): beltlist = UserBelts.objects.all_belts(user=self.request.user) return beltlist error message is as follows: AttributeError at /api/singleuserbelts Got AttributeError when attempting to get a value for field `user` on serializer `UserBeltsSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'user'. -
How to combine Django forms, formsets, and formwizard for multi-step form
I'm looking to replicate the following form structures in a Django application. These are already coded in a PHP application. On the first page there are two separate forms for entry, where the top form is slightly different from the bottom form. At the moment they are two separate forms under forms.py, but could be combined together: forms.py: # forms.py from django import forms from .models import Data2, Data3 class ExampleEntryFormTop(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_top = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data3.objects, empty_label=None, widget=forms.RadioSelect) data4 = forms.MultipleChoiceField(choices=( ('alpha', 'Alpha'), ('beta', 'Beta'), ('gamma', 'Gamma')), widget=forms.CheckboxSelectMultiple ) class ExampleEntryFormBottom(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_bottom = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data2.objects, empty_label=None, widget=forms.RadioSelect) class ExampleEntryFormPage2(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_top = forms.IntegerField() data_bottom = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data2.objects, empty_label=None, widget=forms.RadioSelect) On the second page of the wizard I need to pre-load the next three days. I've been using the following to create the formset: forms.py: def get_example_set(): … -
Django - ORM - datetime field different formats
i am currently working on a Django app where every single DateTimeField should have the exact same format... to start with, this is my abstract model: from django.db import models class AbstractModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True Both created and updated field have the same format, like this: 2019-01-01 12:12:12.123456+00 # right BUT: When i add some other DateTimeField to any model, like: some_other_field = models.DateTimeField() and save it via django-admin, it gets this format in database: 2019-01-01 12:12:12+00 # wrong WHY ?! Right now i have two different DateTimeField formats in my database, which is conceptually very bad.. Can anybody help me out? I simply want one format (the upper one) in every single datetime field.. Settings: LANGUAGE_CODE = 'en-US' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True