Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I update a generic class-view?
I have a django app that stores information on different profiles of people. I want to be able to provide a downloadable spreadsheet and update a class-view(ListView) on the website using the same url. I don't fully understand class views yet and I'm struggling to figure out how to combine the two view functions below. I tried this: views.py class ProfileList(ListView): model = Profile #template_name = 'search.html' def get(self, request): return export_profiles(request) def export_profiles(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="profile_list.csv"' writer = csv.writer(response) writer.writerow(['Name','Title','Location','Phone','Email','Company Name','Company Size','Link']) data = Profile.objects.filter() for row in data: rowobj = [row.name,row.title,row.location,row.phone,row.email,row.GetCompany().companyName,row.GetCompany().companySize,row.url] writer.writerow(rowobj) #Clean up database return response urls.py urlpatterns = [ path('search/', views.search, name='search'), path('profiles/', ProfileList.as_view()), path('accounts/', include('django.contrib.auth.urls')), url('session_security/', include('session_security.urls')), ] This worked for downloading the file, but still didn't update the profile list with the django as_view() function. It just downloaded the csv file without erroring. This is what I currently have: views.py #Post a view of profiles on the website when a search is initiated class ProfileList(ListView): model = Profile template_name = 'search.html' @login_required def export_profiles(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; … -
How can i use MongoDB with Django Rest Framework?
I would like to use Django Rest Framework with a MongoDB database but i don't really know where to start. Is it possible to do it? I tried to look for some help online, but i found very little material. I heard there was a module called django-rest-framework but it's not longer supported, is there anything else i can use? -
How can I get exceptions from django-rest in my vue.js method?
I'm using django-rest-passwordreset for forgotten password recovery. In my Vue.js I have a method to set a new password. It works, but I need to get exceptions if a password is too short of too common etc... Here is my vue.js set_password: methods: { set_password() { axios.post('/app/reset-password/confirm/', {'password': this.password, 'token': this.token}) .then(response => { console.log(response) }) .catch(error => { console.log(error) }) } }, If I send POST request to http://localhost:8000/app/reset-password/confirm/ using RestMan to raise exceptions on django server, for example: a short password I'm getting: { "password": [ "This password is too short. It must contain at least 8 characters.", "This password is too common." ] } but in my vue.js set_password() I really cannot get these exceptions. In browser console I'm getting: POST http://localhost:8000/app/reset-password/confirm/ 400 (Bad Request) Error: Request failed with status code 400 at createError (build.js:15685) at settle (build.js:27186) at XMLHttpRequest.handleLoad (build.js:15559) If I send a good password(not short, etc...) I will 'response' in my browser console: {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …} But How can I get exceptions from my django server? -
Weird behavior while testing: It works without any problem but gives error while testing
I have a small function which rounds the Decimal numbers and my function is as follows: from decimal import Decimal, ROUND_UP def convert_decimal(decimal_number): return decimal_number.quantize(Decimal('0.01'), rounding=ROUND_UP) It works properly in my code when I run the django project without any problem. The function works without any error. But when I try to the code as below it fails with a weird error: class UtilityFunctionsTests(TestCase): def test_decimal_number(self): decimal_number = Decimal("23.54646354745375634756868") converted = convert_decimal(decimal_number) self.assertEqual(converted, Decimal("23.55")) The failing error is as follows: integration/tests/test_base_updater.py:78: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ decimal_number = Decimal('23.546463547453758025085335248149931430816650390625') def convert_decimal(decimal_number): > return decimal_number.quantize(Decimal('0.01'), rounding=ROUND_UP) E decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] entegrasyon/tests/test_base_updater.py:11: InvalidOperation -
Array convert to string in views django
i have a array in Django views and i want to convert into comma separated string, to save data into DB field like all in one. class FindInfo(object): def __info__(request): if request.method == 'POST': name = request.POST.get('name') address = request.POST.get('address') phone = request.POST.get('phone') info = {} info['name'] = name info['address'] = address info['phone'] = phone info = ["Younus", "DHA-A251", "+923228738738"] i did't get anything how to do that? and i need output like this. sting = "Ford,Volvo,BMW" -
How do I convert a Django QuerySet into a Map with List of Objects?
I need to filter and map the result to a map of string keys and list of object values. Something like in Java will result to Map<String, List<SomeDbMoel>>. -
How can i fixed PostgreSQL setup problem from Django
I created postgreSQL in django project. When i do migrate for database it's return this exception. django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' I tried postgresql_psycopg2 and pip install psycopg2-binary but not work DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'eatadil', 'USER': 'postgre', 'PASSWORD': 'realpassword', 'HOST': 'localhost', 'PORT': '5432', } } How can i fix this problem. Can you help me ? -
Row cells not showing up in django-tables2 by default, model issue?
I think there may be an issue with a work django project I inherited. I'm using django-tables2 to display info. Mostly it works in an intuitive way. However, some tables when I render them the actual columns that contain the data cells do not show up. All the table properties show up as columns, but not the data columns. I think the issue may be related to how the model is laid out. a given cell has a row and column property. Rows have a cell_set and a table property but no column_set. Tables have a row_set and column_set property. So is the issue here maybe that the Rows have no column_set property? So when it looks for data to render it isn't finding those columns. If I'm tying to get all the cells associated with a row it's a clunky process of iterating over each column looking for the cell in the cell set that belongs to that column (see below). (I can design customized columns in django_tables2 views in some cases but have an app were users can create tables themselves which need to be rendered dynamically.) As an example, here's the __str__method for Row: def __str__(self): cell_values … -
Django can open image, but not saving it to database
I created a form that will ask for a name and an image to be uploaded in django. In my views, I am using pytesseract to read the text on the image. I was able to successfully save the name and text parameters into the database, but the image itself does not save. `# models.py class Component(models.Model): Serial_number = models.CharField(max_length=20, primary_key='True', default = '') image = models.ImageField(blank=True) text = models.TextField(default = 'no text found') Good_Candidate = models.BooleanField(default=False) dimension1 = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) #forms.py class partForm(forms.ModelForm): Serial_number = forms.CharField(max_length=128) class Meta: model = Component fields = ['Serial_number', 'image', 'text', 'dimension1'] widgets = {'dimension1': forms.HiddenInput(), 'text':forms.HiddenInput()} #views.py def image_view(request): form = partForm(request.POST, request.FILES) if form.is_valid(): # make copy of the data data = request.POST.copy() # access image data through FILES and calling the name attribute image_file = request.FILES.get('image') text_content = pytesseract.image_to_string(Image.open(image_file)) data['text'] = text_content # get largest dimension text_list = [] zeros = ['O', 'o'] badChars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', … -
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.