Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FloatField vs DecimalField in Django and JS/React
I have a Django app as the backend a React app as the frontend. Most of my Django fields related to prices/monetary values were FloatField. It worked with the frontend: when receiving objects from the backend I could see that those fields were numbers and I could make calculations with them. But I've recently changed from FloatField to DecimalField, and now on the frontend the prices are assumed as string. Why is that happening and what is the best approach to deal with this? Has anyone experienced something similar? -
Avoiding duplicate row entry inside django model
I have a CarRent model that is a ForeignKey to the Car model. On the Car detailView page i have a button for drivers to place a Rent which will result in adding a row to the CarRent Table. The rent isn’t active yet until the Car owner approves the rent request. The problem now is that a driver could click the rent button multiple times thereby resulting in many duplicate rows in the CarRent model and also multiple redundant car rent request to the car owner. I am looking for a way to hide the “Place A Rent” form if the current user (driver) has already requested for a particular car and rent_approval is not True. Thanks. Any help will be greatly appreciated. models.py class Car(models.Model): car_owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='car_owner', on_delete=models.CASCADE) car_model = models.CharField(max_length=20, blank=True, null=True) rented = models.BooleanField(default=False) class CarRent(models.Model): car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE) driver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='driver_renting', on_delete=models.CASCADE) rent_approval = models.BooleanField(null=True) active_rent = models.BooleanField(default=False, null=True) views.py class CarView(LoginRequiredMixin, UserPassesTestMixin, FormMixin, DetailView): model = Car form_class = RentForm def get_success_url(self): return reverse('app:car-detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): form = self.get_form() self.object = self.get_object() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form, *args, **kwargs): … -
Loading of Django test fixtures into database
I'm trying to do some test-driven development and would find it useful to look inside the database to see what's being done using database tools in PyCharm. I load up the test fixture here: case6_fixtures = ['test_case6.json'] try: call_command('loaddata', *case6_fixtures, verbosity=9) except Exception as ex: print(str(ex)) And it seems to be loading. Loading 'test_case6' fixtures... Checking '/Users/user/Workspace/application/application/fixtures' for fixtures... Checking '/Users/user/Workspace/project' for fixtures... No fixture 'test_case6' in '/Users/am034402/Workspace/project'. Installing json fixture 'test_case6' from '/Users/user/Workspace/application/application/fixtures'. Processed 2 object(s). Installed 2 object(s) from 1 fixture(s) If I try to query it with the Django ORM, I get a record back, and it matches what is in the fixtures file. However, if I query the sqlite3 db file that is supposed to have something in it (testing.db): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'TEST': { 'NAME': 'testing.db' } } } nothing's there. The same can be said for db.sqlite3. Yes, the tables are there, but they're empty. I'm thoroughly confused. Does Django's test runner load these fixtures into memory or something? Shouldn't there be data in those database tables in testing.db? -
Is shifting an existing Django project to FastAPI a good idea?
I am working on a Django project currently and recently I came across FasAPI. After seeing all the advantages of FastAPI, I am really tempted to shift my project to it. The current project is pretty huge and it's gonna take a while to switch. Is it worth switching to FastAPI spending such a huge effort in the long run? -
aws ec2 not serving static files in a django react application
I am trying to deploy a django react ecommerce app using aws ec2. when i run python manage.py runserver 0.0.0.0:8000 it is loading the page but not serving static files. The errors are [24/Jun/2021 19:29:26] "GET / HTTP/1.1" 200 2297 [24/Jun/2021 19:29:26] "GET /static/css/2.97503911.chunk.css HTTP/1.1" 404 179 [24/Jun/2021 19:29:26] "GET /static/css/main.4586955f.chunk.css HTTP/1.1" 404 179 [24/Jun/2021 19:29:26] "GET /static/js/2.7e7fd32c.chunk.js HTTP/1.1" 404 179 [24/Jun/2021 19:29:26] "GET /static/js/main.002fbd2b.chunk.js HTTP/1.1" 404 179 Here is my settings.py file """ Django settings for backend project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+^5qu3r54+4ja6q(_$rc!w4*z9t$erk61j=m8wbry53y*c-&h*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['myamazonclone.ml'] SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'dj_rest_auth', 'django.contrib.sites', 'allauth', … -
Python console input from html form using django
i have a personality analysis python script, but I want to make it runs in html and get the input form from html page, and the shows the result back in html page. I already use a django framework to run html page. But i don't know how to connect it with python script I have. -
js XMLHttpRequest() with django
I made an GET XMLHttpRequest() with django but I'm received <QueryDict: {}> from the js. How can I send the info in te correct way? What is my mistake? js code: var data = { "startdate":start_Date } var xhttp = new XMLHttpRequest(); xhttp.open("GET", "/scoStart/", true); xhttp.setRequestHeader('Content-Type', 'application/json/x-www-form-urlencoded; charset=UTF-8'); xhttp.send(JSON.parse(data)); xhttp.onreadystatechange = function () { if (xhttp.readyState == 4 && xhttp.status == 200) { try { var obj = JSON.parse(xhttp.responseText); console.log(obj) } catch (error) { throw Error; } } } Django code: def scoStart(request): user_id = request.session.get('idnickname') startdate = request.GET.get("startdate") """ Use the params """ response = {"user_id":user_id} return HttpResponse(json.dumps(response),'application/json') -
Error while uploading image from React to Django
I have following View in django i am able to upload images from Postman but i am getting this error when uploading from React. "KeyError: key profile_pic DoesNotExist" view class ProfilePictureUpload(APIView): """ Endpoint to update Profile picture """ parser_classes = (MultiPartParser, FormParser) permission_classes = [(permissions.IsAuthenticated & ProfilePagePermissions)] def put(self, request): print(f"request.data = {request.data.items()}, ") print(f"request.FILES = {dir(request.FILES.items())}") try: profile = Profile.objects.get(user__id=request.user.id) self.check_object_permissions(request, profile) except Exception as e: return Response(str(e), status=status.HTTP_404_NOT_FOUND) profile_pic_serializer = ProfilePicUpdateSerializer(profile, data=request.data) if profile_pic_serializer.is_valid(): profile_pic_serializer.save() return Response(profile_pic_serializer.data) return Response( profile_pic_serializer.errors, status=status.HTTP_400_BAD_REQUEST ) serializer class ProfilePicUpdateSerializer(serializers.ModelSerializer): """ Separate endpoint for updating profile picture because submitting profile picture in a form along with other fields is not a good UX """ class Meta: model = Profile fields = ["profile_pic"] def update(self, instance, validated_data): print(f"instance = {instance} \n validated data = {validated_data} ") instance.profile_pic = validated_data["profile_pic"] instance.save() return instance I am printing the validated here. It is validated data = {'profile_pic': <InMemoryUploadedFile: Andrew Garfield.jpg (image/jpeg)>} when tried from postman and it is empty dictionary when tried from React. React function ProfilePicUpload(props) { let { profile_pic } = props; const [loading, setLoading] = useState(false); const [file, setFile] = useState(); const handleSubmit = (e) => { console.log(file); e.preventDefault(); const formData = new FormData(); … -
Django / Model Forms
Completely new to all computer programming and trying to build an app that tracks my smoking habits. The first step was creating a Django model called packs: class packs (models.Model): timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, blank=False) num_packs = models.SmallIntegerField(max_length=10) cost_packs = models.DecimalField(max_digits=6, decimal_places=2) Next I created a forms.py page and this is where I started getting lost: from django.forms import ModelForm from .models import packs class packsForm(ModelForm): class Meta: model = packs fields = ['num_packs', 'cost_packs'] Of course that led to my failure in HTML trying to render a page that has all the form data: {%block content%} <div class = "form_pack"> <h3>FORM PACK</h3> <p> <form method="POST" action="."> {% csrf_token %} <input text="cost_pack" name=cost_pack> {{ form }} <input type="submit" value="save"/> </form> </p> </div> {% endblock %} To help my view.py looks like this: def packs_create(request): form=packsForm(request.POST or None) if form.is_valid(): return render(request, 'pack/index.htmnl', {'form': form}) Now when I refresh the page I don't get the form. Just the one input i put in. Can someone help me sort out which path I got lost in and where I need to connect the dots? I believe my forms.py is not complete, but not sure where to progress... Thanks, DrKornballer -
Optimizing for loop inside for loop django
I have a function which checks for a profile name and determines if it is in a tagged profile name. def check_profiles(request): try: # get all individual profiles profiles = Profile.objects.all() # get all individual tagged profiles tagged_profiles = TaggedProfiles.objects.all() # ids to exclude in adding dates exclude_profiles = [] # for profile in profiles for profile in profiles: # for tagged in sdn list for tagged_profile in tagged_profiles: # if contains 1 if any(name in tagged_profile.name_breakdown() for name in profile.name_breakdown()): # put in exclude exclude_profiles.append(profile.pk) profile.status = 'FOR REVIEW' profile.save() break for profile in Profile.objects.all().exclude(pk__in = exclude_profiles): cleared_dates = profile.cleared_dates cleared_dates.append( { 'date': datetime.now().strftime('%Y-%m-%d'), 'time': datetime.now().strftime('%I:%M %p') }) logger.debug(cleared_dates) profile.cleared_dates = cleared_dates profile.save() except Exception as e: logger.error(e) Basically, if a profile's name is 'firstname lastname', it's breakdown is ['firstname', 'lastname']. And if tagged_profiles include either a 'firstname' or a 'lastname' in any of it's breakdowns, it's a hit. But I'm doing it very inefficiently. How may I optimize it with any of django's built in functions? -
Django Nested Serialization
this is my serializor.py class AddressSerializor(serializers.ModelSerializer): class Meta: model = Address fields = 'all' class PersonSerializer(serializers.ModelSerializer): a = AddressSerializor(many=True) class Meta: model = Persion fields = ('id' ,'name', 'age', 'a' ) I am getting: Got AttributeError when attempting to get a value for field a on serializer PersonSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Persion instance. Original exception text was: 'Persion' object has no attribute 'a'. can any one help me what am i missing! -
How can i work with Jquery in Python Django project
I can't user JQuery in Django. This if from index.html <button type="submit" class="btn btn-success" id="mybtn">Send</button> And this is from layout.html <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/jquery-3.6.0.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> And this is JQuery Function from index.html <script> $(document).ready(function(){ $("#mybtn").click(function(event){ alert("Clicked"); }) }) </script> This is INSTALLED_APPS INSTALLED_APPS = [ 'bonusapp.apps.BonusappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I checked the file directories Bootstrap in the same directory is working JQuery is not working somehow. Can you help? I've tried many different ways but none of them work. -
Assign Html form value to python input variable using django
I have a separate Django project in which I have created a html form that take input from the user in the templates directory. And a separate python project that take input from the user and gives output. The problem is I want to take the input of that python project form the html form and show the output on the same html page -
Django filter on combination using F
I wrote the following query using the Django ORM: fixtures = Fixture.objects.filter(league=league).filter((Q(predictions__value__gt=0.0) & Q(predictions__team=F("home"))) & (Q(predictions__value__gt=0.0) & Q(predictions__team=F("away")))) With this I'm trying to filter out each fixture where the prediction__value for the home is greater than 0.0 and the prediction__value of the away is greater than 0.0. Sadly my query is returning 0 records upon using .count() whereas it should return almost every record. When I only use one part of the query; so either the home or the away part the query does return a certain amount of records. The value of league is irrelevant here. -
override save and clean method in django
hello i have StoreCheckout model and i override save and clean method but conditions in override methods not work. class StoreCheckout(models.Model): store = models.ForeignKey( to=Store, on_delete=models.CASCADE, limit_choices_to={ 'is_confirm': True }, ) pay_date = models.DateTimeField() amount = models.PositiveBigIntegerField() bank_number = models.PositiveBigIntegerField(validators=[bank_number_validate]) def __str__(self): return self.store.name def save(self, *args, **kwargs): if not self.bank_number: self.bank_number = self.store.bank_number if not self.pay_date: self.pay_date = datetime.now() super(StoreCheckout, self).save(*args, **kwargs) def clean(self, *args, **kwargs): if not settings.MIN_CHECKOUT <= self.store.wallet <= settings.MAX_CHECKOUT: raise ValidationError( f'amount of your store must between {settings.MIN_CHECKOUT} and {settings.MAX_CHECKOUT} toman' ) super(StoreCheckout, self).save(*args, **kwargs) -
Integrity Error: UNIQUE Constraint failed - Django
login = forms.CharField(label="Username:") password = forms.CharField(label="Password", widget=forms.PasswordInput()) confirm_password = forms.CharField(label="Confirm Password:", widget=forms.PasswordInput()) email = forms.EmailField(label="Email") def clean_username(self): print(f"Clean Username data: {self.cleaned_data}") username = self.cleaned_data.get("login") print("cleaning username...") existing_user_set = User.objects.filter(username=username) if existing_user_set.exists(): raise forms.ValidationError("Username is taken!!") return username def clean(self): data = self.cleaned_data print(f"\n\nData from cleaned data: {data}") password = data.get('password') confirm_password = data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Passwords do not match.") return data I have implemented this even for the 'email' field. however I receive this error only for the 'username' field. This is where it fails: username = register_form.cleaned_data.get("login") email = register_form.cleaned_data.get("email") password = register_form.cleaned_data.get("password") new_user = User.objects.create_user(username, email, password) ... print(f"Newly created user: \n{ new_user }")``` -
Adding a extra field to user (create user including that field)
I want to use an extra field let me distinguish between user roles. For that, I've overriden the User class: class User(AbstractUser): role = models.CharField(max_length=21, blank=False) I've also put this in settings.py: AUTH_USER_MODEL = 'shopping.User' The problem is that I have the new field in my database, but, if I want to create a new user using the admin, it doesn't ask me for the role. I suppose that I have to override the save method too, but I don't know how. Thanks in advance -
Any suggestions on how to improve programming ability without actually coding?
My background is web development for around a year using Django and react. In the following year, I have to go out for 2 weeks per month, without being around a pc. Anyone has an idea about how to overcome this obstacle and improve my skills? -
Getting model data associated with a username and displaying it in HTML in Django
I have a model that associates points and donations with a user. In my view, I want to get the data for the user who is currently logged in and display his donations and points in HTML. How would I go about doing this? The model, view, and HTML are down below. View (I want to get the points and donations assosicated with the user currently logged in).: @login_required(login_url='/login/') def dashboard(request): return render(request,'dashboard.html', ) Model: class userdetails(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) HTML (Instead of a 0, I want to display the points, and the same for the donations): <div class="box"> <span class="value">0</span> <span class="parameter">Points</span> </div> <div class="box"> <span class="value">0</span> <span class="parameter">Donations</span> </div> Thank you to everyone who helps! -
Recover XMLHttpRequest() with django
I'm trying to do an XMLHttpRequest() with js and recover the data with django and I received None but in the js code the status is 200 and the info is returned. How can I fix that to use the data send with the XMLHttpRequest()? js code: var xhttp = new XMLHttpRequest(); var data = JSON.parse('{"startdate":'+start_Date+'}') console.log(data) xhttp.open("GET", "/scoStart/", true); xhttp.send(data); xhttp.onreadystatechange = function () { if (xhttp.readyState == 4 && xhttp.status == 200) { try { var obj = JSON.parse(xhttp.responseText); console.log(obj) } catch (error) { throw Error; } } } Django code: def scoStart(request): user_id = request.session.get('idnickname') startdate = request.GET.get("startdate") return HttpResponse(json.dumps({str(user_id):user_id}),'application/json') -
GEOSException while try to add a new object to database in django - geoDjango
-> whenever i try to add a new estate a GEOexception error pops up I don't know if its because the configuration of gdal, idk If m doing something wrong. model.py: class Estate(models.Model): """model the estates class which will control the estates management aspect """ Es_label = models.CharField(max_length=20, unique=True, null=False) Es_description = models.TextField(max_length=200, unique=True, null=False) Es_surface = models.FloatField(null=False) Es_characteristics = JSONField(blank=True, null=True) Es_equipment = JSONField(blank=True, null=True) Es_geoLocation = PointField() objects = Manager() Es_sold = models.BooleanField(default=False) slug = models.SlugField(max_length=200, unique=True, default="SlugX") # define foreign keys for estates tables Es_project = models.ForeignKey( Project, on_delete=models.CASCADE, null=False) Es_status = models.ForeignKey(Status, on_delete=models.CASCADE, null=False) Es_Type = models.ForeignKey(Type, on_delete=models.CASCADE, null=False) i configure gdal to be accessed within my venv called Genv settings.py #setting up path for gdal to be used from within the env import os if os.name == 'nt': VENV_BASE = os.environ['VIRTUAL_ENV'] os.environ['PATH'] = os.path.join(VENV_BASE,'lib\\site-packages\\osgeo') + ';' + os.environ['PATH'] os.environ['PROJ_LIB'] = os.path.join(VENV_BASE,'lib\\site-packages\\osgeo\\data\\proj') + ';' + os.environ['PATH'] #GDAL_LIBRARY_PATH = 'D:\Final_Studies_Project\Genv\lib\site-packages\osgeo\gdal303.dl l' admin.py from django.contrib import admin from django.contrib.gis.admin import OSMGeoAdmin # Register your models here. from .models import * admin.site.register(Project) admin.site.register(Type) admin.site.register(Media) admin.site.register(NewsLetter) admin.site.register(Status) @admin.register(Estate) class MarkerEstateAdmin(OSMGeoAdmin): """Marker admin.""" list_display = ("Es_label", "Es_geoLocation") -
HttpOnlyCookie not being set after I added domain to my website
I'm trying to upload my first website which consists of frontend(react) and backend(django). So when I use it on development, all works just fine, it also works fine when I search for the IP of my VPS, but the problem comes when I try to login with the domain instead of the ip, for some reason the cookie isn't set after I login, but in with the IP it does, fyi both of them use the exact same backend and frontend. Here is the web: website with domain and here is the one without domain/IP website without domain -
QuerySet' object has no attribute 'posts'
Am having a challenge to get users post on their timeline and I would appreciate if anyone could help me. I keep coming against this error(QuerySet' object has no attribute 'posts') when ever filter through the post object. I wonder what am missing out on here ? here is my model for post. class Post(models.Model): description = models.CharField(max_length=5000, blank=True) pic = models.ImageField(upload_to='path/post/img' ,blank=True) date_posted = models.DateTimeField(auto_now_add=True) user_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users") tags = models.CharField(max_length=100, blank=True) here is my view for users account since i want every user to have their post on their timeline. def account_view(request, *args, **kwargs): """ - Logic here is kind of tricky is_self is_friend -1: NO_REQUEST_SENT 0: THEM_SENT_TO_YOU 1: YOU_SENT_TO_THEM """ context = {} user_id = kwargs.get("user_id") try: account = User.objects.get(pk=user_id) except: return HttpResponse("Something went wrong.") if account: context['id'] = account.id context['username'] = account.username context['bio'] = account.bio context['get_full_name'] = account.get_full_name context['email'] = account.email context['profile_pic'] = account.profile_pic.url context['cover_image'] = account.cover_image.url context['city'] = account.city context['country'] = account.country context['gender'] = account.gender context['hide_email'] = account.hide_email try: post_list = Post.objects.filter(user_name=account) except Post.DoesNotExist: post_list = Post(user_name=account) save.post_list() posts = post_list.posts.all() context['posts'] = posts try: friend_list = FriendList.objects.get(user=account) except FriendList.DoesNotExist: friend_list = FriendList(user=account) friend_list.save() friends = friend_list.friends.all() context['friends'] = … -
Django - storing session object in settings.py
I have an api(legacy), a front end app(legacy) , and a django app(in development). Both the legacy front end app is fully working with the legacy api that operates with a mysql database. I have integrated my django app with that database and for some features I am using some endpoints from the legacy api. In order to do that I must login by sending credentials to that api - I am doing this using python sessions in order to store the cookie. Question Is it safe to instantiate the session object in the settings.py? from requests import Session session = Session() Is there a better way to communicate with the legacy api? Maybe using django sessions as cookie, I have tried many ways to make it work and it works now. If I am using a cookie with JSESSIONID=random string then api does not accept that as a cookie. That's why I am using python sessions. -
Trouble deploying django webapp onto google cloud
I've been following the google cloud documentation titled, "Running Django on the App Engine standard environment" . I'm using the same app provided in the documentation in the "Cloning the Django App". Honestly, I get lost in the google cloud documentation under the "Configuring Database Settings" section. This what my settings.py (mysite/settings.py in the given app mentioned previously) Mysite/settings.py img Whenever running python manage.py makemigrations - I get the following error message on the CLI... django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable Also, I have noticed there is no .env file in that repo. Would I maybe have to create it myself or would is it fine? Again I am using the github given app via the documentation. Just trying to deploy Django website to google cloud. Any help would be greatly appreciated. Im on Mac Big Sur btw if that matters.