Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save fomrset data
I am trying to display some data from my contact table and update it in the same time, but the data that I should passe to the formset is always empty so the formset is unbound that's mean invalid formset,the form data are displayed but they can't be edited, so any solution ?? views.py def see(request,slug): data = dict() ProductFormSet = modelformset_factory(Contact, fields=('Nom','post','Tel','email','contact_type','client'), extra=0) client = get_object_or_404(Client_Data, slug=slug) attig = request.POST or None formset = ProductFormSet(data=attig, queryset=Contact.objects.filter(client=client)) print(formset.is_bound) if request.method == 'POST' and formset.is_valid(): formset.save() else: for form in formset: form.fields['client'].queryset = Contact.objects.filter(client=client.id) context = {'form': formset} template_name = 'Client_Section/partial_client_contact.html' data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) forms.py class Contact_Form(forms.ModelForm): class Meta: model = Contact fields = ('Nom','post','Tel','email','contact_type','client') def __init__(self,*args, **kwargs): super(Contact_Form, self).__init__(*args, **kwargs) self.fields['client'].queryset = Client_Data.objects.all() parital_client_contact.html <form method="post" class="js-book-create-form"> {% csrf_token %} <div class="modal-body" > {% include 'Client_Section/partial_client_contact_form.html' %} </div> <br><br> <div style="pos"> <button style="float : right" type="submit" class="btn btn-primary ">Update Contacts</button> <button style="float : right" type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> parital_client_contact_form.html : {% block content %} {{form.as_p}} {% endblock %} -
python manage.py shell nothing happening
I'n new to django and I'm practicing through Django's Documentation on setting up my first project. All worked well until it asked to invoke the Python shell with the command python manage.py shell As a result, nothing really happens apart from showing the following text: Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) Could someone please help? I tried finding an answer in very different sources but no one has really answered it. Thank you in advance. -
Saving a tweaked form request data in Django
My form accepts URL as input and before the URL can work it should have 'http' or 'https', example: http://apexrice.com. So my issue is that some times users enter the url without https. so am trying to tweak the data and add http or https here's a sample code: def get_link(request): form = shortenerModelForm(request.POST) if form.is_valid(): check_http = form.cleaned_data['link'] print(check_http) if request.is_secure() and not check_http.startswith('https'): link = f'https://{check_http}' u = form.save(link) elif not request.is_secure() and not check_http.startswith('http'): link = f'http://{check_http}' u = form.save(link) else: u = form.save() return render(request, 'index.html', {'form': form, 'users': users}) return render(request, 'index.html', { 'form': form, }) So doing form.save() does not save the changes to databese, but it saves the original data. Please how do I save the changes to the database. -
Django many to one reverse query on the same field
I have a one to many relationship between two tables ... Item - id, title ItemAttribute - id, item_id, attribute_code(string, indexed) where attribute_code can have values for colors, sizes, qualities, dimensions, etc, - like codes for 'Blue', 'Black', 'White', 'S', 'L', 'XL', '250g', '400g', etc Question: How do I query for all Items that are either ('Blue' OR 'White') AND 'XL' I prefer using Django's ORM, but if someone could even help out with raw SQL it would do just fine. Thanks. -
Google Storage creating signed url for multiple objects at once
I have been succesfully using signed urls for my image and video content in google storage. My Django Apis return 100 Google Storage objects and creating 100 signed urls takes literally a long time. Is there any other way to generate signed urls faster or multiple of them at once? -
AttributeError: module 'django.conf.global_settings' has no attribute 'X'
I am writing some tests in a Django project that use settings. When I run what I think is a correct test, I get the error AttributeError: module 'django.conf.global_settings' has no attribute 'X' As a contrived example, I add a constant to my settings file: FOO = 'foo' Then I write a test for it: from django import test from django.conf import settings class FooTest(test.TestCase): def test_foo(self): self.assertEqual('foo', settings.FOO) The last line gives the error AttributeError: module 'django.conf.global_settings' has no attribute 'FOO' I assume I have something configured incorrectly in my project. For what it's worth, I am developing with IntelliJ IDEA and in Project Settings, I have the Django facet set to my settings file at settings/development.py in my project. When I add a breakpoint or print() call to my this file, I see that it is executed. So why do I get this error? -
Get access token from cookies via RestSharp
We have a Django application we need to integrate with, and the developers of the system has no exposed API calls, at this point for us to hit. They have noted to use that we can crab the access_token via a POST scrap, as we don't want to expose their login screen to our API users, but we're stuck trying to get the token cookie after the redirect. Basically, we're using RestSharp to do a simple POST of form data to the page indicated by the developers in the 's action attribute, which just results in a response back to the same page, via RestSharp, but the access token is set when the site redirects to the landing page after successful authentication. Is there a way in either RestSharp, or the standard WebClient to perform the POST but wait for the site to redirect, so the cookies can be set accordingly? Their upgrade path for a viable API set is only December, unfortunately, the data we're exposing is for government purposes, and this project cannot wait that long. Here's the URL path we're hitting: POST: url=https://www.bigdata.analytics/login Once you login here, it sets a result and then redirects the users back … -
Django Enumerate my related many to many objects
I have those models: class Question(models.Model): description = models.CharField(max_length = 255) class Quiz(models.Model): name = models.CharField(max_length = 32) questions = models.ManyToManyField(Question, related_name = 'questions') Im interested to have a property where it returns the index value for the related quiz. So when i do like this in my views: def view_quiz(request,slug): quiz = Quiz.objects.get(name = slug) questions = quiz.questions.all() return render(request = request, template_name = 'main/quiz.html', context = {'quiz': quiz,'questions': questions}) I would be able also to access the index of the question. I was thinking to create a property to question model like this: class Question(models.Model): description = models.CharField(max_length = 255) options = models.ManyToManyField(Option, related_name = 'options',default = None) @property def question_number(self): return 'index of the related quiz' But i could not figure out the code for that property so it would return the index of the related questions. Any suggestions? Thanks -
Why does using a django BooleanField in models.py cause a TypeError?
I'm creating a model for a todo list program. Here is my models.py file: from django.db import models from django.contrib.auth.models import User class Todo(models.Model): content = models.CharField(max_length=250) completed = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.content When I try to run python manage.py migrate after I make migrations, it gives me this error: TypeError: memoryview: a bytes-like object is required, not 'bool' I'm not sure how to fix this, but I'm guessing it has something to do with the Boolean Field. Thanks in advance! -
Django Rest Framework: Serialize User ManyToMany field by username
I have a field: invited_guests = models.ManyToManyField(User, blank=True) A requirement is IDs are not allowed to be exposed, instead username should be used. How can I serialize this field based on username instead of id for create and update view? -
Django 'Login' Page
When I run the server, everything works but I have this problem on the website: The idea is that when someone click on "login" the user will go on the "login" page and actually it goes on localhost/login but when it's on the /login page it shows the "registration" form and not the "login" page that should be the login.html file. It shows the register.html file instead. The code seems right and I revisited it several times but I can't see the error. account/login.html {% extends 'base.html'%} {% block content %} <h2> Login</h2> <form method='post'> {% csrf_token%} {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color: grey;"> {{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style='color:red;'> {{field.help_text}} </p> {% endfor %} {% if login_form.non_field_errors %} <div style="color: red"> <p>{{login_form.non_field_errors}}</p> </div> {% endif %} </p> {% endfor %} <button type="submit"> Login </button> </form> {% endblock content %} account/register.html {% extends 'base.html'%} {% block content %} <h2> Register</h2> <form method='post'> {% csrf_token%} {% for field in registration_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color: grey;"> {{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style='color:red;'> {{field.help_text}} </p> {% … -
Return Username and ID with Django Rest Framework Simple JWT TokenRefresh
I'm using Django Rest Framework and django-rest-framework-simplejwt for authentication. The data being sent is being consumed by react. So far I've been able to subclass the TokenObtainPairSerializer to return both the username and ID when logging in / getting a new token. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super(MyTokenObtainPairSerializer, self).validate(attrs) data.update({'user': self.user.username}) data.update({'id': self.user.id}) return data I'm trying to have a users username and id returned when the token is refreshed as well. This, however, does not work: class MyTokenRefreshSerializer(TokenRefreshSerializer): def validate(self, attrs): data = super(MyTokenRefreshSerializer, self).validate(attrs) user = self.context['request'].user data.update({'user': user.username}) data.update({'id': user.id}) return data Here, the username is always returned as an empty string and the ID is always returned as null. I've tried many different ways, including trying to update this information in the view itself, but can't seem to get it to work. I've noticed that TokenRefreshSerializer subclasses serializers.Serializer while TokenObtainPairSerializer subclasses TokenObtainSerializer which itself authenticates a user using Django authentication. This appears to require a password (like when a user logs in) but obviously that wouldn't be provided when simply refreshing a token. My question is, how can I return the username and id (or any arbitrary information) about the current user when the … -
Django not respecting database test settings
For context, I'm trying to use the admin user and password to run tests with a PostgreSQL database. There seems to be a workaround, but the Django docs state that this should not be necessary. Django seems to ignore test specific database connection settings. According to the settings docs for test DB users the following database configuration should override the user and password when connecting to the database for running tests: # settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("DATABASE_NAME"), "USER": os.environ.get("DATABASE_USER"), "PASSWORD": os.environ.get("DATABASE_PASSWORD"), "HOST": os.environ.get("DATABASE_HOST"), "PORT": os.environ.get("DATABASE_PORT"), "TEST": { "USER": "postgres", "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), } } } One caveat in the docs is that the test USER and PASSWORD settings are marked as being Oracle specific (i.e., MySQL and MariaDB only). Is this the reason for it not using these settings when connecting to a PostgreSQL database? This is an Oracle-specific setting. Instead of using postgres and POSTGRES_PASSWORD, Django uses DATABASE_USER and DATABASE_PASSWORD to connect to the database when running tests. -
Send real time data to Django frontend
I've been making some questions about this topic but i still did not come to a conclusion and i'm still completely uncertain on what approach should i take here, so i decided to make a new question with all the details, in order to be as specific as possible. The problem: i have an external Python script (we will call data-collector) that retrieves trades from various cryptocurrency markets in real time and prints them to my console; this script is up and running on its server and its printing trades, it works flawlessly. On the other side, i have a Django application. When the user opens a page on my Django application, they should receive the trades for a specific market. Example: user opens market ETHUSD > user needs to receive in real time the trades for ETHUSD from data-collector. So i need to find a way to make data collector send the trades to my Django application when the page is opened. I don't need to store that data on a database, i only need it to be seen by the user, nothing else. POSSIBLE APPROACHES 1) Store on a Database and poll I thought of updating the data … -
Allow Users to distribute Django Web App with data
I'm creating a progressive web app with Django. I know the web app saves the state for offline use and one can install it locally to their computer. However, is there any way for that user to distribute their version of the website with saved cache and browser database to another person who doesn't have internet? Say via flash drive or from one local PC to the next without internet. -
When building an API for my e-learning platform project i always get the RuntimeError. Why is that?
RuntimeError at /api/subjects/ class not set defining 'Token' as . Was classcell propagated to type.new? Request Method: GET Request URL: http://127.0.0.1:8000/api/subjects/ Django Version: 1.8.6 Exception Type: RuntimeError Exception Value: class not set defining 'Token' as . Was classcell propagated to type.new? Exception Location: C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\authtoken\models.py in , line 16 Python Executable: C:\Users\uthman\PycharmProjects\Educa\venv\Scripts\python.exe Python Version: 3.8.1 Python Path: ['C:\Users\uthman\PycharmProjects\Educa\educa', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32', 'C:\Users\uthman\PycharmProjects\Educa\venv', 'C:\Users\uthman\PycharmProjects\Educa\venv\lib\site-packages', 'C:\Users\uthman\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\uthman\AppData\Local\Programs\Python\Python38-32\lib\site-packages'] Server time: Fri, 10 Apr 2020 13:58:09 +0000 -
API Call dont work, Unexpected token < in JSON at position 1
I'm trying to GET data from the API, but when I look at the console I get the follow Error: SyntaxError: Unexpected token < in JSON at position 1 and Uncaught (in promise) TypeError: Cannot read property 'results' of undefined But when I look in the networktab, I see that the call will be done without any error. (Status 200) Console Network-tab I get also the following error in the console: import { apiService } from "@/common/api.service"; export default { data() { return { Customers: [], next: null, loadingCustomer: false, } }, methods: { getCustomerData(){ let endpoint = "/api/Kunden"; if(this.next){ endpoint = this.next; } this.loadingCustomer = true; apiService(endpoint).then(data => { this.Customers.push(...data.results); this.loadingCustomer = false; if (data.next){ this.next = data.next }else{ this.next = null; } }); } }, created(){ this.getCustomerData(); } } apiService.js import { CSRF_TOKEN } from "./csrf_token.js" function handleReponse(reponse) { if (reponse.status === 204) { return ''; } else if (reponse.status === 404) { return null; } else { return reponse.json() } } function apiService(endpoint, method, data) { const config = { method: method || "GET", body: data !== undefined ? console.log(JSON.stringify(data)) : null, headers: { 'Content-Type': 'application/json', 'X-CSRFTOKEN': CSRF_TOKEN } }; //FETCH to ENDPOINT, its retured promis return … -
django-rest-auth create userprofile
I'm using django-rest-auth to handle login and registration. The problem that I stumbled upon is that I'd like to add some custom fields to the default django User model. I've seen they covering this on their docs and I've tried replicating their example from here, but when I am making a PUT request for the newly created field from the userprofile I get this error: RelatedObjectDoesNotExist at /rest-auth/user/ User has no userprofile. Request Method: PUT Request URL: http://localhost:8000/rest-auth/user/ Django Version: 2.2.10 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no userprofile. Exception Location: /home/terkea/django_react_template/src/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __get__, line 415 Python Executable: /home/terkea/django_react_template/src/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/terkea/django_react_template/src', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/terkea/django_react_template/src/venv/lib/python3.6/site-packages'] Server time: Fri, 10 Apr 2020 14:56:41 +0000 This is my model from django.db import models from django.conf import settings from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=100, default=None) and here's my serializer: from rest_framework import serializers from rest_auth.serializers import UserDetailsSerializer class UserSerializer(UserDetailsSerializer): company_name = serializers.CharField(source="userprofile.company_name") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('company_name',) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) company_name = profile_data.get('company_name') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data and company_name: profile.company_name = company_name … -
Loading Django custom UserManager properly
I have extended the Django base User object like described in the manual. Somehow my custom UserManager doesn't work anymore, my migrations don't work anymore. I think it has to do with the way I load it. File /app/models/UserEx.py: from MyApp.managers import UserExManager class UserEx(AbstractUser): class Meta: verbose_name = "User / Participant" verbose_name_plural = "1. Users / Participants" objects = UserExManager # fields below... File /app/managers/UserExManager.py: from django.contrib.auth.models import BaseUserManager from django.db import models class UserExManager(BaseUserManager): def create_user(self, email, password, **extra_fields): # ... return user def create_superuser(self, email, password, **extra_fields): # ... return user File /app/managers/__init__.py: from .UserExManager import UserExManager File /app/MyApp/settings.py: AUTH_USER_MODEL = 'MyApp.UserEx' SETTINGS_EXPORT = [ 'AUTH_USER_MODEL' ] In UserExAdmin.py I have admin.site.register(UserEx, UserExAdmin) at the bottom. In the code, I first had objects = UserExManager(), with (). This doesn't work anymore out of a sudden it says web_1 | File "/app/MyApp/models/UserEx.py", line 30, in UserEx web_1 | objects = UserExManager() web_1 | TypeError: 'module' object is not callable I removed the () and from that point it messed everything but then the User -> UserEx connection fails and upon login in in Django, all the stuff I extended went missing. How do I load this correclty, maybe … -
django many to one in models
in this code i want to create a new model in this new model every area from Area has more than one city from Cities how to do that class Area(models.Model): area = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.area) class Cities(models.Model): city = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.city) -
Issue in running django server while pulling code from GIT
I am working on a project which also contains a got repo initialized in it, we are multiple people working on same project but on different branches,my scenario is one of my friends pushes code to his branch then i pull that code from his branch so now i am having merged code(his and mine) now i push the code to my branch that contains final code. Now the problem is when i pulled code from his branch then my django server isn't starting, i think there is a directory issue, one more problem is when is witch to project view in pycharm it shows limited files with yellowish background and when i switch to project files it shows all files i am attaching both pictures My project directory project View Project_files_vies -
Django: How to verify a form whose fields are generated from a queryset in the forms __init__ method?
I have some trouble coming up with a good solution to validating a form whose fields are set in its init method. Quickly explaining my models: Every Product is supposed to have Variations, with each variation in turn having multiple VariationOptions. Every Product can have multiple Variations, like 'Color' or 'Material' Variations can have multiple VariationOptions (ManyToMany-Relation), like 'red' or 'concrete' When rendering the AddToCartForm, every Variation corresponds to a ChoiceField with the VariationOptions being used as choices for said ChoiceField. (see forms.py) Since every product can have different variations and therefore different fields, the AddToCart Form must be generated dynamically from a queryset containing the products variations (views.py), or at least thats what I'm thinking right now. My Questions: How can I validate this kind of form? Do you see a better way of achieving the same idea? I would very much appreciate your help. Thanks in advance! Here is my simplified code: MODELS.PY class Product(models.Model): .. class Variation(models.Model): name = models.CharField() product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variations') options = models.ManyToManyField(VariationOption, blank=True) class VariationOption(models.Model): value = CharField() FORMS.PY class AddToCart(forms.Form): quantity = forms.PositiveIntegerField() # for every variation get all its choices and add new ChoiceField to form def __init__(self, variations, … -
Authenticating a User, without using Django rest framework?
Hey everyone I have a couple questions in regards to refactoring some old api endpoints as far as authentication goes. I have a view for example... @csrf_exempt # PARAMETERS: username, password def submit_offer(request): """Submit an offer""" username = request.GET.get("username") password = request.GET.get("password") # Authenticate user to set instance.user value into BuyerForm user = authenticate(username=username, password=password) if not user: # Always want our potential Buyer to be logged in & authenticated return JsonResponse({'message': 'Please login to continue.'}) if request.method == 'POST': form = BuyerForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) # sets current user as Buyer.user instance.user = user instance.save() return JsonResponse({'success': True}, status=200) else: data = form.errors.as_json() return JsonResponse(data, status=400, safe=False) else: return JsonResponse(data={'status': 403}) Now every view that uses a form, and needs to grab the instance.user, has the same lines of code below...now I thought using request.user would do the job, but when testing that way I am getting back an AnonymousUser, which is kind of confusing me? username = request.GET.get("username") password = request.GET.get("password") # Authenticate user to set instance.user value into BuyerForm user = authenticate(username=username, password=password) Now is there a better way to authenticate the user, like in a regular django view using request.user, rather than having … -
django serialization with nested object
I have real hard time to understand how django serializer works. I have an api_view function in charge to create a BGES object with a nested object Laboratoire such that : @api_view(['POST']) def add_bges(request): laboratoire_data = request.data.pop('laboratoire') laboratoire_serializer = LaboratoiresSerializer(data=laboratoire_data) if laboratoire_serializer.is_valid(): laboratoire_serializer.save() request.data["laboratoire"] = laboratoire_serializer.data["id"] bges_serializer = BGESSerializer(data=request.data) if bges_serializer.is_valid(): bges_serializer.save() return Response(bges_serializer.data, status=status.HTTP_201_CREATED) return Response(bges_serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(laboratoire_serializer.errors, status=status.HTTP_400_BAD_REQUEST) My BGESSerializer looks like this class BGESSerializer(serializers.ModelSerializer): class Meta: model = BGES fields = '__all__' This way, the returned object does not contain the Laboratoire object, so I change it by class BGESSerializer(serializers.ModelSerializer): laboratoire = LaboratoiresSerializer(read_only=True) class Meta: model = BGES fields = '__all__' But this way, when I set the variable laboratoire with the id in api_view like this request.data["laboratoire"] = laboratoire_serializer.data["id"] it's no longer working. I understand django is now expecting an object, by adding : laboratoire = Laboratoire.objects.get(pk=laboratoire_serializer.data["id"]) laboratoire_serializer2 = laboratoire_serializer(laboratoire) request.data["laboratoire"] = laboratoire_serializer2.data But still not working, the laboratoire field in the final answer is None, what am I doing wrong ? -
QuerySet appends _id in a field django
I have a model below class HomeImages (models.Model): homepage_id=models.ForeignKey(HomeAbout,on_delete=models.CASCADE) home_image=models.ImageField(upload_to="home_image",blank=True,null=True) I using a filter for a serializer def get(self,request,homeid): try: homeimg = HomeImages.objects.filter(homepage_id=homeid).values() except (KeyError, HomeImages.DoesNotExist): return Response('Data not found', status=status.HTTP_404_NOT_FOUND) else: if len(homeimg)>0: print("home object",homeimg) return Response([HomeImgSerializer(dat).data for dat in homeimg]) return Response([],status=status.HTTP_200_OK) problem is when I got the result of filter in homeimg object, it returns the field of homepage_id as homepage_id_id which incorrect how can I fix this it should mentioned homepage_id in result of queryset? Below is the queryset result <QuerySet [{'id': 1, 'homepage_id_id': 1, 'home_image': 'home_image/edit.png'}]> it shows homepage_id_id, whereas in model it is defined as homepage_id