Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image file data sent by Axios(React) not appears in server side Django script(POST request)
Im building a web App with React and Django. Now Im building a part that user upload image to server with Axios. I do this like this: Get the image from user: function onImageChanged(event) { handleSubmit(event.target.files[0]); } Send the file to the server: const formData = new FormData(); formData.set("bodyimage", file); console.log(file); //this shows file information like size and name etc... but I didn't see Data part axios({ method: "post", headers: { "Content-Type": "multipart/form-data", }, data: formData, url: "http://localhost:8002/plans/bodyimage", }).then(function (res) { //success message }) }); At the server side in a Django script, I get the data like this: @csrf_exempt def upload_body_image(request): post = request.POST if ("bodyimage" in post): //It's always false and it seems there is no any `bodyimage` in the POST request return "success" else: return "error" My question is that when I send the image file to Django script, there is no any bodyimage field in the POST request. Why this happens? If i send a string instead of image data, bodyimage appears in the POST request. I see some documents that Django handles Files in request.FILES but I check this and there is no chance. beside, I didn't send regular Form, I send a formData in … -
Lookup value of dict based on model
I have a dictionary - returned from rest. It presents a UUID Inside my template i need to display the list returned but want to find the UUID value from a row in model e.g. [{'value1': 'somevalue', 'id':'04fca561-ef45-47d3-a1f3-617e7f24961d'}{'value1': 'somevalue', 'id':'04fca561-ef45-47d3-b2e4-617e7f24961d'}] In my model i have a field such as : mykeyvalue = models.ForeignKey(SOmeotherModel, on_delete=...) I can use the {%for value in list%} {{value.id}}{%endfor} successfully. but i want to display the meaningful value such that it get it from the model. Hope this makes sense. I thought about making a new dictionary up using loops. What is the best way around this issue. -
Django - reverse nested url with drf-nested-routers
I configured my api url as localhost:port/app_name/students/{student_id}/macro/{macro_id}/lto using drf-nested-routers extension. Basically, each students has some macro categories assigned, that in turns have some Long Term Objectives (LTOs). I've tested it using curl and Postman and everything seems to work. Now I need to write a more precise test case for my LTO model. This is my urls.py from django.urls import path, re_path from django.conf.urls import include from rest_framework import routers from app_name.views.views import UserViewSet, StudentViewSet, MacroViewSet, LTOViewSet, MacroAssignmentViewSet from rest_framework_nested import routers as nested_routers # application namespace app_name = 'app_name' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') router.register(r'macro', MacroViewSet, basename='macro') router.register(r'macro-assignments', MacroAssignmentViewSet, basename='macro-assignment') student_router = routers.DefaultRouter() student_router.register(r'students', StudentViewSet, basename='student') lto_router = nested_routers.NestedSimpleRouter(student_router, r'students', lookup='student') lto_router.register(r'macro/(?P<macro_pk>.+)/lto', LTOViewSet, basename='lto') urlpatterns = [ re_path('^', include(router.urls)), re_path('^', include(student_router.urls)), re_path('^', include(lto_router.urls)), ] The issue is that I cannot use the reverse() method correctly to get the url of my LTOViewSet to test it. self.url = reverse('app_name:student-detail:lto', {getattr(self.student, 'id'), getattr(self.macro, 'id')}) This gives the following error django.urls.exceptions.NoReverseMatch: Reverse for 'student-detail-lto' not found. 'student-detail-lto' is not a valid view function or pattern name. In other test cases, I use very similar sentences and those work fine self.list_url = reverse('app_name:student-list') reverse('app_name:student-detail', {post_response.data['id']}) -
relation with users model (django)
when i run makemigration in manage.py i got this exception SystemCheckError: System check identified some issues: ERRORS: market.Customer.user: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract. market.Customer.user: (fields.E307) The field market.Customer.user was declared with a lazy reference to 'market.user', but app 'market' doesn't provide model 'user'. -
Django - how do I make the id go to the next avalaible number? (adding records outside of app)
I have to add 200 records into a table as i'm migrating data from an old SQLite database. I'm doing this through external software and everything is fine, it's just a simple copy and paste, aside from one issue. If I want to add a new record through the Django app - it gives me an error that the ID has been already used. Every time I hit enter to add a record it cycles through to next id. To be able to add a new record successfully, I would need to cycle through 200 errors to arrive at the next available ID. Is there anyway I speed this process up by allowing Django to count the new records that weren't added in the app and take them into consideration? -
Exception Value: 'AnonymousUser' object has no attribute '_meta'
I'm getting the following error under the login(request,user,backend='django.contrib.auth.backends.ModelBackend') function under the views.py file, the debugger says the user is coming back as None. The username and password are being passed correctly. views.py from django.shortcuts import render, redirect from django.views.decorators.http import require_http_methods from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .utils.validation import validate_registration from .utils.model_helper import create_user from .models import User, Restaurant, Role import json # Create your views here. def index(request): if request.user.is_anonymous: return render(request, 'login.html') else: return render(request, 'manager.html') @require_http_methods(['POST']) def sign_up(request): username = request.POST['username'] password = request.POST['pass'] if validate_registration(username, password): user = create_user(username,password,1) login(request, user, backend='django.contrib.auth.backends.ModelBackend') #same error with or without the backend part return redirect('manager') else: return redirect('') model_helper.py from ..models import User, Restaurant from django.db import transaction def create_user(username, password, role): try: with transaction.atomic(): res_id = create_restaurant() user = User(username=username, is_superuser=False, is_active=True, is_staff=False, role_id=role, restaurant_id = res_id ) user.set_password(password) user.save() return user except: print('error') def create_restaurant(): restaurant = Restaurant() restaurant.save() return restaurant.id validation.py def validate_registration(first_name, last_name): return True models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Restaurant(models.Model): name = models.CharField(max_length=100) open_time = models.CharField(max_length=10) close_time = models.CharField(max_length=10) address = models.CharField(max_length=100) phone = models.CharField(max_length=20) email = models.CharField(max_length=30) class Role(models.Model): … -
Let the Django dev server run again after fixing the error in a . py file
AttributeError: module 'django.forms' has no attribute 'T' The Django server stopped working after showing this error message. After fixing the problem, how can I let the server to run again. It is now stuck. I know that running python manage.py runserver is going to work. Is there a more convenient way? -
Adding to manytomany field, on added field from form
I have a model, that needs a user(ForeignKey), and a category(M2M), and for the category field in form, I extended its functionality by adding custom field to it(data-list but with input too), but I am unable to save the form with the category and user. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Category(models.Model): name = models.CharField(max_length=20, blank=True) class Listings(models.Model): title = models.CharField(max_length=64, null=False, blank=False) description = models.CharField(max_length=64, blank=True) bid = models.IntegerField(null=False, blank=False) timestamp = models.DateField(db_index=True, auto_now_add=True) image_url = models.URLField(blank=True) category = models.ManyToManyField(Category) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering=['timestamp', 'title'] forms.py from auctions.models import Listings from django import forms class ListTextWidget(forms.TextInput): def __init__(self, data_list, name, *args, **kwargs): super(ListTextWidget,self).__init__(*args, **kwargs) self._name = name self._list = data_list self.attrs.update({ 'list':'list__%s' % self._name, 'class':'form-control' }) def render(self, name, value, attrs=None, renderer=None): text_html = super(ListTextWidget, self).render(name, value, attrs=attrs) data_list = '<datalist id="list__%s">' % self._name for item in self._list: data_list += '<option value="%s">' % item data_list += '</datalist>' return (text_html + data_list) class ListingsForm(forms.ModelForm): category = forms.CharField() class Meta: model = Listings fields = ['title', 'description', 'bid', 'image_url', 'category'] widgets = { 'title': forms.TextInput(attrs={'class':'form-control'}), 'description': forms.TextInput(attrs={'class':'form-control'}), 'bid': forms.TextInput(attrs={'class':'form-control'}), 'image_url': forms.TextInput(attrs={'class':'form-control'}), 'category': forms.TextInput(attrs={'class':'form-control'}) } def __init__(self, *args, **kwargs): _category_list = kwargs.pop('data_list', … -
Django migrate creates the wrong tables in second database
I want to create a model that will only be used by a second database in my Django project. So in theory I would have a default database that has all the apps and their models and then this new database will have a separate apps model which would be my jobs data. The problem I am having is that whenever I migrate to the new database, it duplicates all the tables including the new table that was only meant to be in the new database. All the original contenttypes, sessions, auth etc is getting added to this new 'jobs' database. I only want the Jobdata model/table to be in the jobs database. I've gone over the Django documentation a few times and haven't had much success with the router that I have set up. I've also played around with a few options I found on SO but they are a bit dated and didn't detail the issue about migrating Here is my current set up: #models.py #the new table/model that I want to go to a new separate database called jobs class Jobdata(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) employer_name = models.CharField(max_length=50, blank=True) empoyer_profile_id = models.CharField(max_length=50, blank=True) #also in models.py … -
How to test CheckboxSelectMultiple in save
I have a form (ModelForm) in Django, where I am adding a field for users in the init method as so: self.fields["users"] = forms.ModelMultipleChoiceField( queryset=users, widget=forms.CheckboxSelectMultiple, required=False,label="Add Designer(s)" ) In the save method how I can iterate over the queryset for this field, however I do not know how I can test if the particular model has been selected/checked. Help please. -
Apache: 500 Error after Successful User Authentication?
I am currently working on a site that is deployed on an AWS EC2 instance using Apache, Django, and mod_wsgi. I am trying to configure my Apache to use mod_authz_user and a python script for user validation following this tutorial but after implementing it, I get a 500 error when successfully logging into the server and the error logs show nothing except that there was an initial GET request for the home page of the site. The structure of my code follows the tutorial linked above pretty much to tea, so I'm not sure what could be going wrong. The site properly asks the user for the username and password, and I know for sure my authentication script is being called by Apache. Technically, all I need is the HTTP_AUTHENTICATION head to be set for my Django application, so if I could somehow have the user enter in their credentials but not have Apache validate it (which leads to the 500 error) that would be great. In that case the HTTP_AUTHENTICATION header would be set because the user entered in the credentials and then my Django application could deal with the authentication from there. For a bit more context, this … -
Rename a site_package folder in python
I installed these two packages from PyPi django-user-account django-allauth these two packages has a sub_package or folder named account which are conflicting with each other in my INSTALLED_APPS in django settings. I have tried renaming the account package inside django-user-account but no success. Please how do I successfully rename either of these packages? -
Django with jsonfile
I'm working on my project with django. [ // More API functions here: // https://github.com/googlecreativelab/teachablemachine-community/tree/master/libraries/pose // the link to your model provided by Teachable Machine export panel const URL = "./my_model/"; const toDoList=document.querySelector(".js-toDoList"); const TODOS_LS = "toDos"; let model, webcam, ctx, labelContainer, maxPredictions; async function init() { const modelURL = URL + "model.json"; const metadataURL = URL + "metadata.json"; // load the model and metadata // Refer to tmImage.loadFromFiles() in the API to support files from a file picker // Note: the pose library adds a tmPose object to your window (window.tmPose) model = await tmPose.load(modelURL, metadataURL); maxPredictions = model.getTotalClasses(); // Convenience function to setup a webcam const size = 600; const flip = true; // whether to flip the webcam webcam = new tmPose.Webcam(size, size, flip); // width, height, flip await webcam.setup(); // request access to the webcam await webcam.play(); window.requestAnimationFrame(loop); // append/get elements to the DOM const canvas = document.getElementById("canvas"); canvas.width = size; canvas.height = size; ctx = canvas.getContext("2d"); labelContainer = document.getElementById("label-container"); for (let i = 0; i < maxPredictions; i++) { // and class labels labelContainer.appendChild(document.createElement("div")); } } async function loop(timestamp) { webcam.update(); // update the webcam frame await predict(); window.requestAnimationFrame(loop); } async function predict() { // … -
Static images are not rendering in production on pdf using wkhtmltopd in django application
I am using pdfkit to convert html into pdf. Everything seems to be working perfectly in development, but after building a docker image and running it locally, the pdf is generated but images are not loaded. Here is my how I am rendering image, which seems to be working fine locally: <img src="{{ host_url }}/static/tcs.jpg" style="width:100px;display:block;" /> Here's my code in django view function: template = get_template("tcs_invoice.html") data = { "host_url": settings.HOST } html = template.render(data) # Renders the template with the context data. pdf = pdfkit.from_string(html, False) return HttpResponse(pdf, content_type='application/pdf') I have installed wkhtmltopdf on my docker container. When I hit the url in the browser the image is shown. why does it not render in production mode. -
Check if option select is empty in django
<div class="form-group col-md-6"> <div class="form-group"> <label for="customer_id" class="text-white">Customer</label> <select class="form-control bg-dark text-white" name="customer_id" id="customer_id" value="{{ testoccasion.customer_id }}"> {% for customer in testoccasion %} {% if customer.customer_name != None %} <option {% if customer.customer_id == customer.customer_id %} selected {% endif %} value="{{ customer.customer_id }}">{{ customer.customer_name }}</option> {% endif %} {% endfor %} </select> </div> i have this form where im getting data from a database, but i want to check if there are no data and show something else. -
Python Flask/Django check if API call was made by server
What would be a way to check if api request was made by server and not outside source? with flask or django? -
Retrieve Stripe customer by E-mail | Django
I'm trying a way to figure out how to retrieve the Stripe Customer by e-mail: In my views, I wrote the below code: if stripe.Customer.retrieve(email=request.POST['email']): customer = stripe.Customer.retrieve(id) else: customer = stripe.Customer.create( email=request.POST['email'], name=request.POST['nickname'], ) charge = stripe.Charge.create( customer=customer, amount=500, currency='brl', description='First Test Ever!', source=request.POST['stripeToken'], ) Basically, if the customer is found by their e-mail, so I don't need to create a new account. Otherwise, the account is created. The last step is to charge either the new customer or the existent one. The code is not working properly. I assume this is the wrong way to search for an existent customer. Any help? Thank you! -
action decorator in DRF doesn't work with url_path
I'm trying to achive that such endpoint /api/messages/<str:email>/ will return a list of messages for given email. So in my ViewSet I've created a function with @action decorator @action( detail=False, methods=["get"], name="Get email messages", url_path="<str:email>", url_name="Email's messages" ) def email_messages(self, request, email=None): return Response({"aaa": email}, status=200) But it seems that django doesn't resolve eg. this url: /api/messages/aaa/ (just for the test) and returns 404. Even if I change url_path to email it returns 404 on /api/messages/email/. It only works when I remove the url_path kwarg from the params. Then it is accessible under /api/messages/email_messages. How can I achieve a working GET on /api/messages/<str:email/ so that the email will be passed to the function? -
Django Admin checkbox states don't match 'checked' attributes when changed with JS
I have a Django admin 'Add' page for a Model ORIGINAL that has a foreign key to a Model CHOICES that has a boolean field BOOL. On the 'Add' page, the input for CHOICES includes four checkboxes for the BOOL field. From the Page Source, they look like this: <input type="checkbox" name="CHOICES_set-0-BOOL" id="id_CHOICES_set-0-BOOL"> <input type="checkbox" name="CHOICES_set-1-BOOL" id="id_CHOICES_set-1-BOOL"> <input type="checkbox" name="CHOICES_set-2-BOOL" id="id_CHOICES_set-2-BOOL"> <input type="checkbox" name="CHOICES_set-3-BOOL" id="id_CHOICES_set-3-BOOL"> I'm trying to use JavaScript to make this set of checkboxes act like radio selectors so that only one can be selected at a time. In admin.py, I include additional JavaScript for the ORIGINAL ModelAdmin: class OriginalAdmin(admin.ModelAdmin): class Media: js = ['admin/js/admin/choices_radio.js'] A test version of choice_radio.js that illustrates the problem I'm having is (function() { /* 'checkboxes' is an HTMLCollection of the <input type="checkbox"> * nodes in question. I've verified that it's constructed correctly */ let checkboxes = getCheckboxes(); function boxAdd() { // Loop over all checkboxes and add the checked="" attribute for (let i = 0; i < checkboxes.length; i++) { checkboxes[i].setAttribute("checked",""); } } function boxRemove() { // Loop over all checkboxes and remove the checked="" attribute for (let i = 0; i < checkboxes.length; i++) { checkboxes[i].removeAttribute("checked"); } } function assignTest() { … -
Use Microsoft 0365 access token with Django rest frameworks toekn authentication
I am trying to make an api which will use access token from Microsoft o365, I have created an app in azure and I have registered client id and client secret, By using Microsoft graph api url I am able to get access token through post request at https://login.microsoftonline.com/common/oauth2/v2.0/token and I used grant_type as password, now I want to use the token obtained from o365 in my api having class based views and want to use that token for authenticating user in my api. I would also like to validate the token obtained from above url for its validation. -
DjangoCMS Apphooks Not Working As Documented
We have the following code in the project's urls.py urlpatterns += i18n_patterns( url(r'^', include('cms.urls')), url(r'^mentors/', include("apps.mentors.urls")), url(r'^payment/', include("apps.payment.urls", namespace="payment")), url(r'^users/', include("apps.xyz.urls", namespace="users")), ) The first also has an apphook declared in its respective directory. When we open a page, we can attach that app to a DjangoCMS page. So far, so good. The following part of documentation says that the URLs for an app should be removed after the apphook is created. When we do that, the app no longer works. NoReverseMatch at /mentors/ 'mentors' is not a registered namespace It is not quite clear why. Isn't DjangoCMS supposed to take care of the the URLs for apphooks? In case it matters, here is how we declared the apphooks from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool @apphook_pool.register class MentorApphook(CMSApp): app_name = "mentor_detail" name = "Mentor Apphook" def get_urls(self, page=None, language=None, **kwargs): return ["apps.mentors.urls"] http://docs.django-cms.org/en/latest/introduction/05-apphooks.html -
return custom field validation in DRF
i have a serializer and view function that returns a default error messages when the user register with an existing username or email what i'm trying to do if instead of "email":["account with this email already exists."],"username":["account with this username already exists."] is to return a custom message with my language how to create a validation function that check for those errors and return the customized message that i wrote models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email",max_length=60, unique=True) username = models.CharField(max_length=60,unique=True) phone = models.CharField(max_length=60,unique=True) date_joined = models.DateTimeField(verbose_name="date joined",auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login",auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) email_confirmed = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','phone'] objects = MyAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True views.py @api_view(['POST']) def register(request): if request.method == 'POST': serializer = AccountCreateSerializer(data=request.data) data = {} if serializer.is_valid(): account= serializer.save() data['response']="successfully registered a new user." data['email'] = account.email data['username'] = account.username data['phone'] = account.phone token = Token.objects.get(user=account).key data['token'] = token else: data = serializer.errors return Response(data) serializers.py class AccountCreateSerializer (UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = Account fields = ('email','username','phone','password') -
Django dictionary parameters issue
I am trying to use Django dictionary parameters when calling cursor.execute that is documented in this link I have this test code: with connection.cursor() as cursor: params = {"server_id": 1} cursor.execute( ("select * from General.Servers where ServerID = %(server_id)s"), params, ) But I am getting the following error: TypeError: format requires a mapping What does this error mean? and how to fix it? Thank you! -
Authorisation token: OAuth on Django back end, with front end call to 3rd party API. Is this a bad idea?
I am learning Django and have an idea for an app that would access data on the Microsoft Graph API for users of their outlook service. It seems the cleanest way of doing this is by using a package like django-all-auth to handle obtaining and storing the authorisation token in the backend. There’s also an example on the Graph API website using python-social-auth. However, I’ve been informed here that I can use a library like jQuery to make the API call directly, meaning the JSON data returned from the 3rd party API could bypass my server and go directly to the user’s browser. With a 3rd party API requiring authorisation I’d need to get the auth token from my django back end to the front end so that it could be used in the Ajax request. I appreciate that it would be an option to use the implicit or PKCE flows in the browser. However, as an alternative I’d had the idea that I could use the server side OAuth flow to store the access token and refresh token in the back end and then send the auth access token from django back end to the user’s browser to be … -
Same function throwing "No 'Access-Control-Allow-Origin'" in one page but not in the others
I have a function to get zip code infos throughout my django website. The problem is that this function works perfectly in all pages except one. I'm using the same header to all pages. var HttpClient = function () { this.get = function (aUrl, aCallback) { var anHttpRequest = new XMLHttpRequest(); anHttpRequest.onreadystatechange = function () { if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200) aCallback(anHttpRequest.responseText); } anHttpRequest.open("GET", aUrl, true); anHttpRequest.send(null); } } function getZipCode(obj) { var client = new HttpClient(); client.get("http://viacep.com.br/ws/" + obj.value + "/json/", function (response) { console.log(response_json) //more code... }) } In the problematic page I'm getting the famous "No 'Access-Control-Allow-Origin' header is present on the requested resource." error. I've reserached a lot about it, but couldn't find a proper solution when this problem appears in only one page. How can I make this work in all pages?