Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django vs php laravel
I'm a python Django back end developer, applied for a job as back end and they asked me to implement a minimal double-entry accounting system via PHP Laravel, I have not worked on PHP Laravel at all, and have 5 days to accomplish the task, should I dedicate the next 5 days to learn and accomplish the task or it won't be easy mission given that I'm not familiar with the language and the framework. Will my understanding of Django easier the process of learning? Please your input will really help me decide, I'm overthinking it alot. -
Django TypeError : expected str, bytes or os.PathLike object, not list || When adding new object
When I'm in the admin panel and I add this object called Cover I am getting this error. I have the same image, text, and char field in other models without any issue does anybody have a good idea of what is happening? TypeError : expected str, bytes or os.PathLike object, not list https://ibb.co/XzDwsXd But I don't have a list anywhere! Please help! models.py class Cover(models.Model): cover_image = models.ImageField(upload_to="images/", blank=True, null=True) cover_title = models.CharField(max_length=64, null=True) text = models.TextField(max_length=256, null=True) views.py def index(request): if request.method == 'POST': is_private = request.POST.get('is_private', False) message_email = request.POST['message_email'] send_mail( 'New Midas&Co litter and newsletter request from '+ message_email, # subject message_email + ' requests to be notified about upcoming litters.', # message 'Midas & Co Website', # from Email ['midasandcompany22@gmail.com', 'webmasterzzzbot@gmail.com'], # to email ) return render(request, "cattery/index.html", {'message_email': message_email, 'cover':cover}) return render(request, "cattery/index.html") admin.py from django.contrib import admin from .models import Cat, Stud, Queen, Cover admin.site.register(Cat) admin.site.register(Stud) admin.site.register(Queen) admin.site.register(Cover) -
Django TypeError at /admin/login in the admin AppConfig.__init__() missing 1 required positional argument: 'app_module'
I am not able to go to the admin site when I type /admin. With startproject this page should work as far as I know and I cannot find out what is the problem. -
how to make my django api publicily accessible?
I deployed it in the ubuntu server, it is running on localhost port 8000? I tried doing port 80 redirecting to 8000 using IP tables but its not helping -
Restricting user sending one form again and again?
I want to know how to restrict a user that he can't send form again and again, if it submitted already by him. The main goal is like, if I have a form like daily quiz that asks "What is the capital city of Italy?", a user should see it and send an answer once. And restrict a user to send an answer until the new question is active, like "What is the capital city of Germany". Are there any good approach? -
Reliably navigate route history for "back" button Django 4.0.3
On each of my app views, there is a page header with breadcrumbs & a back button to return to the previous view. I'd like to be able to reliably track & navigate the user's routing history to make sure to always send them back to the same view they came from. HTTP_REFERER doesn't factor in the potential of nested views. If you were to navigate from Page A -> Page B - Page C & use the back button on Page C you'd be taken to Page B, and then the HTTP_REFERER would become PAGE_C which sends the user in an infinite loop rather than taking them to Page A on clicking back again. window.history.back() or window.history.go(-1) doesn't consider that someone might be linked directly to Page B in which the back button would then send them to whatever is the previous page in their browsing history throughout the life of that tab, not direct them to Page A. My thought was maybe a middleware could append each route to a list in request.session, however, at this point I'm unsure how I'd detect a back button click to move backwards through this. As well, with this solution, I'm worried … -
URL can't contain control characters
I am getting Url can't contain special character.{the whole url with mobile number and otp in it} (found at least ' ') errror. Please help ''' def send_otp(mobile , otp): print("FUNCTION CALLED") conn = http.client.HTTPSConnection("api.msg91.com") authkey = settings.AUTH_KEY headers = { 'content-type': "application/json" } url = "http://control.msg91.com/api/sendotp.php?otp="+otp+"&message="+"Your otp is "+otp +"&mobile="+mobile+"&authkey="+authkey+"&country=91" conn.request("GET", url , headers=headers) res = conn.getresponse() data = res.read() print(data) return None ''' -
How can I use for loop to find society name endswith city name or not?
I am trying to check each society's name that contains the city name at the end of the society name. This is the code that I writing in the cmd. for s in societies: ... s_name = societies.filter(name__iendswith=s.locality.city.name) ... print(s_name) I have tried the above code and I got these entries. All these societies' name contains city name at the end but problem is that as you see it prints the same entry again and again. <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object (636)>]> <QuerySet [<Society: Society object (213)>, <Society: Society object (239)>, <Society: Society object (629)>, <Society: Society object (634)>, <Society: Society object (635)>, <Society: Society object … -
Django form not showing validation error with in Templates
I am trying to build Registration page . I am writting custom validation for my registration form field . But the problem is form is not raising validation error . When i am writting form.is_valid() it is showing validated . I am new to django and learning new concepts . I am trying to figure out what is wrong here . Forms.py file code : from django import forms from django.core import validators def emptyField(value): if value == '': raise forms.ValidationError("Please fill all the fields .") def length(value): if len(value) > 20: raise forms.ValidationError("Username can contain atmost 20 characters .") class UserForm(forms.Form): username = forms.CharField(required=False,validators=[emptyField,length]) email = forms.EmailField(required=False,validators=[emptyField]) password = forms.CharField(required=False,validators=[emptyField]) rePassword = forms.CharField(required=False,validators=[emptyField]) views.py file code : from django.shortcuts import render,redirect from .forms import UserForm # Create your views here. def home(request): return render(request,"Users/home.html") def registrationPage(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): print("validated") else: form=UserForm() context = { "form": UserForm } return render(request,"Users/register.html",context) register.html file code : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title> REGISTRATION PAGE </title> </head> <body> <h1> REGISTRATION PAGE </h1> <form method="POST"> {% csrf_token %} {{ form.username }} {{ form.email }} {{ form.password }} {{ form.rePassword }} <input type="submit" … -
HTTPS Mixed content error with hosting React site and Django REST API
I am trying to host a website made with React and its API (Django REST) on the same Ubuntu machine. The React site is currently being hosted on a domain with HTTPS, while the API is hosted on a port on the machine with HTTP. I get the following error accessing the site: Mixed Content: The page at (site) was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint (api). This content should also be served over HTTPS. It still works if I enable insecure content for the site, but is there a way to serve both of them over HTTPS other than having the API on a separate domain? -
Is there a way to add all Django Models fields into a check list?
I would like to create a checklist form based on the models selected can I print out all of the models fields into a checklist for the user to select which field to create a table for? -
How could i use fieldsets in django template for Django 3.0
Here i am using python version 3.7.10 and Django 3.0 My fieldsets worked fine on python 2.7 and Django 1.8 Here is my forms.py class CampaignMainForm(forms.ModelForm): class Meta: model = Campaign exclude = ['campaign_create_send_id', 'list_id', 'name', 'subject', 'created_by', 'send_datetime', 'send_timezone'] fieldsets = [ ['group',{ 'fields': ['group'], 'legend': "Recipients", }], ['template',{ 'fields': ['stored_template'], 'legend': "Template", }], ['templatedata',{ 'fields': ['stored_template_data', 'stored_template_data_validated'], 'legend': "Template Content", }], ] Now in my template how i tried is {% for fieldset in form.fieldsets %} <fieldset{% if fieldset.name != "templatedata" %} class="accordion-group"{% endif %}> {% if fieldset.name != "templatedata" %} <legend><bull class="bull {% if fieldset.legend == "Recipients" %}{% if object.group != None %}label-color-0d0{% endif %}{% elif fieldset.legend == "Template" %}{% if object.stored_template != None %}label-color-0d0{% endif %}{% else %}label-color-0d0{% endif %}"></bull> <a href="#" class="collapse-title" data-toggle="collapse" data-target=".collapse-{{ fieldset.legend|slugify }}" data-parent="#main-accordian">{{ fieldset.legend }}</a> <small class="muted">{% if fieldset.legend == "Template" %}{% if object.stored_template != None %}{{ object.stored_template.name }}{% endif %}{% endif %}{% if fieldset.legend == "Recipients" %}{% if object.group != None %}{{ object.group }} ({{ email_valid_count }} emails){% endif %}{% endif %}</small> </legend> ..... ..... {% endfor %} But here my for loop is not working properly.Actually what i need is if fieldset.name != "templatedata" then it need to display … -
Django rest framework Heroku Application Error
-----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in Pipfile.lock -----> Requirements file has been changed, clearing cached dependencies cp: cannot stat '/tmp/build_eaebc38f/requirements.txt': No such file or directory -----> Installing python-3.10.2 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (86a10d)... Ignoring tzdata: markers 'sys_platform == "win32"' don't match your environment -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/tmp/build_eaebc38f/static' in the STATICFILES_DIRS setting does not exist. 161 static files copied to '/tmp/build_eaebc38f/staticfiles', 414 post-processed. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 98.7M -----> Launching... Released v11 https://vicsites.herokuapp.com/ deployed to Heroku This my heroku deployment log and its still showing application error Here's my Procfile web: gunicorn vicsite.wsgi --log-file - The errors I spot in the log stated above are: ?: (staticfiles.W004) The directory '/tmp/build_eaebc38f/static' in the STATICFILES_DIRS setting does not exist. 161 static files copied to '/tmp/build_eaebc38f/staticfiles', 414 post-processed. 'sys_platform == "win32" don't match your environment -
How to save a foreign key automatically in Django?
I'd like to save restaurantID(foreign key which refers to Restaurant_Account) in the Menu table. They need to have the same value. For example, if user 'A' in Restaurant_Account is logged in and fills the form to save data in the Menu table, user A's restaurantID should be saved in the Menu table automatically. How can I do this? Thanks in advance. Below is my code! class Restaurant_Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_restaurant = models.BooleanField(default=True) restaurantID = models.AutoField(primary_key=True) name = models.CharField(max_length=200) isActive = models.BooleanField(default=True) image = models.ImageField(upload_to='images/', blank=True) website = models.URLField(blank=True) country = models.CharField(max_length=50) def __str__(self): return self.user.username class Menu(models.Model): restaurantID = models.ForeignKey(Restaurant_Account, on_delete=models.CASCADE, default=None, null=True) item = models.CharField(max_length=100) itemImage = models.ImageField(upload_to='images/', blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField( max_length=20, choices=CHOICES) def __str__(self): return self.item Below is my views.py. def Add_Menu(request, restaurantID): display=Menu.objects.get(id=restaurantID) form = MenuForm if request.method=="POST": form = MenuForm(request.POST, request.FILES) if form.is_valid(): restaurant = form.save(commit=False) restaurant.restaurantID = Restaurant_Account.objects.get(restaurantID=restaurantID) restaurant.save() #form.save_m2m() messages.success(request, "Saved successfully!") return redirect('index') else: form=MenuForm() return render(request, 'restaurant/add_menu.html', {'form':form, 'display':display}) -
Create superuser error, TypeError: create_superuser() missing 1 required positional argument: 'name'
When i run createsuperuser command in terminal ..it prompts to enter email and then password .I didn't get the username field. After entering password it gives me TypeError: create_superuser() missing 1 required positional argument: 'name'. Here is my models.py from django.db import models from datetime import datetime class Realtor(models.Model): name = models.CharField(max_length=50) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') description = models.TextField(blank=True) phone = models.CharField(max_length=20) email = models.CharField(max_length=100) top_seller = models.BooleanField(default=False) date_hired = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name and this is the error : self.UserModel._default_manager.db_manager(database).create_superuser( TypeError: create_superuser() missing 1 required positional argument: 'name' Could anyone please guide me how to solve this issue? -
How to allow adding inline objects only if a BooleanField is checked in django admin?
Screenshot: django admin site inline model I want the 'Add another Step' button to be disabled/greyed out if 'Have Step' is not checked (see screenshot above). When 'Have Step' is checked, the 'Add another Step' button should be enabled and the user can add a step. Is there any easy way to do this? Thanks! The Step model is an inline for the Course model. A course can have 0 or more steps. My models.py: class Course(models.Model): title = models.CharField(null=False, max_length=50) short_description = models.TextField(max_length=100, null=False) external_resource = models.BooleanField(default=False, blank=True) external_resource_link = models.URLField(null=True, blank=True) have_step = models.BooleanField(default=False, blank=True) class Step(models.Model): title = models.CharField(max_length=100, null=False) step_description = models.TextField(max_length=150, null=False) course = models.ForeignKey(LearningGuide, on_delete=models.CASCADE) My admin.py: class StepInline(admin.StackedInline): model = Step extra = 0 # no empty step form is shown initially min_num = 0 # min number of steps per course = 0 class CourseAdmin(admin.ModelAdmin): inlines = [StepInline] list_display = ['title'] admin.site.register(Course, CourseAdmin) -
Django JsonResponse is returning escaped Unicode
I’m trying to get Django to return a JsonResponse, but strings containing Unicode characters are being turned into escape sequences. For example, when I try to create a response with this dictionary: { "Latn-x-macron": "amisk", "Latn": "amisk", "Cans": "ᐊᒥᐢᐠ" } cURL gets a response like this: { "Latn-x-macron": "amisk", "Latn": "amisk", "Cans": "\u140a\u14a5\u1422\u1420" } Is there any way to get Unicode to return normally? -
Why file extension validator is not working properly in django?
I am trying to add a file extension validator in the Filefield of my model. But when I am adding a different extension file through my serializer it's adding the extensions I didn't put in my validators.py Here is the code so far # validators.py def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] # [0] returns path+filename valid_extensions = ["png", "jpg", "jpeg", # for images "pdf", "doc", "docx", "txt", # for documents "mp3", "aac", "m4a", "mp4", "ogg"] # for audios if not ext.lower() in valid_extensions: raise ValidationError('Unsupported file extension.') #models.py class QuestionFile(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name='files', null=True, blank=True) FILE_TYPE = ( ('NONE', 'NONE'), ('IMAGE', 'IMAGE'), ('DOCUMENT', 'DOCUMENT'), ('AUDIO', 'AUDIO'), ) file_type = models.CharField( choices=FILE_TYPE, max_length=50, null=True, blank=True) file = models.FileField( 'files', upload_to=path_and_rename, max_length=500, null=True, blank=True, validators=[validate_file_extension]) def __str__(self): return str(self.question) and here is the output in my serializer for this model "id": .., "file": "<filepath>/c-f479b7453519484b827dbc0051bd9a64.html", "file_type": .., "question": .. As it's visible, though .html extension is not added in the validators.py still it's uploading. Did I make any mistakes in my code? I am unable to figure out that. If any other information is needed let me know, please. Thanks -
Static files not loading for deployed django rest framework
I have built and successfully deployed a django rest framework using gunicorn and nginx on Ubuntu 18.04. However, the static files are not being pulled up. Django web app without loaded static files Here is my nginx configuration: server { listen 80 default_server; listen [::]:80 default_server; server_name [my_server_domain_or_IP]; #root /var/www/html; location = /favicon.ico { access_log off; log_not_found off; } location = /static/ { root /home/ubuntu/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } And in my settings.py file: STATIC_URL = '/static/' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I have checked that DEBUG is set to False. I have also already run collectstatic and the static files are located in a folder called static in: /home/ubuntu/myprojectdir/static. Every change I tried to make in the nginx configuration, I restarted nginx with the following command: sudo systemctl restart nginx. I mainly followed this tutorial, the only difference is that I edited the default nginx configuration instead of creating a new one because it wasn't deploying my django application this way. I can't seem to figure out what's wrong and have been trying to solve it for days. Am I missing something here? -
Django Modelform user issues
I have a model form to list an item and I am trying to get the form to fill in the user id from the user that is submitting the form. Currently, the form is submitted successfully but it always uses the first user in the database's id for every item. models.py class Item(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) creator = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, default=2) item_name = models.CharField(max_length=40) price = models.DecimalField(max_digits = 6, decimal_places=2) description = models.CharField(max_length= 500) main_image = models.ImageField(upload_to=path_and_rename , max_length=255, null=True, blank=True) image_2 = models.ImageField(upload_to='items/', blank=True) image_3= models.ImageField(upload_to='items/', blank=True) image_4= models.ImageField(upload_to='items/', blank=True) image_5= models.ImageField(upload_to='items/', blank=True) quantity = models.IntegerField(default=1, validators=[ MaxValueValidator(100),MinValueValidator(1)]) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.item_name def get_absolute_url(self): return reverse("item_detail_view", args=[str(self.id)]) forms.py from django.forms import ModelForm, forms from .models import Item class List_Item_Form(ModelForm): forms.ModelChoiceField(queryset=Item.objects.filter(user=user)) class Meta: model = Item def __init__(self, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) views.py class AddListing( generic.CreateView): template_name = 'store/add_listing.html' fields = ('item_name','price','description','main_image','quantity') model = Item def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) -
oath2 (fusionauth) in Django-Rest-Framework and React
I am sure there is something I fundamentally do not understand about oath2. I am trying to make django-rest-framework and react work w/ fusionauth. In react I have a button that redirects to the fusionauth authentication page. Once a user successfully logs into fusionauth, it sends a code to a redirect URL on the django backend. That DRF view exchanges the code for an authentication token and some other other info like an ID. Using that ID, I can find a corresponding (local) django user and generate a JWT token (or whatever sort of authentication system I wind up using) for that user and return it as JSON. The bit I don't understand, is how do I pass that JSON back to the frontend? -
Gunicorn binding specifically to multi-endpoint websites running on different ports
I am using Gunicorn + NGINX to deploy a multi-endpoint Django REST application. The application runs with pipenv shell foreman start which runs 5 different websites on different ports on localhost. I am trying to deploy just a single one of these websites that runs on port 8000 using Gunicorn. However, I am facing some issues while binding shown down below. I am quite sure how to exactly bind this application using the following line: gunicorn --bind 0.0.0.0:8000 myproject.wsgi Here is the WSGI file that I am using: import os from django.core.wsgi import get_wsgi_application if not "DJANGO_SETTINGS_MODULE" in os.environ: raise Exception("DJANGO_SETTINGS_MODULE not set") os.environ.setdefault("PERFORM_TIME_CONSUMING_INITIALIZATIONS", "True") application = get_wsgi_application() And this is how the websites were exported: export default { website1: "http://localhost:8007", website2: "http://localhost:8000", website3: "http://localhost:8005", website4: "http://localhost:8010", website5: "http://localhost:8009", }; -
Limited some columm in queryset django
I tried many ways but all failed when trying to get some special columns in model my code: or I use defer test_detail=testimport.objects.defer("so_hd","noi_dung") or I use only test_detail=testimport.objects.only("so_hd","noi_dung") or even use filter and defer/only test_detail=testimport.objects.filters().def("so_hd","noi_dung") When I print print(test_detail.values("ten_kh")), there are still results Because there are some columns I rarely use, so I want to save memory and improve speed if dont get there columns Please help me -
In Django, how do I construct a serializer that captures data in a join table?
I'm using Python 3.9 and Django 3.2. I have a couple of models -- a Coop model, which has many Address models, linked through a join table (CoopAddressTags) class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) addresses = models.ManyToManyField(Address, through='CoopAddressTags') enabled = models.BooleanField(default=True, null=False) web_site = models.TextField() description = models.TextField(null=True) approved = models.BooleanField(default=False, null=True) self.save() class CoopAddressTags(models.Model): # Retain referencing coop & address, but set "is_public" relation to NULL coop = models.ForeignKey(Coop, on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) is_public = models.BooleanField(default=True, null=False) I would like to create a serializer that can parse data POSTed from a front end app taht would then save these relationships, class Coop(APIView): ... def post(self, request, format=None): serializer = CoopSerializer(data=request.data) if serializer.is_valid(): serializer.save() but I'm having trouble figuring out how to incorporate the join table part of the equation. Specifically I don't know how to capture the "is_public" field from the join table in the serializer and then save everything, since the join table needs both the Coop and Address models to exist. I have this class CoopSerializer(serializers.ModelSerializer): addresses = AddressSerializer(many=True) class Meta: model = Coop fields = '__all__' def to_representation(self, instance): rep = super().to_representation(instance) rep['addresses'] = AddressSerializer(instance.addresses.all(), many=True).data return rep def create(self, … -
How to use Django and python to create a resources webpage?
I am using Django and python to create a resources webpage. So far I have created my virtual environment and set up MySql with a database. I have also created an admin with a page and can add entries to the resources page via the admin page such as: id: 1 name: stack_overflow url:http://stackoverflow.com How do I create the webpage such that it displays and lets you manage these resources (add, remove, edit)? I'm comfortable with the URL routing but I don't know how to set my models in models.py to talk to my views.py and then use a html file as a template?