Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerfile Customization for Google Cloud Run with Nginx and uWSGI
I'm trying to migrate a Django application from Google Kubernetes Engine to Google Cloud Run, which is fully managed. Basically, with Cloud Run, you containerize your application into a single Dockerfile and Google does the rest. I have a Dockerfile which at one point does call a bash script via ENTRYPOINT But I need to start Nginx and start Gunicorn. The Google Cloud Run documentation suggest starting Gunicorn like this: CMD gunicorn -b :$PORT foo.wsgi (let's sat my Django app is named "foo") But I also need to start Nginx via: CMD ["nginx", "-g", "daemon off;"] And since only one CMD is allowed per Dockerfile, I'm not sure how to combine them. To try to get around some of these difficulties, I was looking into using a Dockerfile to build from that already has both working and I came across this one: https://github.com/tiangolo/meinheld-gunicorn-docker But the paths don't quite match mine. Quoting from the documentation of that repo: You don't need to clone the GitHub repo. You can use this image as a base image for other images, using this in your Dockerfile: FROM tiangolo/meinheld-gunicorn:python3.7 COPY ./app /app It will expect a file at /app/app/main.py. And will expect it to contain … -
How to check existence of a record in a model from current authenticated user in Django template?
Code below checks whether a user added a product in cart or not. If it is added to cart by this current user it should show remove from cart button else it should show a simple form to add product in cart. {% for ordereditem in item.ordereditems_set.all %} {% if ordereditem.quantity > 0 and ordereditem.user.username == user.username %} <a href="{{ item.get_remove_from_cart_url }}">Remove from cart</a> {% elif not ordereditem %} # here! <!-- else if there is no record of 'ordereditem' from current user show this form to add it to cart--> <form class="d-flex justify-content-left" method="POST" action="{{ item.get_add_to_cart_url }}"> {% csrf_token %} <input type="number" name="number" value="1"> <input type="submit" value="Add to cart"> </form> {% endif %} {% endfor %} the problem lies here {% elif not ordereditem %} it seems like my current if statement doesn't meet the condition I expect. I tried using {% else %} but it still shows the form even after adding product to cart. This is how models look like: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='Discount', null=True, blank=True) image = models.ImageField(upload_to='products/%Y/%m/%d/') image_cover = models.ImageField(upload_to='products/%Y/%m/%d/') description = models.TextField() slug = models.SlugField(max_length=150, blank=True, null=True) category = models.CharField(max_length=15, choices=CATEGORY_CHOICE) label = models.CharField(max_length=10, choices=LABEL_CHOICE) … -
Django management commands when using AWS Fargate
I have deployed a Django application using the AWS Fargate service. It is so far working good, but I am wondering if there is any quick / easy way to interact with the Django management commands? What would be the best way to achieve this? Thanks -
How to get a single model object with a relation to the template in Django
I am working on this project that I can add two or more forms in a template. I am able to get the two forms in the template but when I submit the form, I get the objects for the rentalproperty model and not the contract model. I have created two different solution but the two doesn't solve the problem. The first solution below display both objects multiple times in the detailview but what I want is to display the two model objects just once. The second solution display the rentalproperty object once but the contract objects multiple times. Could someone point me in the right direction? Thanks. First solution: views.py class DetailView(generic.DetailView): model = RentalProperty template_name = 'rental/detail.html' context_object_name = 'property' def new_rental(request, pk): if request.method == 'POST': rental_form = NewRentalPropertyForm(request.POST, request.FILES, prefix = "rentals") contract_form = NewContractForm(request.POST, prefix = "contracts") if rental_form.is_valid() and contract_form.is_valid(): print ("all validation passed") rentalproperty = rental_form.save() contract_form.cleaned_data["rentalproperty"] = rentalproperty print(contract_form) contract = contract_form.save(commit=False) contract.rentalproperty = rentalproperty contract = contract_form.save() return HttpResponseRedirect(reverse("home")) else: messages.error(request, "Error") contract = Contract.objects.get(pk=pk) else: rental_form = NewRentalPropertyForm(prefix = "rentals") contract_form = NewContractForm(prefix = "contracts") contract = Contract.objects.get(pk=pk) return render(request, 'rental/new_rental.html', { #'rentalproperty': rentalproperty, 'rental_form': rental_form, 'contract_form': contract_form, 'contract': contract, … -
Get Django ALLOWED_HOSTS env. variable formated right in settings.py
I'm facing the following issue. My .env files contains a line like: export SERVERNAMES="localhost domain1 domain2 domain3" <- exactly this kind of format But the variable called "SERVERNAMES" is used multiple times at multiple locations of my deployment so i can't declare this as compatible list of strings that settings.py can use imidiatly. beside I don't like to set multiple variables of .env for basically the same thing. So my question is how can I format my ALLOWED_HOSTS to be compatible with my settings.py. Something like this does not seem to work it seems: ALLOWED_HOSTS = os.environ.get('SERVERNAMES').split(',') Thanks and kind regards -
How to save three related models in one DRF endpoint?
I have 4 related models and I need to implement the functionality to consistently create instances of these models in a database in one post query. For this I use override of the APIView class post method. models class VendorContacts(models.Model): contact_id = models.AutoField(primary_key=True) vendor = models.ForeignKey('Vendors', on_delete=models.CASCADE) contact_name = models.CharField(max_length=45, blank=True) phone = models.CharField(max_length=45, blank=True) email = models.CharField(max_length=80, blank=True, unique=True) class Meta: db_table = 'vendor_contacts' class VendorModuleNames(models.Model): vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE, primary_key=True) module = models.ForeignKey(Modules, models.DO_NOTHING) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'vendor_module_names' unique_together = (('vendor', 'module'),) class Vendors(models.Model): COUNTRY_CHOICES = tuple(COUNTRIES) vendorid = models.AutoField(primary_key=True) vendor_name = models.CharField(max_length=45, unique=True) country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) nda = models.DateField(blank=True, null=True) user_id = models.ForeignKey('c_users.CustomUser', on_delete=models.PROTECT) timestamp = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'vendors' unique_together = (('vendorid', 'timestamp'),) class Modules(models.Model): MODULES_NAME =tuple(MODULES) mid = models.AutoField(primary_key=True) module_name = models.CharField(max_length=50, choices=MODULES_NAME) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'modules' unique_together = (('mid', 'timestamp'),) serializer.py class VendorsSerializer(serializers.ModelSerializer): class Meta: model = Vendors fields = ('vendor_name', 'country', 'nda',) class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( 'contact_name', 'phone', 'email',) class VendorModulSerializer(serializers.ModelSerializer): class Meta: model = VendorModuleNames fields = ('module',) class ModulesSerializer(serializers.ModelSerializer): class Meta: model = Modules fields = ('module_name', ) views.py class VendorsCreateView(APIView): … -
Increase number of supported request by django on dev
I have a doc project where I have to test a massive ammount of urls and links. To do that I was using python 2 linkchecker. I upgraded to django 2.2 and python 3.6 and I am using a go binary called muffet (https://github.com/raviqqe/muffet). linkchecker was gentle with the server, muffet on the other hand is more brutal (even with timeout options and other settings). The problem I have is after some time, the requests timeout and the django local server crashes. I heard about somme kind of queue or cache for the local django server. Is anyone knows how to increase the django limit in order not to DDOS myself while I am running my tests before deployment (this tool is not running in production). Or any out of the box thinking to solve this. Just for you to know, I run the server in background, and call the tool on the localhost url. (from another terminal) Thanks -
django is installed but still django-admin.py command not found
i was running this command PYTHONPATH=/opt/graphite/webapp django-admin.py migrate --settings=graphite.settings but it is showing this error: -sh: django-admin.py: command not found django directory is present in /usr/local/bin.what can be the reasons? -
Django How to create tables in views.py and display it to the Html
Good day guys, I am new here please good to me :) I hope the title is enough to understand what the problem is, I want to create a table in my views.py and display it to my html, I have this code in my views.py students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter(Grading_Categories__in=cate.values_list('id')).filter(GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records', 'Grading_Categories', 'Grade').distinct() teachera = studentsEnrolledSubjectsGrade.objects.filter(id__in=students.values_list('id')) teacherStudents = StudentsEnrolledSubject.objects.filter( id__in=students.values_list('Students_Enrollment_Records')) Categories = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = students.values_list('id')).order_by('Grading_Categories') table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header_Period = ['Period'] table_header.extend(Categories) table.append(table_header) for student in students: if not student['Students_Enrollment_Records'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = student['Grade'] table.append(table_row) This is my Models.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) @property def dates(self): # you have Year-month-day dates from the form return [datetime.strptime(date, '%Y-%m-%d') for date in self._dates] @dates.setter def dates(self, … -
Django Model data in views as variable
Need help, Very new to Django. I have created a model as below class Redirect_url(models.Model): hosturl = models.CharField(max_length=100) path = models.CharField(max_length=100) redirectpage = models.CharField(max_length=200) I need the hosturl, path and redirectpage as a variable in my views page for me to make some logic before I render to the html page. I don’t know from django.shortcuts import render,redirect from django.http import HttpResponseRedirect from django.http import HttpResponse from .import models def home(request): return render(request,'home.html') def redurl(request): b = request data = (models.Redirect_url.objects.all()) print(data) return HttpResponse(data, content_type="text/plain") I am getting print as Redirect_url object (1)Redirect_url object (2). How to get all the models data. Thanks. -
eval() in python crashing the server
From the UI, I am currently getting a list of strings to my python function in the back-end via ajax as shown below in ans variable. ans = ["Address().address()", "Address().number()", "Address().city()", "Address().continent()"] Address is the class name and address, number and city are its methods I am using eval() to evaluate each of the strings in a for loop of 1000 which means 1000 such lists with evaluated strings will be stored in a final list. but when i loop for 1000, the server crashes due to this. Also, when i loop till 50, its runs fine...but gets crazy for large number of input number. are there any alternatives for eval()? Please suggest. -
How can I prevent losing cookies in a Django app, upon a callback done by 3rd party API?
I am trying to integrate Spotify login for a logged/registered user of my Django app. I am facing issues with preventing losing the session id (stored in cookies). The session id is lost when the api requests the callback uri. The flow so far is: Django/Website View: Login the user (using Django's authentication system; this sets the session id cookie in the browser) Django/Website View: User chooses to connect Spotify account (redirected to Spotify's login screen) Spotify View: User logs in and grants permissions Django/Website View: Spotify redirects to my application (redirect uri is set in the API dashboard; the browser is now missing the session id cookie) After the redirect, Django logs my user out of the app. I have noticed the reason to be a loss of cookies namely, session id and csrftoken. I need to preserve the session id cookie in order prevent the logging the user out. Is there anyway I can prevent the loss of session id after the redirect takes place? -
How to metronic theme integration in django?
I have metronic theme how i am run metronic theme with django or integrate the theme i want to create front-end with metronic theme and back-end using django. how can i do this. -
How to properly add the checked users in a certain group?
views I have a checkbox to check the users in order to add them in a group.Here If the checked user is already in the group then it fails now with this code but I want proceed(if checked users are already in) and add the remaining user to the group and leave the already added user as it is. It throws this error if the checked users are in the group already UNIQUE constraint failed: user_registration_user_groups.user_id, user_registration_user_groups.group_id def assign_users_to_group(request, pk): group = get_object_or_404(Group, pk=pk) if request.method == 'POST': users = request.POST.getlist('users') for user in users: if user in group.user_set.all(): pass group.user_set.add(user) messages.success(request, 'users added to this group') return redirect('user_groups:view_group_detail', group.pk) -
Django model query with not equal exclusion
I would like to create query that has a not equal parameter, but in exclusion part. All posts suggest to exclude the parameters that should be not equal. So what I need is : Object.objects.filter(param1=p).exclude(param2=False, param3=False, param4 != q) I try Object.objects.filter(param1=p).exclude(param2=False, param3=False).exclude(param4=q) but, as expected, doesn't work it is the same as exclude(param2=False, param3=False, param4=q) So how to do it, or how to rightly chain exclude statements, so that second exclude is pointed to first exclude and not first filter. -
How to use javascript string as variable name in django html template?
I have a django view that passes a multiple of values to my html page. based on some client side process, I want to process one of those values. consider the example: views.py return render(request,'output.html',{ 'k1'=x, 'k2'=y, 'k3'=z, } output.html: <script> var temp; if( ....... ){ temp='k1'; } else if ( ...... ){ temp='k2'; } else{ temp='k3'; } now i want to access value in variable whose name is stored in temp, to perform some jquery operations. So i need the value stored in a javascript variable. Note: the given is just a small example, i am actually using a loop of about 60 iterations, i.e. k1 to k60. -
How to store user created through signup page to google cloud mysql database thorugh python3 django?
Can anyone provide me a link or guidance on how to proceed to store the users created through signup page using django's auth libs to google cloud sql? I am unable to store the data as well as retrieve it in order for the person to login into the website. -
How to add columns through django admin panel
I have a table named tableA with columns "name" and "age" built using model.py. Now I wanted to add another column like "gender" but this time not by changing model.py but directly through admin panel. I know that admin panel allows to add values to the existing table but i wanted to add a feature where we can add columns too through the admin panel and not by hardcoding in model.py So is it possible? -
Unable to migrate changes from Django to Oracle database
I am unable to migrate changes in Oracle version 6 database. After creating the model and write: python manage.py makemigrations python manage.py migrate I get: django.db.utils.DatabaseError: ORA-02000: missing ALWAYS keyword -
Radio buttons not validating with done() method in django form?
I'm having issues getting my forms to submit radio button selection. The forms work fine, but I keep getting a Your SessionWizardView class has not defined a done() method, which is required. error. My code is shown below: forms.py from django import forms class PresidentForm(forms.Form): CHOICES=[('choice 1', "Choice 1"), ('choice 2', "Choice 2"), ('choice 3', "Choice 3"), ('choice 4', "Choice 4"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="U.S President / Vice President") class SenatorForm(forms.Form): CHOICES=[('choice 1', "Choice 1"), ('choice 2', "Choice 2"), ('choice 3', "Choice 3"), ('choice 4', "Choice 4"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="U.S Senator") class RepresentativeForm(forms.Form): CHOICES=[('choice 1', "Choice 1"), ('choice 2', "Choice 2"), ('choice 3', "Choice 3"), ('choice 4', "Choice 4"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="U.S Representative") class PropositionForm(forms.Form): CHOICES=[('yes', "Yes"), ('no', "No"), ] ballot = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect, label="Proposition 123") views.py Note: I have 2 done() methods, one of which is commented out. This is a result of me experimenting and the final product will only have 1 done() method from django.http import HttpResponseRedirect from .forms import PresidentForm, SenatorForm, RepresentativeForm, PropositionForm from formtools.wizard.views import SessionWizardView class FormWizardView(SessionWizardView): template_name = "templates/form.html" form_list = [PresidentForm, SenatorForm, RepresentativeForm, PropositionForm] # def done(self, form_list, **kwargs): # return render(self.request, 'done.html', { … -
Django: The UI throws a "This field is required" error after uploading a file
My template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> </form> My view: def create_batch(request): form = BatchForm(request.POST or None, request=request) if form.is_valid(): form.save_batch(request=request, create_batch_flag=True) return redirect('list_batch_url') return render(request, template_name, {'form': form}) My form: class BatchForm(ModelForm): csv_file = FileField(label='CSV File') class Meta: model = Batch fields = ('project', 'name', 'csv_file', 'filename') def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(BatchForm, self).__init__(*args, **kwargs) #limit to projects created by the logged in user self.fields['project'].queryset = Project.all_created_by(self.request.user) def clean(self): cleaned_data = super().clean() csv_file = cleaned_data.get("csv_file", False) The clean method does not pick up "csv_file" and the UI throws a "This field is required" on the CSV FILE input button. I cant seem to get what im doing wrong here. Can you please help. Thanks -
How to switch design for each cards in django templates
How to switch between different card designs for each data in the for loop. <div class="col-1-of-3"> <div class="card"> ... </div> </div> <div class="col-1-of-3"> <div class="card"> ... </div> </div> <div class="col-1-of-3"> <div class="card"> ... </div> </div> These three cards have different designs, Currently facing trouble in switching these cards for each loop in the Django template. {% for cont in data %} {% ifequal forloop.counter|divisibleby:"3" True %} <div class="col-1-of-3"> <div class="card"> ... </div> </div> {% endifequal %} {% ifequal forloop.counter|divisibleby:"2" True %} <div class="col-1-of-3"> <div class="card"> ... </div> </div> {% endifequal %} {% ifnotequal forloop.counter|divisibleby:"2" True %} <div class="col-1-of-3"> <div class="card"> ... </div> </div> {% endifnotequal %} {% endfor %} Third card logic is wrong. I need to change this logic so that for each loop each cards need to be displayed alternatively. And another challenge is that after 3 loop it should close the section, since in a row only 3 cards are allowed. <section class="section-tours" id="section-tours"> {% ifequal forloop.counter|divisibleby:"3" True %} {% endifequal %} {% ifequal forloop.counter|divisibleby:"2" True %} {% endifequal %} {% ifequal forloop.counter|divisibleby:"2" True %} {% endifequal %} </section> -
Is it recommended to Install and configure UFW for a new Django project?
I'm deploying a new project on Google Cloud Platform using Django certified by Bitnami that comes with pre-installed Debian 9, Apache, MySQL, Python. My end goal is to build a web application, but nothing is close to production yet and I'm still running on an ephemeral external IP address assigned to the VM instance. So my question is that is it recommended that install an ufw (Uncomplicated Firewall) ? -
Django channels: Alternative of Redis for windows machine?
As per documentation of redis, A.3.1 Drawbacks of Redis on Windows Windows doesn’t support the fork system call, which Redis uses in a variety of situations to dump its database to disk. Without the ability to fork, Redis is unable to perform some of its necessary database-saving methods without blocking clients until the dump has completed. Questions: 1) If I'm not wrong, this issue will occur when concurrent users increases? Is that correct? 2) Is it really a issue, if we deploy channels on windows machine(production server)? If yes, is there any better alternative of redis? Note: Can't use wsl2(as officially not released) or wsl as current windows server won't support. -
Django OSMGeoAdmin Cross Origin Issue
It's basically this question: cross origin access issues - django 2.1.7 But it's still not correctly answered. Is this still a JS thing? Or are we missing something? The original question: I have gone through literally all SO links, reinstalled django and django-cors-headers and followed this to the T and yet we get pre flight error cross origin not allowed Django version 2.1.7 relevant sections of settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'uploads.core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True Even with corsheader middlewear at the top, same error code arrives. [Error] Cross-origin redirection to https://a.tile.openstreetmap.org/14/4684/6268.png denied by Cross-Origin Resource Sharing policy: Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. [Error] Cannot load image http://a.tile.openstreetmap.org/14/4684/6268.png due to access control checks.