Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect from one question to another having same forignkey (quiz name)
I m building quiz app I have 3 models ( Quiz, Question,Answers) Question foreign key with Quiz,and Answee foreign key with Questions. I m successful in showing each question on separate page according to their pk. But to redirect from one question to another until last question -
making duplicate entries without ids using django
I'm making a django dashboard where the users can upload their experience certificates. The problem is the certification section sends duplicate entries to the django view with empty ids and the logic in the views make duplicate entries in thedatabase. The problem I found that the form is sending duplicate entris without the ids. certificate.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for c in cert %} <div class="form-body"> <div class="row"> <div class="col-md-12"> <div data-role="dynamic-fields"> <div class="form-content"> <input type="text" name="id" value="{{c.id}}"> <div class = "row"> <div class="col-md-6"> <div class="form-group"> <label>Month</label> <input type="text" class="form-control" id="field-value" name = "month" value = "{{c.month}}"> </div> </div> <div class="col-md-6"> <div class="form-group"> <label>Year</label> <input type="text" class="form-control" id="field-value" name = "year" value = "{{c.year}}"> </div> </div> </div> <div class="col-md-12"> <div class="form-group"> <label>Company</label> <select class="form-control" id="field-value" name = "company"> {% if c.company %} <option value = "{{c.company}}">{{c.company}}</option> {% endif %} <option value="Microsoft">Microsoft</option> <option value="TEDx">TEDx</option> <option value="Business Standard">Business Standard</option> <option value="EF Standard English Test">EF Standard English Test</option> <option value="Open2Study">Open2Study</option> <option value="eMarketing Institute">eMarketing Institute</option> <option value="Amazon">Amazon</option> <option value="Airbnb">Airbnb</option> <option value="Adobe">Adobe</option> <option value="Paypal">Paypal</option> <option value="Intel">Intel</option> <option value="eBay">eBay</option> <option value="Beats">Beats</option> </select> </div> </div> <div class="col-md-12"> <div class="form-group"> <label>Title</label> <input type="text" class="form-control" id="field-value" name = "title" value="{{c.title}}"> </div> </div> <div class="col-md-12"> <div class="form-group"> … -
While running on Server i am getting HTML code on my browser
When i am running my Django project on local server. It is returning whole html code on webpage. Like after executing command python manage.py runserver and copy and pasting url on browser i am getting whole HTML file code instead element i have used. My Html file {% extends "wfhApp/base.html" %} {% block body_block %} <div class="jumbotron"> {% if registered %} <h1>Thank you for registration</h1> {% else %} <h1>Register here!</h1> <h3>Fill out the form:</h3> <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ user_form.as_p }} <input type="submit" name="" value="Register"> </form> {% endif %} </div> {% endblock %} My views.py from django.shortcuts import render from wfhApp.forms import UserForm def register(request): registered = False if request.method == 'POST': user_form = UserForm(data = request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm return render(request, 'wfhApp/registration.html', {'user_form': user_form}, {'registered': registered}) Above is from template inheritance. -
Invalid HTTP_HOST header: '0.0.0.0:8000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS
Django does not seem to find my host 0.0.0.0 I have already added "0.0.0.0" to my ALLOWED_HOSTS. In fact, if I print(ALLOWED_HOSTS) I get ['localhost', '127.0.0.1', '0.0.0.0', '[::1]']. I am working in docker. Is there anything I am overlooking? .env.dev DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 0.0.0.0 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=xxxx SQL_USER=xxxx SQL_PASSWORD=xxxx SQL_HOST=db SQL_PORT=5432 DATABASE=postgres env_settings.py import os # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! # DEBUG = True DEBUG = int(os.environ.get("DEBUG", default=0)) ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ") # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) settings.py from core.env_settings import * print(ALLOWED_HOSTS) """ print(ALLOWED_HOSTS) returns ['localhost', '127.0.0.1', '0.0.0.0', '[::1]'] """ NB: I have carefully reviewed all similar questions posted here and there's none with this specific problem. -
access media root in server from local django
How could I make media root to access path in server when I work local Django ? path I want to access in sever: /var/test/ this is my local media root and media url: MEDIA_ROOT = '/home/test/' MEDIA_URL = '/media/' -
Accept customized input and customized output using Django Rest Framework
I am getting this part input and output successfully & documentation is also available for this type of problems input { "someid:"1" "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899" } output posting--> { "id:1, "someid" :1 "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899", } but my data is not coming like above format and i need to get post response not like above , i am expecting this input and { "someid:"1" "lectures": [{ "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899" }] } output { "lectures": [{ "id:1, "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "1534567899", "someid" :1 }] } I have succeeded in getting the listing of data by overriding def list this function serializers--> class LecturesSerializer(serializers.ModelSerializer): schedule_timestamp=serializers.IntegerField() class Meta: model=Lectures fields = ('id','lecture_id','schedule_timestamp','subject_name','teacher_id','teacher_name','room') def validate(self, attrs): travel_date = Lectures.to_date_time(attrs.pop('schedule_timestamp')) attrs.update({'schedule_date': travel_date}) attrs = super().validate(attrs) return attrs def to_representation(self, instance): data = super(LecturesSerializer, self).to_representation(instance) result_data={} result_data["lectures"]=data return result_data views--> class LecturesViewSet(viewsets.ModelViewSet): queryset = Lectures.objects.all() def get_serializer_class(self): return LecturesSerializer def list(self, request, *args, **kwargs): self.object_list = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(self.object_list, many=True) return Response({'lectures': … -
Getting AttributeError for body tag in Json parsing Python
Getting this error when parsing data AttributeError: 'str' object has no attribute 'body' Generating data json like this data = { 'params': { 'content': { 'mail': self.email_address } } } And parsing that data like this param = json.loads(request.body) content = param['params']['content'] mail = content['mail'] How to create Data properly which I can get in response.body? -
save serial number generated after form submission and displayed in django database?
I have created the model as class Personal_Detail(models.Model): message=models.CharField(max_length=100,blank=True, null=True) def __str__(self): return self.beneficiary_aadhaar_name and views as from django.contrib import messages import datetime import random @login_required def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) beneficiary_adhaar_name=request.POST.get('beneficiary_adhaar_name') apply_online = Personal_Detail(beneficiary_adhaar_name=beneficiary_adhaar_name) apply_online.save() return render(request,'users/applyonline.html') I don't know how can i do the same for messages so that the displayed serial number after form submission will also get saved in the database.(for messages.success i don't know how to proceed like other cases) -
Django form for entering user id and product id
So, There's a button on my products results page. It's function is supposed to put the user id(request.user.id) and product id(request.product.id) (which is in the html) into a junction table between users and product tables. I've tried the code below. I'm not getting any errors but it doesn't save to the database. I don't want it to redirect to other page so the target is an iframe models.py class UserProductTracking(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: verbose_name_plural = "Trackings" def __str__(self): return str(self.product) forms.py class TrackingForm(forms.ModelForm): class Meta: model = UserProductTracking widgets = {'any_field': HiddenInput(),} exclude = {'id'} views.py def result(request): form = TrackingForm(request.POST) if request.method == "GET": rawquery = request.GET.get('q') #gets the product name to search from a form Product_set = Product.objects.filter(name__icontains=rawquery).distinct() #get all products with name ccontainingthe search term 'q' products = [] # create a blank set for product in Product_set: # for every item in Product_set price = Scan.objects.filter(product=product.id).first() # get price price_max = Scan.objects.filter(product=product.id).aggregate(Max('price')) price_min = Scan.objects.filter(product=product.id).aggregate(Min('price')) products.append({ #append adds to an existing list 'name': product.name, #context name = name column in product table 'store_name': product.store_name, # '' 'image_link': product.image_link, 'id': product.id, 'price': price.price, #'' 'price_max': … -
How to display no record using ListView in Django?
I'm using ListView to display objects of model but i want when there is no object in model so I display No records or products. What I need to do write a new function for it or there is any built-in function in ListView for this purpose. views.py class StockView(ListView): template_name = 'stock/stock.html' model = Product paginate_by = 3 -
Django ValueError for deleted fields when running migrations
My models.py file is as follows: from django.db import models from django.utils import timezone from random import randint # Create your models here. class File(models.Model): fileName = models.CharField(max_length = 30) description = models.CharField(max_length = 100) dateUploaded = models.DateTimeField(default = timezone.now) doc = models.FileField(default = None) serial = models.CharField(max_length = 6, default = randint(100000000, 999999999), unique = True) id = models.AutoField(primary_key=True) I used to have code = models.CharField(default = 'A13S34', max_length = 6, unique = True but it kept giving the error ValueError: Field 'code' expected a number but got '236E96'. Thus, I replaced it with the serial field. However, now when I try to makemigrations and migrate, I get the same error ValueError: Field 'code' expected a number but got '236E96'. What can I do when I no longer even have the code field? -
Action attribute in html form tag is not sending the data in django
I want to send song.id from each song in an album model but every time I send it, I get A KeyError This is what I wrote in details.html {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ song.id }}" name="song" value="{{ song.id }}"> <label for="song{{ song.id }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="https://png.pngtree.com/png-vector/20190726/ourmid/pngtree-cute-light-star-with-black-frame-png-image_1633374.jpg"> {% endif %} </label> <br> {% endfor %} <input type="submit" value="Favorite"> </form> This is my views.py def favorite(request, album_id): album = get_object_or_404(Album, pk=album_id) try: selected_song = album.song_set.get(pk=request.POST['song']) except (KeyError, Song.DoesNotExist): return render(request, 'music/detail.html', { 'album':album, 'error_message':"You did not select a valid song", }) else: selected_song.is_favorite = True selected_song.save() return render(request, 'music/detail.html', {'album':album}) -
Filter users in form
I have a form for multi select drop-down. I want to use filter user=request.user in forms. class AssignPlanToUserForm(forms.Form): user_options = forms.ModelMultipleChoiceField(Company.objects.all(), widget=forms.SelectMultiple(attrs={'class': 'form-control name-option name-control'}), required=True) I want to add filter user=request.user in this field. Can anyone help or suggest anything. -
Hide some part of code in views DJANGO before send to GIT
Is is possible to hide some part of code in views before I send it to git or it is impossible? I have one issue and it would be the easiest way to solve it, i am trying to use .env file but unfortuntely does not work as it should. My problem TWILIO API ERROR Credentials are required to create a TwilioClient django so i have code which works in views, but not with using env file. -
Minimum mobile resolution in present date
What should me the minimum screen width a web developer should design his/her website in present date.It is 320px or 360px or even higher. -
ValueError: Field 'X' expected a number but got 'X'
So I was working on some fields in my models.py and ran a python3 manage.py makemigrations and python3 manage.py migrate. A few minutes later I decided to get rid of one of the fields, and replace it with something else - however, everytime I try to migrate and makemigrations, the error that Field 'X' (which is deleted) expected a number but got 'X'. Anyway around this considering my field is deleted? The exact error is: ValueError: Field 'randkey' expected a number but got '1AB2CD'. -
SMTPRecipientsRefused at /accounts/signup/ django-allauth
When I'm using django all-auth i'm facing error somethings like this. {'test@gmail.com': (553, b'5.7.1 : Sender address rejected: not owned by user .... enter image description here With out django allauth it is working fine. Here is my configurations 1 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.domain_naame.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'sandeep@domain_name.com' EMAIL_HOST_PASSWORD = 'account_password' -
Routing URLs between Django and Angular
I'm currently creating a website in Django and Angular. Django is serving the Angular build files. Excluding /api calls, all URLs are returned a template that loads the Angular index. This part works. The part I'm having trouble with is when I try to lazy-load modules. Angular will try to find a module foo at localhost:8000/foo-module.js, but it's really at localhost:8000/static/mydjangoapp/angular/foo-module.js. I know I could solve this problem by setting <base href="/" /> in index.html to <base href="/static/mydjangoapp/angular" />, but I want the frontend to be served from /. I could also avoid lazy-loading modules, but I feel like there's a better way to serve Angular from Django using which I can lazy-load. How can I get Angular to properly fetch the URLs? I'm also having a similar issue with serving Angular assets. -
django send response to website without changing it
This is what the form looks like right now This piece of code gets the input and has a rough IF statement that confirms if the confirm pasword input == password input, if not it redirects you and sends an http response that passwords do not match, now instead of an http response what i want to do is send a message without changing the website that confirm password == password like a little message that says passwords do not match while you type or after you press submit. views.py def get_data(request): username = request.POST.get('username', None) email = request.POST.get('email', None) password = request.POST.get('password', None) confirm_password = request.POST.get('confirmpassword', None) try: #validate the email validate_email(email) if confirm_password == password: # confirm password a = Account() a.username = username a.email = email a.password = password a.save() return HttpResponse('User %s has been registered. ' %(username)) else: return HttpResponse('<h1>Passwords do not match</h1>') except: return HttpResponse('<h1>%s is not a valid e-mail id.</h1>' %(email)) models.py from django.db import models from django import forms # Create your models here. class Account(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=64) password = models.CharField(max_length=16) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('get-data', views.get_data, name='get-data'), … -
Django key, value dictionary returning data under the same key
I'm pulling post data from my firebase database and trying to pass it into my template in Django. I can easily pass just the values into the template but I'm trying to also pass the ID using a key-value dictionary but for some reason, I can't get it to work the way I want it to. It's returning all the values under the same key I would like each key to match the relating value. Database structure: "posts" : { "-LqytRym_35j-6il-nHQ" : { "title" : "Purple", "uid" : "LTAeaDscQyexbud3ijIMYpDCucO2" }, Views.py: posts = database.child("posts").child(favKey).get() posts_dict.append(posts.val()) at1 = {posts.query_key:[posts.val()]} print(at1) return render(request, 'users/favourites.html', {'posts': at1}) Template: {% for key, value in posts.items %} <article class="media content-section col-md-9 ml-sm-auto col-lg-10 px-4"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ key }}</a> <small class="text-muted"></small> </div> <h2><a class="article-title" href="#">{{ value.title }}</a></h2> <p class="article-content">{{ post.uid }}</p> </div> </article> {% endfor %} -
Update a single object from a database - Django/Python
So I am trying to allow users to edit menu item prices that are in the database currently. The fields will auto-populate data into the page and users will be able to edit that data to change the price. Here is what I have. I have tried and asked many questions, but I am still lost. I have googled a lot and it helped me understand forms a bit, but I'm not able to fix it. Please let me know if you need more info. Views.py: def edit_menu(request): queryset = Product.objects.all() context = { "object_list": queryset } if request.method == 'POST': post=ProductModelForm(request.POST) if request.POST.get('price') and request.POST.get('name'): if 'name' == Product.name: post.name= request.POST.get('name') post.price= request.POST.get('price') post.save() return redirect('Edit Menu Item') else: return redirect('Edit Menu Item') else: return render(request, 'mis446/edit-menu-item.html', context) else: return render(request, 'mis446/edit-menu-item.html', context) forms.py: class ProductModelForm(forms.ModelForm): class Meta: model = Product fields = ['name','price'] # specify which field you need to be in the form HTML: <title>ACRMS - Edit Menu Price</title> <div class = "container"> <form action = "" method = 'POST'> {% csrf_token %} {% for instance in object_list %} <input name = "name" value = "{{ instance.name }}"></input> <input type="number" name="price" value = "{{ instance.price }}"/><br> {% … -
how to correctly import urls.py from app?
This is probably pretty simple but I can't get my head around it. I'm learning Django, have v3.0.4 installed and can't get the URLs from an app to work correctly. On the project urls.py I have the following: Project\urls.py: from django.contrib import admin from django.urls import path from django.urls import include from AppTwo import views urlpatterns = [ path('', views.index, name='index'), path('', include('AppTwo.urls')), path('admin/', admin.site.urls), ] I've created an app named "AppTwo" and have the following urls.py and views.py in the app: AppTwo\urls.py: from django.urls import path from . import views urlpatterns = [ path('/help', views.help, name='help'), ] AppTwo\views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("<em>My Second App</em>") def help(request): return HttpResponse("<em>Help Page!!!</em>") If I browse to http://127.0.0.1:8000/ the index page loads and I see the text "My Second App" as expected. However if I browse to http://127.0.0.1:8000/help I get page not found 404 error. I can also browse to the admin page just fine. So far this is a stock project, the only other change I made after creating it was to the settings.py file to install the "AppTwo" application. Based on the documentation, this looks like it should … -
django cannot get static css to work in template base.html
I am trying to setup a site wide css file. My css will render if I place it directly in my block content cat register/templates/register/register.html {% extends "base.html" %} {% block title %}Create an Account{% endblock %} {% load crispy_forms_tags %} {% block content %} <style> .registration_base { padding-top: 50px; margin: auto; width: 30%; } </style> <div class="registration_base"> <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} </div> and it will function fine but I would like the code called from a style.css file site wide, in my base.html file. I cannot get the css file to actually render. In my templates/base.html I have <head> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}style.css"> </head> in my register/static/style.css I have the same css code: .registration_base { padding-top: 50px; margin: auto; width: 30%; } I can run #python3 manage.py findstatic style.css Found 'style.css' here: /home/user/www/src/register/static/style.css and it finds it, but my css formatting never changes. I have the app installed in site/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', 'register.apps.RegisterConfig', 'crispy_forms', ] How do I get a site wide css file properly included? -
how to detect url IP change in django
I am trying to detect the change in IP address for my website. If website IP address is changed, then redirect the page to login screen with new ip address. Detailed problem statement explanation given below Lets say website URL assigned to IP address 192.168.0.15 Login to the website and navigate to any page or just remain on the home page Change the website IP address to 192.168.0.12 (or something different from step 1) Select a link to a different page in already opened screen (in step 2) Confirm the Login screen is displayed. Could you please help me how this can be achieved in Django. -
django rest api not creating user
halo i'm working on a django rest_framework api code for user signup, but when i test the code with postman, they user doesn't get registered and it doesn't return any particular error, hoping anyone can help out, below is my models, serializers and views codes..... models class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=100) created = models.DateField(auto_now=True) timestamp = models.DateTimeField(auto_now=True) role = models.CharField(max_length=5) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email class Meta: ordering = ('email',) objects = CustomManager() views @api_view(['POST', ]) def registration(request): if request.method =='POST': serializer = RegisterUserSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() data['response'] = 'registration successful' data['email'] = user.email else: data = serializer.errors return Response(data) Serializers class RegisterUserSerializer(serializers.HyperlinkedModelSerializer): confirm_password = serializers.CharField(style= {'input_type': 'password'}, write_only=True) class Meta: model = CustomUser fields = ['id', 'email', 'password', 'confirm_password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def save(self): user = CustomUser( email = self.validated_data['email'], ) password = self.validated_data['password'] confirm_password = self.validated_data['confirm_password'] if password != confirm_password: raise serializers.ValidationError({'password: Password didn\' match'}) user.set_password(password) user.save() return user