Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build a docker image (without docker compose) of a django app and use an existing mysql container
I have a "point of sales" application in Django that uses a mysql database. I followed this Docker guide: Python getting started guide In order to setup the mysql container I created a couple of volumes and its network: docker volume create mysql docker volume create mysql_config docker network create mysqlnet My Dockerfile looks like this: (I don't want to use docker-compose yet becouse I want to learn the bases) Dockerfile # syntax=docker/dockerfile:1 FROM python:3.8-slim-buster RUN apt update RUN apt upgrade -y RUN apt dist-upgrade RUN apt-get install procps -y RUN apt install curl -y RUN apt install net-tools -y WORKDIR /home/pos COPY requirements.txt ./. RUN pip3 install -r requirements.txt COPY ./src ./src CMD ["python", "./src/manage.py", "runserver", "0.0.0.0:8000"] And in the Django project my database settings and requirements looks like: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'point-of-sales', 'USER': 'root', 'PASSWORD': 'r00t', 'HOST': 'localhost', 'PORT': '3307' } } requirements.txt # Django django>=3.1,<3.2 # DRF djangorestframework>=3.12,<3.13 # Databases mysqlclient What I want is to build an image of the Django application that I could run and attach to the mysql network. The problem is that I can't build the image of my django app becouse it throws the following … -
Azure python library return web app configurations
I am trying to deep dive into azure python sdk to retrieve and control all my resources in azure, but I am having hard time to find any valid documentation on the following issue. using this code: resource_client = ResourceManagementClient(credentials, subscription_id) web_client = WebSiteManagementClient(credential=credentials, subscription_id=subscription_id) rg_subscription = resource_client.resource_groups.list() web_apps_test = [] for rg in list(rg_subscription): for site in web_client.web_apps.list_by_resource_group(rg.name): print(site) I am able to return all my azure web app service. Which is great, but what I would like to have more is to be able for each web app, to return its configurations so I can extract specific values from it. I have been looking around since yesterday but I am having some problems to find the right documentation, code or GitHub project to achieve this. Just to give a practical example of what I am looking for, is this: Using azure cli, I can run the command az webapp config show --name <webapp-name> -g <resource-group-name> and I will get all the configurations for the specific web app. I was wondering if there is any python library to achieve this using python. Can anyone help to solve this please?any help would be much appreciated. And please if my question … -
Django Allauth - allow to sign up again if email is unverified
Suppose, user A tries to sign up with an email not of their own (user's B email). He fails to verify it and hence fails to sign in. Some time later user B encounters the site and tries to sign up, but they fail as well with a message "A user is already registered with this e-mail address." From what I see in admin site, it is true, the user instance is actually created, even though the email is unverified. Is there a way to easily allow user B to sign up (i.e. overwrite the unverified user instance)? Or what is the standard way of dealing with this situation? -
change password in django rest framework
I am working on change password function for an API. My code runs fine locally. The problem is that when testing in postman I have to connect it using the login token. But in login, I have two passwords refresh and access. How should I configure Postman to give me access? I was advised to use Bearer and accept allow_classes = [permissions.IsAuthenticated] but when doing so, the login stops working and still cannot give access to password change. -
Retrieve stripe session id at success page
I am using stripe with django and I want to pass some information I received from the checkout session to success page. After reading the documentation https://stripe.com/docs/payments/checkout/custom-success-page#modify-success-url I modified success url to MY_DOMAIN = 'http://127.0.0.1:8000/orders' success_url=MY_DOMAIN + '/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=YOUR_DOMAIN + '/cancel/', metadata={ "price_id": price_id, } ) def Success(request): session = stripe.checkout.Session.retrieve('session_id') return render(request, 'orders/success.html') But this gives me an error: Invalid checkout.session id: session_id If I manually put instead of "session_id" the actual id that is printed in the url everything works fine. So my question is what should I write instead of 'session_id' in order to retrieve the session? -
Accessing UserProfile data from foreign key related Post
I am currently working on a little django app, the app is like a social media app. User can post, like and comment. I recently created the User Profiles. Which I can now see the user for that user profile in my view, but I cant seem to dig into the Posts that may be related to the UserProfile. what I am trying to do is in my view of HTML, I want to be able to get the post from the userprofile and the comment, and likes. But I have tried everything and nothing works. Currently in my HTML view I have rendered {{ profile.user }} and it displays the users name, but If I try profile.user.post or profile.user.comments I get nothing. Here is some code to show where I am at. Any help would be much appreciated. Profile View. def profile(request): profile = get_object_or_404(UserProfile, user=request.user) template = 'profiles/profile.html' context = { 'profile': profile, # 'posts': posts } return render(request, template, context) Profile Model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): """ A user profile model to link posts and likes """ user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") def … -
Django: EmailMessage encode the subject in base64 when translated and contains non US-ASCII characters
The usual behavior of the EmailMessage class regarding its subject is to keep it as it is if i contains only US-ASCII characters and to encode it as quoted-printable if it contains non US-ASCII characters. That works well and avoid our emails to be considered as pishing by antispam from email servers But in the specific context of translations there is a bug -> if the subject of an email is translated into another language (through the built-in django translations tools) and contains non US-ASCII characters, by an mechanism I didn't catch, the subject is encoded as base64 and not quoted-printable. This results in being considered as spam by the email servers (tested on Gandi and Gmail)... I submitted a ticket on https://code.djangoproject.com/ Do you have any idea of the mechanism that leads to this encoding in base64 instead of quoted-printable when we translate the subject of a mail ? -
I am getting this IntegrityError at /registration/ NOT NULL constraint failed: bankapp_registration.date_of_birth error
models.py from django.db import models # Create your models here. class Registration(models.Model): bank_ac = models.CharField(max_length=64) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) user_name = models.CharField(max_length=64) mobile_number = models.CharField(max_length=10) email = models.EmailField() password = models.CharField(max_length=18) date_of_birth = models.DateField(max_length=64) address = models.CharField(max_length=160) pin_code = models.IntegerField() views.py from django.shortcuts import render from bankapp.forms import RegistrationForm, LoginForm from bankapp.models import Registration from django.http import HttpResponse # Create your views here. def Home(request): return render(request, 'home.html') def RegistrationView(request): if request.method == 'POST': rform = RegistrationForm(request.POST) if rform.is_valid(): bac = request.POST.get('bank_ac') fname = request.POST.get('first_name') lname = request.POST.get('last_name') uname = request.POST.get('user_name') mnumber = request.POST.get('mobile_number') email = request.POST.get('email') password = request.POST.get('password') dob = request.POST.get('date_of_birth') address = request.POST.get('address') pin_code = request.POST.get('pin_code') data = Registration( bank_ac = bac, first_name = fname, last_name = lname, user_name = uname, mobile_number = mnumber, email = email, password = password, date_of_birth = dob, address = address, pin_code = pin_code ) data.save() rform = RegistrationForm() return render(request,'Registration.html', {'rform':rform}) else: return HttpResponse('User Entered invalid data') else: rform = RegistrationForm() return render(request,'Registration.html', {'rform':rform}) def LoginView(request): sform = LoginForm() if request.method == "POST": sform = LoginForm(request.POST) if sform.is_valid(): uname = request.POST.get('user_name') pwd = request.POST.get('password') print(uname) print(pwd) user1 = Registration.objects.filter(user_name=uname) password1 = Registration.objects.filter(password=pwd) if user1 and password1: return redirect('/') else: … -
Django datatable server side processing tutorial
I am using Django and there are lots of data in my table which takes times to load. Therefore, i would like to utilize enable server side processing. Is there a tutorial i can follow you may suggest. I tried to employ the datatable serverside and rest framework POST option as mentioned here. However, i could not utilize it because i am missing an intuitive understanding of the concept. If there would be any tutorial for me to follow i would like to know. Thanks for your attention. -
HTML Input Tage Values not saving in SQLite Database - Django
I am trying to save data from HTML Form to SQLite database. My database is connected to my app and project. I am able to enter from Django Admin, but my values from Input tag are not going in database. Views.py def add_record(request): if request.method == 'POST': ref_no = request.POST.get('ref_no') token_no = request.POST.get('token_no') agent_name = request.POST.get('agent_name') trip_no = request.POST.get('trip_no') date = request.POST.get('date') vehicle_no = request.POST.get('vehicle_no') bora = request.POST.get('bora') katta = request.POST.get('katta') plastic = request.POST.get('plastic') farmer_name = request.POST.get('farmer_name') farmer_address = request.POST.get('farmer_address') farmer_mob = request.POST.get('farmer_mob') gross_weight = request.POST.get('gross_weight') tier_weight = request.POST.get('tier_weight') net_weight = request.POST.get('net_weight') bora_weight = request.POST.get('bora_weight') suddh_weight = request.POST.get('suddh_weight') loading = request.POST.get('loading') unloading = request.POST.get('unloading') unloading_point = request.POST.get('unloading_point') dharamkanta_man = request.POST.get('daramkanta_man') rate = request.POST.get('rate') bardana = request.POST.get('rate') gross_total = request.POST.get('gross_total') deduction = request.POST.get('deduction') kanta = request.POST.get('kanta') hemali = request.POST.get('hemali') our_vehicle_rent = request.POST.get('our_vehicle_rent') agent_commission = request.POST.get('agent_commission') other_amt = request.POST.get('other_amt') other_remarks = request.POST.get('other_remarks') advance = request.POST.get('advance') net_total = request.POST.get('net_total') var_datasave = paddy_purchase(ref_no=ref_no, token_no=token_no, agent_name=agent_name, trip_no=trip_no, date=date, vehicle_no=vehicle_no, bora=bora, katta=katta, plastic=plastic, farmer_name=farmer_name, farmer_address=farmer_address, farm_mob=farmer_mob, gross_weight=gross_weight, tier_weight=tier_weight, net_weight=net_weight, bora_weight=bora_weight, suddh_weight=suddh_weight, loading=loading, unloading=unloading, unloading_point=unloading_point, dharamkanta_man=dharamkanta_man, rate=rate, bardana=bardana, gross_total=gross_total, deduction=deduction, kanta=kanta, hemali=hemali, our_vehicle_rent=our_vehicle_rent, agent_commission=agent_commission, other_amt=other_amt, other_remarks=other_remarks, advance=advance, net_total=net_total ) var_datasave.save() messages.success(request, 'Record saved successfully.') return redirect('index') return render(request, 'add.html') Models.py class paddy_purchase(models.Model): ref_no = models.IntegerField(primary_key='true') token_no = … -
django View - 'Comment' object has no attribute 'comments'
I'm trying to get my comments to be deleted but when I run the code the following error shows up: my comment_delete views: class CommentDelete(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'comment_delete.html' success_url = reverse_lazy('article_list') def test_func(self): obj = self.get_object() return obj.comments == self.request.user models.py Comment model: class Comment(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name='comments', ) name = models.CharField(max_length=140) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('article_list') -
broken django production webpage
I cannot figure out why only one webpage in django production server is broken. The same webpage renders as expected on the development server. Django renders the webpage partially. The script files are executed partially. This is very confusing and I don't know where to look. All the webpages render and execute script files as expected, except for one. Please help static settings: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = 'media/' TEMP_ROOT = os.path.join(BASE_DIR, 'temp/') TEMP_URL = 'temp/' -
Django How to do I search for a model data in HTML?
I have the following classes in my models.py file. class Resident(models.Model): house_number = models.CharField(max_length=100,unique=True,primary_key=True) name = models.CharField(max_length=100) contact_number = PhoneNumberField() def __str__(self): return self.house_number + " : " + self.name class Balance(models.Model): residents = models.OneToOneField(Resident, on_delete=models.CASCADE, primary_key=True) date = models.DateTimeField(default=timezone.now) previous_balance = models.DecimalField(max_digits=1000, decimal_places=2 , null=True) transaction = models.DecimalField(max_digits=1000, decimal_places=2, null=True) final_balance = models.DecimalField(max_digits=1000, decimal_places=2, null=True, editable=False) def save(self, *args, **kwargs): self.final_balance = self.previous_balance + self.transaction return super().save(*args, **kwargs) def __str__(self): return self.residents.name + " : " + str(self.final_balance) class Transaction(models.Model): transaction_id = models.UUIDField(primary_key=True,default=uuid.uuid4(), editable=False,unique=True) residents = models.ForeignKey(Resident, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) transaction_Amount = models.DecimalField(max_digits=1000, decimal_places=2) date = models.DateTimeField() category_choices = ( ('Monthly-Bill', 'Monthly-Bill'), ('Cash', 'Cash'), ('Transfer', 'Transfer'), ('EFT', 'EFT'), ) category = models.CharField(max_length = 13 ,choices = category_choices, default = 'Monthly-Bill') def save(self, *args, **kwargs): if self.transaction_id == "": self.transaction_id = generate_code() if self.created is None: self.created = timezone.now() try: last_bal = Balance.objects.filter(pk = self.residents).get() except Balance.DoesNotExist: Balance.objects.create(residents = self.residents, date=self.date, previous_balance=Decimal.from_float(0.00), transaction=self.transaction_Amount) else: last_bal.date = date=self.date last_bal.previous_balance = last_bal.final_balance last_bal.transaction = self.transaction_Amount last_bal.save() return super().save(*args, **kwargs) def __str__(self): return str(self.transaction_id) + " : " + self.residents.name I would like to know how can I create a dropdownlist using the Resident.name to search/filter for a particular Transaction in html? … -
django: populate multiple image upload with initial data
I have an image form field that accepts multiple images like so: images = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'form-control', 'multiple': True}), required=False) Now when you use a ClearableFileInput with an ImageField that accepts one image and populate it with initial data, it renders as something like this: I am wondering if it is possible to achieve a similar result with an ImageField that accepts multiple files? I.e. is it possible to populate the above field with initial data? -
Postgres asking unknown password
installing PostgreSQL for my Django Project. (vent) my_name@Name-MBP dir % createuser my_user createuser: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL: password authentication failed for user "my_name" Problem: I do not specify any password for user "my_name" and don't even create such user. HELP PLEASE!!! -
How to encrypt responses in DRF?
I want to encrypt my DRF project APIs responses Is there a way to encrypt large responses so that I only have access to the data on the front end side? I want to encrypt all responses. -
How can i split the value of a dropdown list option and pass it in two different input fields
How can i split the value of a dropdown list option and pass it in two different input fields scripts <script> function getsciname() { ("#selectsci").change(function() { var sciname = (this).val().split(','); ("#sid").val(sciname[0]); ("#sname").val(sciname[1]); }}; </script> (dropdown) select option code <select id="scinameid" class="scinameclass" onchange="getsciname()"> <option disabled="true" selected>-- Scientific name --</option> {% for getData in TaxonmyDistributionInsert %} <option value={{getData.id}},{{getData.ScientificName}}>{{getData.id}} - {{getData.ScientificName}}</option> {% endfor %} </select> input box code <input type="text" style="font-size: 16px" placeholder="Shrimp Prawn ID" name="ShrimpPrawnID" id="sid" /> <input type="text" style="font-size: 16px" placeholder="Scientific Name" name="ScientificName" id="sname" /> -
Check for a certain condition before processing each view in Django
I'm building a multi-tenant Django app, where I need to check for a certain condition before processing each view, similar to the login_required decorator which checks if user is authenticated or not. And if the condition is not true, stop processing the view and send the user to the login page. How can I implement this for each view in my app My condition - def index_view(request): domain1 = Domain.objects.get(tenant=request.user.client_set.first()) domain2 = request.META["HTTP_HOST"].split(":")[0] // Condition if str(domain1) != domain2: return redirect("accounts:login") return render(request, "dashboard/index.html") -
How can i run a python script in django
So a python script like Sherlock on Git hub, which sources usernames. Can that be run by clicking a button on a HTML page in a Django project and return a CSV file. How would this be done ? -
Stock quantity update when and order is placed in Django app
I have a product and order create models where I'd like to update the quantity of the product when and order is placed for that product. Using a ForeignKey, I am able to select the product but so far I'm definitely missing something as nothing i have tried seems to work, please take a look at my code below and assist. Thank you in advance Models.py #Product Model class Product(models.Model): SKU = models.CharField(max_length=30, unique=False,default='input SKU') Category = models.CharField(max_length=200,default='Input Category') Name = models.CharField(max_length=250,unique=False, default='Input product name') Platform = models.CharField(max_length=50, default='platform') Price = models.PositiveIntegerField(default='price') Discount = models.PositiveIntegerField(default='discount') Prod_Qty = models.PositiveIntegerField(unique=False, default=0) Date = models.CharField(max_length=30, default='Char field') Cost = models.PositiveIntegerField() created_date = models.DateField(auto_now_add=True) def __str__(self): return self.Name class Order(models.Model): STATUS_CHOICE = ( ('pending', 'Pending'), ('decline', 'Decline'), ('approved', 'Approved'), ('processing', 'Processing'), ('complete', 'Complete'), ('bulk', 'Bulk'), ) SALE_CHOICE = ( ('platform1', 'platform1'), ('platform2','platform2') ) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=False) sale_type = models.CharField(max_length=50, choices=SALE_CHOICE, null=True) cost_goods_sold = models.PositiveIntegerField(default=6) shipping_fee = models.PositiveIntegerField(null=False) shipping_cost = models.PositiveIntegerField(default=0) buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE, null=True) manifest = models.ForeignKey(Manifest, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices=STATUS_CHOICE) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.product.Name Views.py # Product views @login_required(login_url='login') def create_product(request): forms = ProductForm() context = {"form": forms} if request.method … -
1v1 Game Django using Javascript / Html
I'm having for the moment a memory card game using JS & html on Django I would know where do I have to search to make it like a 1v1 game. People would be able to create a 1v1 room (lobby) and then play this memory card game If you guys have any clues, will appreciate. Bru -
CS50w commerce project: 'The bid must be as large as the starting bid, and must be greater than any other bids that have been placed (if any)'?
So I have solved this particular problem, but there is something that I noticed and didn't get why was it behaving the way it did. So the below code worked the way I wanted it to work: def bid_placed(request,listing_id): if request.method == "POST": recent_bid = Bid( Bid_amount = request.POST["bid_amount"], listing = Listing.objects.get(pk=listing_id) ) listing = Listing.objects.get(pk=listing_id) starting_Bid = listing.Starting_Bid recent_bid_int = int(recent_bid.Bid_amount) if recent_bid_int > starting_Bid: listing.Starting_Bid = recent_bid_int listing.save() return HttpResponse("Bid SUCCESSFULLY Placed") else: return HttpResponse("Bid CANNOT be placed") But the below code is NOT working as desired, even though the starting_Bid variable has been declared: def bid_placed(request,listing_id): if request.method == "POST": recent_bid = Bid( Bid_amount = request.POST["bid_amount"], listing = Listing.objects.get(pk=listing_id) ) listing = Listing.objects.get(pk=listing_id) starting_Bid = listing.Starting_Bid recent_bid_int = int(recent_bid.Bid_amount) if recent_bid_int > starting_Bid: starting_Bid = recent_bid_int listing.save() return HttpResponse("Bid SUCCESSFULLY Placed") else: return HttpResponse("Bid CANNOT be placed") ``` Can someone please guide, why it might be the case.? Thanking you in advance.! -
Why I am getting the NGINX welcome page instead of my Django application
I have deployed my Django Application on a VPS server. I have configured NGINX and uWSGI server. Here is my Nginx configuration # the upstream component nginx needs to connect to upstream django { server unix:///root/PIDC/ProjetAgricole/ProjetAgricole.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name my_public_IP_address; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /root/PIDC/ProjetAgricole/media; } location /static { alias /root/PIDC/ProjetAgricole/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /root/PIDC/ProjetAgricole/uwsgi_params; } } Here is my mysite_uwsgi.ini file # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /root/PIDC/ProjetAgricole # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /root/my_project/venv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe … -
How to get data from a running task in Python(Django)
I have a script to compare and move my files around, which is to be called by cmp_object = my_cmp.Compare('/mnt/f/somedir', '/mnt/f/newdir') cmp_object.main() and the Compare class is defined as class Compare: def __init__(self, path1, path2): self.path1 = path1 self.path2 = path2 self.totalFileNumber = getTotalFileNumber(path1) self.totalFileSize = getTotalFileSize(path1) self.progress = 0 self.progressPercent = 0 self.status = 'Not started' self.started = False self.finished = False def start(self): self.status = 'Started' self.started = True self.finished = False def update(self, index): self.progress = index self.progressPercent = round( self.progress / self.totalFileNumber * 100, 2) self.status = f'{self.progressPercent}%' if self.progressPercent == 100: self.status = 'Finished' self.finished = True def getStatus(self): return self.status def getProgress(self): return self.progressPercent def getTotalFileNumber(self): return self.totalFileNumber def getTotalFileSize(self): return self.totalFileSize def isStarted(self): return self.started def isFinished(self): return self.finished def main(self): self.start() for index, file in enumerate(listAllFiles(self.path1)): compareFiles(file, self.path2 + file[len(self.path1):]) self.update(index) self.update(self.totalFileNumber) self.finished = True , which has functions to get and set some states like progress, status and finish. I am running this on Django backend, where I would be retrieving information from the backend by setting an interval... I am using cache to set and get the states across different views, but I'm not sure how can I keep on … -
Django Terraform digitalOcean re-create environment in new droplet
I have saas based Django app, I want, when a customer asks me to use my software, then i will auto provision new droplet and auto-deploy the app there, and the info should be saved in my database, like ip, customer name, database info etc. This is my terraform script and it is working very well coz, the database is now running on terraform { required_providers { digitalocean = { source = "digitalocean/digitalocean" version = "~> 2.0" } } } provider "digitalocean" { token = "dop_v1_60f33a1<MyToken>a363d033" } resource "digitalocean_droplet" "web" { image = "ubuntu-18-04-x64" name = "web-1" region = "nyc3" size = "s-1vcpu-1gb" ssh_keys = ["93:<The SSH finger print>::01"] connection { host = self.ipv4_address user = "root" type = "ssh" private_key = file("/home/py/.ssh/id_rsa") # it works timeout = "2m" } provisioner "remote-exec" { inline = [ "export PATH=$PATH:/usr/bin", # install docker-compse # install docker # clone my github repo "docker-compose up --build -d" ] } } I want, when i run the commands, it should be create new droplet, new database instance and connect the database with my django .env file. Everything should be auto created. Can anyone please help me how can I do it? or my approach is …