Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
View function that handles only POST requests to check database
My friends and I are writing a game that uses a website for registration/login. When a player logs into the game, it'll check the Django website's SQLite database using a POST cURL request or an equal to see if the player is valid. What should I sent in my request and how should I write my function that handles this? http://127.0.0.1:8000/login/ Login includes Username Password import requests url = 'http://localhost:8000' data = { "username": "password" } x = requests.post(url, data=data) print(x.status_code) Currently, this is all I have. It tells me I have to add the CSRF token. But would just doing this and adding the csrf token work? -
django form not being saved to db
<div class="review-form"> <h1 class="review-title">Add Review</h1> <form class="form" method="POST"> {% csrf_token %} <div>{{ form.title }}</div> <textarea>{{ form.description}}</textarea> <br> <button class="submit-btn" type="submit">Submit</button> </form> </div> **forms.py** from . import models from django import forms class gameReviewForm(forms.Form): title = forms.CharField(max_length=24) description = forms.CharField(max_length=500) **models.py** from django.db import models from django.db.models.fields import AutoField, CharField, TextField class gameReview(models.Model): title = CharField(max_length=24) description = CharField(max_length=500) def __str__(self): return self.title **views.py** def add_review(request): if request.method == 'POST': form = forms.gameReviewForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] review = models.gameReview(title=title, description=description) review.save() return HttpResponseRedirect('home') else: form = forms.gameReviewForm() return render(request, 'main/add_review.html', {'form': form}) // I am trying to post data to the database but for some reason it's not actually working! Any help is greatly appreciated, the redirect doesnt execute so it seems to me that the form is somehow invalid -
Access One to One Field property in DRF Serializer
I am having trouble with setting the password as a write_only property in my Serializer. This is what I currently have, and I want to hide the password. { "nit": "54545445", "direccion": "ciudad", "telefono": "54545454", "usuario": { "id": 12, "password": "asdf12321", "last_login": null, "is_superuser": false, "username": "admin3", "first_name": "admin3", "last_name": "admin3", "email": "admin3@gmail.com", "is_staff": false, "is_active": true, "date_joined": "2021-06-24T20:47:56.286694Z", "groups": [], "user_permissions": [] } } There should be a way of getting that value in my serializer to set the write_only=True property. class UserExtraSerializer(serializers.ModelSerializer): class Meta: model = UserExtra fields = ['nit', 'direccion', 'telefono', 'usuario'] depth = 1 extra_kwargs = {''''access usuario['password'] here''': {'write_only': True, 'required': True}} -
How to get HTML5 Video page or direct download link from downloadAddr or playAddr on Tiktok
I have compacted Python + PHP project it can collect data from video page in Tiktok, now i need way to get direct video link from Tiktok cdn to download this video or create HTML5 video to show this video? because the link from downloadAddr not working if I test it in other pc or browser and thank you. what I need exactly is class with python or PHP receive URL from request and respond with the link of watching or download video from Tiktok cdn. -
How to solve ModuleNotFoundError: No module named '{{cookiecutter' in docker django
I am getting this error while running docker build. File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 204, in fetch_command #14 0.440 app_name = commands[subcommand] #14 0.440 KeyError: 'collectstatic' #14 0.440 #14 0.440 During handling of the above exception, another exception occurred: #14 0.440 #14 0.440 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed #14 0.440 File "<frozen importlib._bootstrap>", line 1014, in _gcd_import #14 0.440 File "<frozen importlib._bootstrap>", line 991, in _find_and_load #14 0.440 File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked #14 0.440 File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed #14 0.440 File "<frozen importlib._bootstrap>", line 1014, in _gcd_import #14 0.440 File "<frozen importlib._bootstrap>", line 991, in _find_and_load #14 0.440 File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked #14 0.440 ModuleNotFoundError: No module named '{{cookiecutter' I have installed cookiecutter via pip. How to solve this? -
how can i create rows in 2 models(tables) with reusable functions based on one form
I want to save data in two models from a single POST request. Two different models (OF, Encours) Here's my models.py: class OF(models.Model): Id_OF= models.BigAutoField(primary_key=True) Numero_Of = models.BigIntegerField(unique=True,blank=False) class Dimension_OF(models.TextChoices): PD_inférieur_à_500mm="PD" MD_Entre_500_et_1500mm="MD" GD_supérieur_à_1500mm="GD" Dimension_OF = models.CharField(max_length=20, blank=False,choices=Dimension_OF.choices) class Machine(models.TextChoices): MGP1="MGP1" MGP2="MGP2 " MGP3="MGP3" MGP4="MGP4" MGP5="MGP5" MGP6="MGP6" MGP7="MGP7" MGP8="MGP8" Machine=models.CharField(max_length=10,choices=Machine.choices, blank=False) class Scenario(models.TextChoices): Ajustage_Controle="scenario1" Ajustage_Redressage_Controle="scenario2" Ajustage_Formage_Controle="scenario3" Ajustage_Redressage_Formage_Controle="scenario4" Scenario = models.CharField(max_length=50,choices=Scenario.choices, blank=False) Date_E_initial=models.DateTimeField(auto_now_add=True,auto_now=False) Date_S_Final=models.DateTimeField(null=True, blank=True) Etat_OF=models.CharField(max_length=50, null=True, blank=True) Nb_jrs_att_Usin=models.DurationField(null=True, blank=True) Nb_jrs_att_TM=models.DurationField(null=True, blank=True) Nb_jrs_att_total=models.DurationField(null=True, blank=True) def _str_(self): return self.Scenario class Encours(models.Model): Id_encours=models.IntegerField(primary_key=True) OF = models.ForeignKey(OF, on_delete=models.CASCADE ) class Nom_encours(models.TextChoices): EN_MGP1="Encours MGP1" EN_MGP2="Encours MGP2" EN_MGP3="Encours MGP3" EN_MGP4="Encours MGP4" EN_MGP5="Encours MGP5" EN_MGP6="Encours MGP6" EN_MGP7="Encours MGP7" EN_MGP8="Encours MGP8" EN_AJU_GD="Encours Ajustage GD" EN_AJU_MD="Encours Ajustage MD" EN_AJU_PD="Encours Ajustage PD" EN_RED="Encours Redressage" EN_For="Encours Formage" EN_Contr_GD="Encours Contrôle GD" EN_Contr_MD="Encours Contrôle MD" EN_Contr_PD="Encours Contrôle PD" Nom_encours = models.CharField(max_length=30,choices=Nom_encours.choices) Capacite = models.IntegerField(default=0) Date_E_Encours=models.DateTimeField(null=True, blank=True) Date_S_Encours=models.DateTimeField(null=True, blank=True) def _str_(self): return self.Nom_encours But before saving data into Encours I want to define some functions to test field for exemple ; if OF.Machine=='MGP1' then create a row in Encours model with Nom_Encours='Encours MGP1' and Date_E_Encours = Date_E_initial that automatically added. views.py def lancerOF(request): form = OFLancementForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() messages.success(request, 'OF lancé avec succès', extra_tags='alert') return redirect('lancer') else: messages.warning(request, … -
Django group by multiple column and get count of unique combination
In my model there are 10 fields, out of which below four I need to group on, department city state zip And then get count of records which has same combination of these values Example IT|Portland|Oregon|11111 => 100 I tried annotate however it is not giving me desired results. Please advice -
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?