Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying queryset in django
I want the notes that is in my database to be displayed on the template. if(request.user): notes = Notes.objects.filter(user=request.user,url=costum_link) print(notes) print(costum_link) context.update( { "note" : notes } ) return render(request,'index/video.html' ,context) This is my template: <h2>Your Notes:</h2> {% for n in note %} <li>{{ n }}</li> {% endfor %} The template prints out Your Notes: ('This is the best note taking app I have seen on youtube\r\n',) (' I love it',) And this is not what I want it to print. I just want it to print the data. Can anyone please explain about this 'note' object and how to properly use it to solve my issue. -
I want to create a blog with the forum by using Python language. Please suggest me, which framework is best? 1. Django 2. Flask?
I want to create a blog with the forum by using Python language. Please suggest me, which framework is best? 1. Django 2. Flask? The nonsense person doesn't answer my question. I know Flask is the mini-framework which is not my question's answer. I want to know which framework is best to fulfill all the forum and blog requirements also best in the future use? Thanks -
django.utils.dataStructures.MultiValueDictKeyError 'name' - while receiving data from post request send by pure JavaScript using fetch API
What is the correct way of receiving data from post request in django.The request comes from pure javaScript using the fetch api. below is my code snippets: def change_group_name(request, pk): if request.method == 'POST': user = request.user name = request.POST.get('name', False) pk = request.POST.get('id', False) print('==========================================') print(name) print('============================================') I get an error when i try to print the name django.utils.dataStructures.MultiValueDictKeyError 'name' javascript async sendInfo(name ,id , csrf_token) { fetch('http://127.0.0.1:8000/accounts/group/detail/10/settings/change',{ method: 'post', credentials: "same-origin", headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'X-CSRFToken':csrf_token }, body: {'id': JSON.stringify(id), 'name': JSON.stringify(name)} }) } -
Template doesn't exist
I'm new to django. I am trying to learn it by building a project. I wanna replace the django's localhost hompage with my homepage. But, I couldn't find views.py in main project directory.Why? By the way, I made a new 'views.py' and also created a templates forlder and put index.html in another directory inside templates named englishexchange. englishexchange/url.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), path('admin/', admin.site.urls), ] englishexchange/views.py from django.shortcuts import render def index(request): return render(request, 'englishexchange/index.html') and I put my templates directory in main project directory englishexchange. I know I can do that by making another app and maping the url to nothing like ' '. But I want them to have different home page than the main's static home page. The error I am getting is like Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Sujeet Agrahari\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\englishexchange\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Sujeet Agrahari\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\templates\englishexchange\index.html (Source does not exist) I believe it's trying to find the templates in its default directory which is admin. How can I change this behavior so that it gets the templates from mian project directory? -
Django AUTH_PASSWORD_VALIDATORS doesn't see my validators
I needed password validators with Russian messages, so i rewrote existed validators. personalpage/accountpage/validators.py: from django.core.exceptions import ValidationError from django.conf.urls import url, Path from django.utils.translation import gettext as _ class MyUserAttributeSimilarityValidator: ... class MyMinimumLengthValidator: ... class MyCommonPasswordValidator: ... class MyNumericPasswordValidator: ... also, I indicated them in the settings.py personalpage/account/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accountpage', ] ... AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'accountpage.validators.MyUserAttributeSimilarityValidator', }, { 'NAME': 'accountpage.validators.MyMinimumLengthValidator', }, { 'NAME': 'accountpage.validators.MyCommonPasswordValidator', }, { 'NAME': 'accountpage.validators.MyNumericPasswordValidator', }, ] but when i register new user i get error why django doesn't see my validators? -
how to solve the error 'CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.'
I'm trying to set up Internationalization in my project in Django. But when doing the command: python manage.gy makemessages 'en' This error occurs: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. However, when I try the brew install gettext command it has the following response: Warning: gettext 0.19.8.1 is already installed and up-to-date I've read several posts in stackoverflow about this, but none of them solved my problem. -
Ngrix welcome page
Hello I followed the Digital ocean guide to setting up my django project on a server but I have can across a problem I keep getting the "Welcome to ngrix" page I even deleted my droplet and started again to see if that would work Guide [Unit] Description=gunicorn daemon After=network.target [Service] User=djangodeploy Group=www-data WorkingDirectory=/home/djangodeploy/portfolio-project ExecStart=/home/djangodeploy/venv/bin/gunicorn --access-logfile - --workers 3 --bind uni$ [Install] WantedBy=multi-user.target NOTE: removed IP for the question but I have been entering the correct IP server { listen 80; server_name MY IP CHANGED FOR THE QUESTION; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangodeploy/portfolio-project; } location / { include proxy_params; proxy_pass http://unix:/home/djangodeploy/portfolio-project/portfolioAK.sock; } } here is my file structure -
DateField and TimeField don't come out after adding to model class
I'm quite new to Python and Django. I'm setting up a new model class and I'm able to add appointments on the admin page, but here's the strange thing: I used to have a DateTimeFiled, which I changed to a separate DateField and a TimeField. But now I see neither my DateField nor my TimeField. Why is that, I don't understand it. I've done the migration, everything looks right. This is my model class: class Appointment(models.Model): patient = models.ForeignKey(User, related_name="appointment_patient", on_delete=False) date = models.DateField(auto_now=True) start_time = models.TimeField(auto_now=True) duration = models.DurationField(default=timedelta(minutes=30)) Before I made this change every property came out right, but now this happens: -
Django : How can I implement a remember me key on my login page
Actually rather than just code , I want to know all the topics I have to study for making a remember me key on my login page. Its a inbuilt django login page and i have a bit knowledge of sessions and cache but not enough for making a remember me key and havent user caching yet. If you can supply me with a answer or a source , that will be helpful -
Page not found when trying to catch url parameter
here is the error : Page not found (404) Request Method: GET Request URL: http://localhost:8000/pagePeople/18/ Using the URLconf defined in RepSys.urls, Django tried these URL patterns, in this order: 1. admin/ 2. [name='index'] 3. signup/ [name='signup'] 4. accounts/ 5. logout/ [name='logout'] 6. BasketPeople/ [name='index'] 7. Following/ [name='index'] 8. searchObject/ [name='searchObject'] 9. pageObject/ [name='pageObject'] 10. pagePeople/(?P<peopleId>\w{0,50})/$ [name='pagePeople'] and my urls.py : path("pagePeople/(?P<peopleId>\w{0,50})/$", views.pagePeople, name="pagePeople"), I'am trying to get this url : http://localhost:8000/pagePeople/18/ I am scratching my head Regards -
Django: How can i pass user input value from models.py to other business logic written file and then save to the database
I am new to Django so please guide if i am going on wrong way. Problem Defination: To take user input AS string and perform various manipulations on the input and save the modified value in the database.I also want to show this modified input as a json response. For temporary purpose i have created 4 fields namely ticker,open,close,volume.I want to transfer the open value from models.py to entity_exctraction.py file and multiply by 2 and save the updated value to the database. I tried to write the same logic in the models.py (commented part) and its working fine.but what i want is to write all business logic in some different file. Models.py from django.db import models from .entity_exctraction import Exctraction class Stock(models.Model): ticker = models.CharField(max_length=10) open = models.FloatField() close = models.FloatField() volume= models.IntegerField() open_val = Exctraction.update(open) #def save(self, force_insert=False, force_update=False, using=None, # update_fields=None): # print(self.open) # self.open = self.open * 2 # super(Stock, self).save() def __str__(self): return self.ticker entity_exctraction.py from django.db import models class Exctraction(): def update(val): val = val * 2.0 return val serializers.py from rest_framework import serializers from .models import Stock class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock print(type(model)) #model.open=model.open*2 #fields = ('ticker', 'volume') fields = '__all__' -
Django - redirect to from one app to another app's page Django
I have two apps called shop and subapp_gallery . Basically, subapp_gallery contains photo albums.. In my shop app I have my homepage for the website. so how can I redirect from link in a homepage[links to each albums] to subapp_gallery's albums path.both apps are working without errors. Thanks in advance. --CODE attached in links down-- >shop_project >>settings.py >>urls.py >shop >>apps.py >>models.py >>urls.py >>views.py >subapp_gallery >>apps.py >>models.py >>urls.py >>views.py shop app subapp_gallery app shop > urls.py subapp_gallery > urls.py -
How to retrieve current Django user and feed it into a db entry
I am adding instances of Pets to a table: class Pet(models.Model): petName = models.CharField(max_length=100, default='My Pet') petImage = models.ImageField(default='default.png', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) The code above is fine, however "User" on the last line gives me all the Users ever signed up on my app in a dropdown menu (when viewed as a form). I want the author (i.e. the User that is logged in) to be automatically associated with this new pet object. I dont know the ins and outs of the inbuilt auth_user database, so I dont know how to reference this specific instance of user, meaning the one who is logged in. I know that request.user on the other pages returns the user logged in, I just dont know how to feed that variable into this model. Any ideas? -
Django form won't show up
Like in title, I created simple form but it won't display. forms.py from django import forms class TimeTable(forms.Form): title = forms.CharField(max_length=100, required=True) time_start = forms.DateTimeField(required=True) time_end = forms.DateTimeField(reguired=True) views.py from home.forms import TimeTable from django.shortcuts import render def schedule(request): forms = TimeTable() return render(request, "registration/harmonogram.html", {'schedule_form': forms}) html: <div class="calendar_create"> <form method="post"> {% csrf_token %} {{ schedule_form.as_p }} <button type="submit">Submit</button> </form> </div> Only thing that I see is this <button type="submit"> rest just won't display? What I am doing wrong ? -
Update form django
I am trying to update my database by using form. I have a list of project data in front end with edit button. Now if I click corresponding edit button I want to redirect the webpage to the form with the project details.I want to update the data through that form. Error: Page not found (404). The current path, Project_Name/$, didn't match any of these. Please look into this video.This is what i am trying to do. https://www.youtube.com/watch?v=6y5Ucj5bI0Q&t=319s models.py class Project(models.Model): user = models.CharField(max_length=100) Project_Name = models.CharField(max_length=100) Project_Status = models.CharField(max_length=100) def get_absolute_url(self): return reverse ("update", kwargs={"Project_Name":self.Project_Name}) views.py @login_required def Create(request): form = CreateForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.success(request, 'New Entry Added') """return HttpResponseRedirect('')""" context = { "form": form, } return render(request, "users/form.html", context) @login_required def update(request, ASIN): template='users/form.html' post= get_object_or_404(Post, ASIN=ASIN) if request.method == "POST": form = CreateForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.success(request, 'Updated') return redirect("") else: form = CreateForm(instance=post) template='users/form.html' context = {"form": form} return render(request, template, context) datalist.html <table id="datatable" style="margin-top: 20px" style="margin-bottom:20px" class="table table-bordered" > <thead> <tr> <th>user</th> <th>Project_Name</th> <th>Project_Status</th> </tr> </thead> <tbody> {% for Project in filter.qs %} <tr> <td>{{ Project.user }}</td> … -
How to add friendships between users in Django
I'm doing a project for school. I'm creating a social media website with Django. I have problems with adding friendship between users. In the models I have extended the basic Django user. Is the get_friendship done correctly? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) real_name = models.CharField(max_length=60) address = models.CharField(max_length=60) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') phone_number = models.CharField(validators=[phone_regex], max_length=17) def get_friendships(self): friendships = Friendship.objects.all() return friendships class Friendship(models.Model): creator = models.ForeignKey(User, related_name="friendship_creator_set", on_delete=models.CASCADE) new_friend = models.ForeignKey(User, related_name="friend_set", on_delete=models.CASCADE, null=True) confirmed = models.BooleanField(default=False) @classmethod def make_friend(cls, creator, new_friend, confirmed=True): friendship, created = cls.objects.get_or_create( creator = creator, new_friend = new_friend, confirmed=True) friendship.save() views.py class Index(LoginRequiredMixin, generic.ListView): login_url = '/login' redirect_field_name = '' template_name = 'home/index.html' context_object_name = 'posts_list' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-pub_date') users = User.objects.exclude(id=request.user.id) user = Profile.user friends = Profile.get_friendships(user) args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } def add_friend(request, operation, pk): friend = User.objects.get(pk=pk) Friendship.make_friend(request.user, friend) return redirect('/') index.html <h2>Friends</h2> {% for friend in friends %} <h3>{{ friend.username }}</h3> {% endfor %} So the issue is that I cannot access the friends list. It seems that the get_friendships is not working correctly. Some of the code is just for testing so they are … -
Ajax post request cros-origin not working
I am trying to send some data to other domain, from my Django application via ajax post request. Here is my post request: var data = "id=somedata&src=somedata"; $.post('http://otherdomain.com/something.php', data, function(d){console.log(d)}) I get Reason: CORS header ‘Access-Control-Allow-Origin’ missing as expected, but i was told that i can catch the request and send it with python script with something(headers... i don't know), which then should work. The people that told me this were saying something about proxy but i don't remember what. But i still don't understand how can it work, and also i tried django-cors-headers but it doesn't work.Then i made my own middle-ware which adds header 'Access-Control-Allow-Origin','*' but when i looked at that request in developer tools it didn't have that header, only request which were 'inside' my django application. I still don't know if what i was trying to do was right and i only have problem in implementation, or i was doing everything wrong and should do something else. They send me this php-cross-domain-proxy, which is apparently what i am suppose to do, but in python. -
Package a Django project and its dependencies to run on a debian 9 server
I have a python Django project that runs on my local by running manage.py. It also runs fine on a debian machine when I do a scp of my project from my local to the server . After installing the requirement.txt , works as expected. But, I wanted to know if there is a way I can package my Django that can be easy installed on a debian machine . Thanks, Archana -
How to construct home page URL to render DetaiView with Django?
Please, help me to write correct URL to render context on the home page. Thanks to the kind help received here, I have the following code: model: import datetime from datetime import datetime, timedelta from django.utils.translation import ugettext as _ from django.db import models class DayOfWeekSchedule(models.Model): “""Dynamic days of week""" def days_of_week(self): days = { 1, _('Monday’), 2, _('Tuesday’), 3, _('Wednesday'), 4, _('Thursday’), 5, _('Friday'), 6, _('Saturday'), 7, _('Sunday')} DOW_CHOICES = [] today = datetime.today() for i in range(7): day_number = (today + timedelta(days=i)).isoweekday() day = days[str(day_number)] DOW_CHOICES.append(day_number, day) context = dict(DOW_CHOICES) return context view: import datetime from datetime import * from django.shortcuts import render from django.views.generic.detail import DetailView from .models import DayOfWeekSchedule class DayOfWeekSchedules(DetailView): model = DayOfWeekSchedule template_name = 'schedule.html' def get_context_data(self, **kwargs): context = super(DayOfWeekSchedules, self).get_context_data(**kwargs) context_a = self.object.my_dict() return render(request, self.template_name, context) url: path('<int:pk>/', DayOfWeekSchedules.as_view(), name='schedule’), and I get on http://127.0.0.1:8000/ the Error 404. I would like to see my page on 127.0.0.1:8000, not on 127.0.0.1:8000/1/. I also highly appreciate the relevant reading recommendations. -
Remove some logs in gunicorn
Hi I am using gunicorn as a web server for django. I would like the Closing connection log to be excluded or at least somewhat avoided.. Is that possible? [2018-11-22 19:07:31 +0800] [11] [DEBUG] GET /admin/login/ {Client-IP: -, Request-time: 0.010543, Request-date: [22/Nov/2018:19:07:31 +0800], HTTP-Status: "GET /admin/login/ HTTP/1.1", HTTP-Status-Code: 200, Response-length: 1987, Http-Referrer: -, User-Agent: kube-probe/1.9+} [2018-11-22 19:07:31 +0800] [11] [DEBUG] Closing connection. -
nginx gunicorn with docker: how to use multiple dockerfiles
I'm using the following example to build a django-postgres-nginx-gunicorn web server. I'd like to have separated folders for each container. The following structure of the project works correctly. The main Dockerfile is used for the hello app (the django project): svm3_03 |____Dockerfile |____config | |____gunicorn | | |____conf.py | |____nginx | | |____conf.d | | |____local.conf | |____db | |____db_env |____docker | |__db | |__Dockerfile | |__dataForDB |__docker-compose.yml |__hello the docker-compose.yml looks like this: version: '3' ... services: djangoapp: build: context: . ... and the Dockerfile has the following line: CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "hello", "hello.wsgi:application"] Everything works. Now I tried to have the same structure as the DB image also for the django app so I move the main Dockerfile and the hello directory inside the docker folder... I created a new folder inside the docker folder with name djangoapp and I moved there the Dockerfile and the hello folder. The new structure is the following: svm3_03 |____config | |____gunicorn | | |____conf.py | |____nginx | | |____conf.d | | |____local.conf | |____db | |____db_env |____docker | |__db | | |__Dockerfile | | |__dataForDB | |__djangoapp | |__Dockerfile | |__hello |__docker-compose.yml All I did then was … -
Exporting django variable to python file
Hi everybody and thank you in advance for your help. I want to introduce a number in my home.html, save it as variable 'n' and export it to my_calculations.py file. <form> <label for='number'>Number:</label> <input type='number' value='Save'> <button type="submit">submit</button> </form> Can you please explain me what should I exactly do? I look everywhere but there's a lot of info about how to send a variable from .py to templates but not the other way round. -
django : form_valid() missing 1 required positional argument: 'form'
I'm wondering how I can solve this issue in my form_valid() function : form_valid() missing 1 required positional argument: 'form' I'm using Django Class Based View and formsets. But, it could be possible to get IntegrityError and I added a try/except in order to save the formset when forms are valid, and redirect the template with an error message when I get this issue. class AnimalCreateView(CreateView): model = Animal template_name = 'animal_form.html' def get_context_data(self, **kwargs): context = super(AnimalCreateView, self).get_context_data(**kwargs) foo_queryset = Foo.objects.all() context['FooFormSets'] = FooFormSet(self.request.POST or None, self.request.FILES or None, prefix='foo', queryset=foo_queryset) return context def form_valid(self, request, form): context = self.get_context_data() formsets = context['FooFormSets'] if form.is_valid(): self.object = form.save() try: if formsets.is_valid(): formsets.instance = self.object formsets.save(commit=False) for element in formsets: element.save(commit=False) formsets.save() except IntegrityError: messages.error(self.request, _(f"Issue with foo")) return render(request, self.template_name) return super(AnimalCreateView, self).form_valid(form) I would like to know what I have to do in my form_valid() function in order to solve my issue and redirect user on the same template form with error message. Thank you -
Add fields dynamically in django ModelForm
my model class MyModel(models.Model): remark = models.CharField(max_length=120) data_1 = models.BooleanField(default=False) data_2 = models.BooleanField(default=False) data_3 = models.BooleanField(default=False) data_4 = models.BooleanField(default=False) Form class MyModelForm(forms.ModelForm): CHOICES= (("data_1", "data_1"), ("data_2", "data_2"), ("data_3", "data_3"), ("data_4", "data_4"),) my_choice = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple()) class Meta: model = MyModel fields = ["remark"] view class MyView(UpdateView): model = MyModel form_class = MyModelForm template_name = "mytemplate.html" def form_valid(self, form): selected_choices = self.request.POST.getlist("my_choice") for item in selected_choices: form.instance.item = False form.instance.remarks = form.cleaned_data["remark"] form.instance.save() return super(MyView, self).form_valid(form) what i want is, i want to take the selected choices and change its value to False by checking the checkbox and remaining must be unaffected.Please help.... -
Django-Bootstrap formset not displaying group select as dropdown
I have a formset to display a selected subset of User information, and allow permitted people to edit it. Part of that is the users Group membership. The formset is created with modelformset_factory from django's built in User form. The problem I have is that the group field is not rendering as a dropdown. It shows all of the groups as a block, with the selected group highlighted. The template renders the form with <form action="{% url 'users:profiles' %}" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row"> {% bootstrap_form form show_help=FALSE %} {% buttons %} <button name="submit" class="btn btn-primary btn-sm">Submit</button> {% endbuttons %} </div> {% endfor %} </form> </div> I have tried rendering each field seperately with {% bootstrap_field %}, and the group as a <select>. That rendered correctly, but then trying to change on users detail caused every form to error. Is there a way to have a dropdown in a formset?