Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to differentiate new users and existing users on OAuth using Django?
I want my users to be differentiated between : Returning users, and New users while using OAuth such that when I use django-allauth package for OAuth using Google, Github, and LinkedIn, it doesn't create a new user from the login page which is meant only for existing users but rather redirect them to the sign up page. So far I've found that new users just end up making new accounts from the login page as well and I don't want that in the case I'm making it an invite-only app or something similar. -
Why is my python class variable (ex. Post) unable to be used within the class to declare a variable. - django
I keep getting an error while trying to runserver(python manage.py runserver) The error is a nameError and says that Post is not defined. this is from models.py ''' from`` django.db import models class Post(models.Model): posts = Post.objects.all() title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique = True) body = models.TextField(blank=True, db_index = True) date_pub = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title ''' this is from settings.py ''' from django.shortcuts import render from blog.models import Post # # Create your views here. def home(request): return render(request, 'blog/index.html') def index(request): posts = Post.objects.all() return render(request, 'blog/index.html', context={'posts': posts}) File "C:\Users\MaxLe\Desktop\My_Django_Stuff\blogengine\blog\models.py", line 9, in Post posts = Post.objects.all() NameError: name 'Post' is not defined NameError: name 'Post' is not defined '''`enter code here` All help is appreciated as I'm just trying to get off my feet. Thanks. -
How to correctly update a nested Object in django rest framework?
i have a nested model that i want to CRUD. i made the Create method as bellow and now i'm getting a new error in my career i have tow models: class Planning(models.Model): name = models.CharField(max_length=50) salle_sport = models.ForeignKey(SalleSport, verbose_name="Salle de sport", related_name='plannings', on_delete=models.CASCADE, null=True, blank=True) class SalleSport(models.Model): name = models.CharField( max_length=50) adresse = models.CharField( max_length=50) phone = models.CharField(max_length=50) def __str__(self): return self.name i made one serializer For the GET and an other for POST & PUT for the POST method i used the PrimaryKeyRelatedField to get the SalleSport name as a PK to used it as reference. Here is my serializer code of the models : from salle_sport.models import SalleSport from .models import Planning class NameSalleSportSerialiser(serializers.ModelSerializer): class Meta: model = SalleSport fields= ('name',) class PlanningListSerialiser(serializers.ModelSerializer): salle_sport = NameSalleSportSerialiser() class Meta: model = Planning fields= ('id', 'name', 'salle_sport') class PlanningSerialiser(serializers.ModelSerializer): salle_sport = serializers.PrimaryKeyRelatedField(queryset= SalleSport.objects.all(),source='salle_sport.name') class Meta: model = Planning fields= ('id', 'name', 'salle_sport') def create(self, validated_data): plan = Planning.objects.create(salle_sport=validated_data['salle_sport']['name'], name=validated_data['name']) return plan def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.save() nested_serializer = self.fields['salle_sport'] salle_data = validated_data.pop('salle_sport') nested_instance = instance.salle_sport nested_instance.name = salle_data['name'] nested_instance.save() ### raise TypeError( ### TypeError: Tried to update field salle_sport.SalleSport.name with a model instance, <SalleSport: newValue>. … -
accessing variable to another apps django
I have two apps in django ├── search │ └── views.py │ └── preprocessing └── views.py in search/views.py, i have dataframe with the code like this: df = pd.DataFrame() def scrape(request): global df items = comments + replies df = pd.DataFrame(items, columns=['Comments']) return render(request, 'search/scrape.html', context) And, i want to use the dataframe from search/views.py in second apps preprocessing/views.py from search.views import df def index(request): print(df) context = { } return render(request, 'preprocessing/preprocessing.html') but the problem is dataframe that i pass to preprocessing/views.py is empty so, how can i pass the datframe also with the value inside from search/views.py thx for ur help -
How to create a loop for a approval system?
I created a approval system for my project. I have several users. These users are analyst, lead, manager, etc. I have a credit limit table (DoaTable) in my system. I want to when a lead type user updates a field in this table it shouldn't be accepted until a manager approves it. So, the old value should be valid until the manager approves the new values, and when the manager approves it the new value should be accepted. I created a new model. When a lead wants to update this table, data will save a second model (table) called as DoaTableBeforeApproval. In this way, when a manager approved the table which a lead update, DoaTable should be equal to new table (DoaTableBeforeApproval). How can I create a loop for this equality? models.py LIMITS = ( ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ..'), ('Strict Credit Check', 'Strict Credit Check'), ('No Credit Check', 'No Credit Check'), ) RANKS = ( ('Analyst', 'Analyst'), ('Senior Analyst', 'Senior Analyst'), ('Lead', 'Lead'), ('Manager', 'Manager'), ... ) class DoaTable(models.Model): rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) limit = models.FloatField() comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) class DoaTableBeforeApproval(models.Model): rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) … -
How to pass the object itself which is creating in model method save()
I would like to pass the object which itself is creating in the model method save. How can I do it? class Legal(ApplicationAbstractFields): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='legal') legal_product_cat = models.ForeignKey(TechniqueCategory, blank=True, null=True, on_delete=models.CASCADE) legal_product_cat_type = models.ForeignKey(TechniqueCategoryType, blank=True, null=True, on_delete=models.CASCADE) legal_product_name = models.CharField(blank=True, null=True, max_length=254) legal_name = models.CharField(blank=True, null=True, max_length=254) def save(self, force_insert=False, force_update=False, using=None, update_fields=None, *args, **kwargs): if self.is_sent == True: Notification.objects.create( # HERE HOW TO PASS THE OBJECT Legal itself??? legal=self.objects, is_viewed=False, user=self.user, event='Your application was received') super().save(*args, **kwargs) -
In drf can i use image like this <img src={`http://127.0.0.1:8000${mapped.product.img}`} alt="one" />?
{list.map((list_item) => { return ( {list_item.quantity} {list_item.product.name} {list_item.product.type} {list_item.product.quantity} <img src={http://127.0.0.1:8000${list_item.product.img}} alt="one" /> ); })} -
How to read inputs from bootrap modal form in Django?
I want to read inputs from bootstrap registration modal form which is present in base.html(This is just a layout acting as a parent for other pages). But this base.html has two forms . In models.py for database In views.py In views: I have made a function def register(request): request.method=='POST' first=request.POST["first_name"] print(first) but nothing is getting printed The form is not getting detected so I have to render base.html in views.py Any help will be appreciated? -
upload image from react to django api
i'm using "react-images-upload" to upload images from react to django api but every time i choose an image i get a re-render to a blank screen export default class CreatePost extends Component { constructor(props) { super(props); this.state = { title: this.props.title, main_post: this.props.main_post, thumbnail: this.props.thumbnail, pictures: [] }; this.handlethumbnail = this.handlethumbnail.bind(this); handlethumbnail(e) { this.setState({ pictures: this.state.pictures.concat(picture), thumbnail: e.target.pictures[0], }); render() { return ( <> <ImageUploader singleImage={true} buttonText='Choose images' onChange={this.handlethumbnail} imgExtension={['.jpg', '.gif', '.png', '.gif']} maxFileSize={5242880} /> } </> i also configured the media folder in setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
adding a one-to-many django model as a foreign key to another django model
I currently have three models: Member, Driver, and Order, where Member and Driver are one to many models (one member can have multiple taxi orders) and order holds the foreign keys to the Member and Driver models. I've written a script that passes the contents of the input file into my Django models. I've been able to load data into my Member and Driver models; however, I keep getting errors when loading data into my order models, and I suspect its because I used the get_or_create function inside a loop (and is not globally accessible). Is this the case? I thought models would be accessible globally seeing as I'd imported it into the script. Here's my code for reference (also, I'm using Python 2.7 and Django 1.6.11): models.py from django.db import models from django.conf import settings # from datetime import datetime from decimal import Decimal import pymysql # apparently this isn't officially supported by django LOL o well pymysql.install_as_MySQLdb() # Create your models here. ORDER_STATUS = ( ('No Car', 'NC'), ('User Cancelled', 'UC'), ('Completed', 'CC'), ('Driver Cancelled', 'DC'), ) PAYMENT_METHOD = ( ('CA', 'cash'), ('CC', 'creditCard'), ) class Member(models.Model): member_hash = models.CharField(max_length=32) member_loc_lat = models.DecimalField(max_length=20, max_digits = 25, decimal_places = … -
Compare against null value in Django Filefield
In my 'FileField` in models I have the following: document = models.FileField(upload_to='delivered/', null=True, blank=True) I tried to compare against this file field using None but it doesn't work What I tried: d_url = Delivered.objects.filter(allotment_id =a_id).first().document print("d url", d_url) print("d url", type(d_url)) if d_url is None: print("none") There are a few entries where I haven't uploaded the files and in those cases I want to do something but the if statement is never accessed, how do I do it ? -
i'm trying to create a product and save to database but isn't working
I'm trying to create a product and save it. The page redirects where it's supposed to but doesn't save the date. recently I had some problem registering a user and when I fixed it now this problem occurred. views.py from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from .models import myUser,Listings,Bid from django.http import HttpResponseRedirect from django.urls import reverse from .form import registerForm,loginForm,createListingForm from django.db import IntegrityError from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def index(request): if not request.user.is_authenticated: message = f"please sign in" else : message = f"signed in as {request.user}" return render(request, "auctions/index.html",{ "listings": Listings.objects.all(), "message": message }) def login_view(request): if request.method == "POST": form = loginForm() email = request.POST["email"] password = request.POST["password"] user = authenticate(request,username=email,password=password) if user is not None: login(request,user) return HttpResponseRedirect(reverse('index')) else: return render(request, "auctions/login.html",{ "form": form , "message": "username/password not valid" }) return render(request, "auctions/login.html",{ "form": loginForm() }) def logout_view(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): if request.method == "POST": form = registerForm() email = request.POST["email"] # check passwords are same password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render (request, "auctions/register.html",{ "form": form, "message": "Passwords does not match" }) # Attempt to create new user … -
Enforce Django Admin to correctly call .update() instead of .save() to avoid triggering checks meant for object creation
How do we enforce Django Admin to correctly call .update() instead of .save() to avoid triggering checks meant for object creation? This is the models.py: class BinaryChoice(): # field definitions ... def save(self, *args, **kwargs): # check if binary if self.question.qtype == 2: if self.question.choices.count() < 2: super(BinaryChoice, self).save(*args, **kwargs) else: raise Exception("Binary question type can contain at most two choices.") else: super(BinaryChoice, self).save(*args, **kwargs) This passes the test, no surprises: class SurveyTest(TestCase): def test_binary_choice_create(self): q1 = Question.objects.create(survey=survey, title='Have you got any internship experience?', qtype=Question.BINARY) BinaryChoice.objects.create(question=q1, choice="Yes") BinaryChoice.objects.create(question=q1, choice="No") with self.assertRaises(Exception): BinaryChoice.objects.create(question=q1, choice="Unsure / Rather not say") The .save() correctly checks that there isn't already 2 binary choices related to the same Question. However, in Django Admin, when using the interface to update the value (anything arbitrary, for example changing the value from "Yes" to "Sure") and saving it, one would expect the .update() method to be called. It turns out, according to Django docs and also a relevant thread here, the .save() method is called instead. So now our update operation would fail when there's already 2 BinaryChoice, even if you intend to update a value in-place using the Django Admin's default interface. For completeness sake, this is admin.py: … -
How to turn off or terminate my Django app when I click the button on browser
I'm new to python and Django, now I want to ask about how to turn off or terminating my Django app when I click button on my browser. On the browser, I click the button and then sending post request to the server using javascript fetch api. On the server when I sending the POST request, i'm executing exit() command, but it doesn't kill my Django app. Is there a way to kill my Django app? -
Error installing django-vimeo: Failed building wheel for xxhash
I have created a new virtual environment installed Django, I'm using Python3. When I try to run pip3 install django-vimeo it throws me this error. ERROR: Command errored out with exit status 1: command: 'C:\Users\...\env\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users...AppData\\Local\\Temp\\pip-install-ntq_y7sl\\xxhash_5774b3470aaf44ff8894164020121d78\\setup.py'"'"'; __file__='"'"'C:\\Users...AppData\\Local\\Temp\\pip-install-ntq_y7sl\\xxhash_5774b3470aaf44ff8894164020121d78\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\apoor\AppData\Local\Temp\pip-wheel-2a0xk73p' cwd: C:\Users\...AppData\Local\Temp\pip-install-ntq_y7sl\xxhash_5774b3470aaf44ff8894164020121d78\ Complete output (5 lines): running bdist_wheel running build running build_ext building 'xxhash' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Failed building wheel for xxhash The error says to install Microsoft Visual C++ 14 or greate in order to fix this but I dont see such a dependency listed in the installation instructions of the package. Did I miss something here? -
Django - Field name is changing to the variable data instead of being filled with the variable data
In the below code, when I call the area variable in the location model field, the name of the model field gets changed to the value of the area variable instead of the field being filled with the area value. What's causing this? class Profile(models.Model): loc = get('http://ipapi.co/json/?key=left_blank_for_reasons') address = loc.json() city = address['city'] region = address['region'] area = city + ", " + region user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.CharField(area, max_length=100, blank=True) -
multipart upload to S3 with Django-storages
I'm using django-storages to upload large files into s3. Currently testing with files that are 1GB in size and would like to split it into multi part for quicker uploads. I have tried setting AWS_S3_MAX_MEMORY_SIZE to 5mb to see if that would help, but no luck. I could not find any other settings for multipart uploads in the django-storage docs https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html. -
is it safe to only use Paypal client side Integration?
i'm programming a ecommerce website using django and paypal smart Payment Buttons Integration and i want to know if it's safe to only use the client side integration or do i need a server side integration. <script src="https://www.paypal.com/sdk/js?client-id={{ client_id }}&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container let total = '{{ product.price }}'; paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); }); } }).render('#paypal-button-container'); </script> Thank you in advanced. -
How to create a "not equal" and "not in" filter in django with graphene-django and django-filters
I tried to find solutions on how to carry out not equal and not in filtering, but due to my inexperience I was unable to identify a solution. this is a fragment of my current structure. # result/models.py class Result(models.Model): ... object = models.ForeignKey(Object, on_delete=models.PROTECT) ... # result/types.py class ResultType(DjangoObjectType): class Meta: model = Result filter_fields = { ... 'object__object_name': ['exact', 'icontains'], ... } convert_choices_to_enum = False interfaces = (graphene.relay.Node,) object = DjangoFilterConnectionField(ObjectType) # result/queries.py class Query(object): results = DjangoFilterConnectionField(ResultType) I wanted to be able to perform searches similar to: # result/types.py class ResultType(DjangoObjectType): class Meta: model = Result filter_fields = { ... 'object__object_name': ['exact', 'icontains', 'notequal', 'notin'], ... } convert_choices_to_enum = False interfaces = (graphene.relay.Node,) object = DjangoFilterConnectionField(ObjectType) query { results ( object_ObjectName__Notequal: "Pluto"){ edges { node { object { objectName } } } } } -
Django filter exact value in list
Good day again SO. I was hoping you can help me with some of the logic. Based on this SO Answer, I can filter the search with a list which works perfectly. However, I wish to get an EXACT id instead of at least one matches. models: class Condition: condition_name = models.CharField(....) class Jobs: jobs = models.CharField(...) class JobsConditions: account = models.ForeignKey(Account...) job_item = models.ForeignKey(Jobs...) condition = models.ForeignKey(Condition...) So if I try to search for Jobs with Conditions, I do the following: cond_array = [1,2,4,5] # Append to array based on request. condition_obj = Condition.objects.filter(id__in=cond_array) Then compare condition_obj to JobsConditions model. How to use this so that I will only get only the jobs with exact condition? No more no less. -
Django: UnboundLocalError at /all_hours_report local variable 'HttpResponse' referenced before assignment
I'm stumped. I have a django project and keep getting this error when trying to call HttpResponse. I've ran into this with HttpResponse at random times, but it works in dozens of other places in my project. I've tried many things and am still getting the error. Here is the code snippet throwing the error: from django.template import loader from django.http import HttpResponse from django import template def all_hours_report(request): context={ 'msg' : "You are not authorized" } template = loader.get_template('unauthorized.html') return HttpResponse(template.render(context, request)) Django==2.1.15 Python==3.8 -
Does Django use one thread to process several requests in WSGI or Gunicorn?
As per the title, I am wondering if Django, when run via WSGI or Gunicorn, uses one thread to process several requests? I know it is a bad practice to access the request from places not meant to be accessed from, but I still want to do it. (for good reasons in my opinion, such as accessing the current user and site in my custom template loader. Django template loader doesn't offer these two entities.) Now I managed to get access to the user, etc. from everywhere using the following bit of code: import threading _thread_locals = threading.local() def get_current_user(): request = get_current_request() if request: return getattr(request, "user", None) class RequestThreadMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): _thread_locals.request = request response = self.get_response(request) return response My question/concern is: is it guaranteed that requests/users don't get mixed up in production? I am concerned the second user, for instance, gets identified as the first user because the thread is being used for my than one request. Is that possible, or every request has its own local thread in WSGI and Gunicorn? -
How to create a login in drf
I am making an application in drf that is doing a login validation through the tokens, but I ran into a problem and it is that I have not been able to generate a login because although I create the user and assign a token, it does not I have it been able to perform the login validation: This is my model: from django.db import models from django.conf import settings from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser from rest_framework.authtoken.models import Token class User(AbstractUser): def get_full_name(self): return f'{self.first_name} {self.last_name}' @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_token_user(sender, instance, **kwargs): if kwargs.get('created', False): Token.objects.create(user=instance) This is my serializer: from django.contrib.auth.hashers import make_password from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): password2 = serializers.CharField(write_only=True) class Meta: model = User fields = ( 'first_name', 'last_name', 'username', 'email', 'password', 'password2' ) def validate(self, data): if data.get('password') != data.get('password2'): raise serializers.ValidationError('Las contraseñas no son iguales') return data def create(self, validated_data): return User.objects.create( first_name=validated_data.get('first_name'), last_name=validated_data.get('last_name'), username=validated_data.get('username'), email=validated_data.get('email'), password=make_password(validated_data.get('password')) ) This is my view: class CreateUser(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) I know drf provides a login: … -
Django - how to render template after AJAX POST request from view function using the context variables pulled from the database
Simple question but can't find the answer. I submit an AJAX post request from my template template1.html, my view function uses the AJAX POST data to lookup objects/context variables from the database. Then I simply want to load a different template template2.html from this view function using those context variables as template tags in this new template (template2.html). I do NOT want to use the AJAX success call-back function to load the next template (because I don't want the context variables displayed in the URL in the GET request). Doing simply render(request, "template2.html", context=context) from within the view does not work. Please help. (To Stackoverflow moderators - there is no reason to close this question. It's sufficiently clear and detailed) -
How to add information to a field from a function created in a view?
How would I take a value from a view function and put it in a model field? For example, let’s say I did a view that adds two numbers together. How would take that value and add it to the field of a model every time an instance of that model is created? Or is there another way of doing this that I’m not seeing. I have a function that takes the user's IP and displays the city and region they are in. I was wondering how I could put that information in a model field every time an instance of that model is created.