Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Class Based Views keep url parameters in session
I have a django listview working fine. Its receive url parameters to filter data. Its paginated. Now, I want to maintain these data along the user session. (page number and url parameters). Example: I'm in the products list view. I search for 'foo' I select page 2 And then, I click in any product detail. The page will redirect to detail view. When I return to product list view, I whant to keep the search argument 'foo' and selected page 2. What is the better way to do this? I'm using Django 2.0.6 Models.py class Product(models.Model): name= models.CharField(_('name'), max_length=150) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.0) Views.py class ProductList(ListView): model = Product paginated_by = 10 def get_queryset(self): queryset = Product.objects.all() name = self.request.GET.get('name', None) if name: queryset = queryset.filter(name__icontains=name) return queryset Urls.py path('products/', views.ProductList.as_view(), name='product_list'), -
Problemnotrunningdjangosite
i have a django site When executing the site, Error is given Problem in path ordering In the file url error : path('posts/', views.posts, name ='post') image (urls and error) : enter image description here -
My django html tags are not showing the result
Hello my django tags are not displaying the result. I don't know where I am making a mistake as i am new to django python. If you want to see more code do let me know. Template: {% extends 'default/base.html' %} {% block content %} <h1>Products Details </h1> <p>These are the details of your product, {{ user.username }}</p> {% for s in product__details %} {{ s.name }} {% endfor %} {% endblock %} My view from django.shortcuts import render, redirect, get_object_or_404 from .forms import NewPro, Product from django.contrib.auth.decorators import login_required @login_required() def pro(request): form = NewPro() if request.method == 'POST': form = NewPro(request.POST, request.FILES) if form.is_valid(): entry = form.save(commit=False) entry.user = request.user entry.save() return redirect('add_products') else: form = NewPro() return render(request, "default/add_product.html", {'form': form}) @login_required() def product(request, product_id): print(product_id) details = get_object_or_404(Product, id=product_id) product_details = Product.objects.get(id=product_id) print(product_details) return render(request, "default/product_details.html", {'details': details, 'product_details': product_details}) -
Unresolved Error in Django Signal
I want to populate artistfield of Album model with pre_save function while saving an instance Musician model. models.py class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) def __str__(self): return self.first_name class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField(null=True,blank=True) num_stars = models.IntegerField(null=True,blank=True) def __str__(self): return self.artist @receiver(pre_save,sender = Musician) def create_album(sender,instance,**kwargs): sm = Album() sm.artist = instance sm.save() But when I am trying to create an instance of Musician Model from admin, it shows this error upon hitting save button. Exception Type: ValueError at /admin/sig/musician/add/ Exception Value: save() prohibited to prevent data loss due to unsaved related object 'artist'. I cant understand how to solve this sm.save() error! Please be helping me. -
creating a custom tag and make it accessible to templates in different apps in django
I am new to Django and I am trying to custom tags in django my view.py is like this def my_view(request): do_work = utils(request) return JsonResponce(do_work) my uitls.py gets the request, does something and returns a dictionary as a response def my_utils(request): do_somthing = somthing(request) return do_somthing I want this JsonResponce accessible to templates of different apps on the same project. So I am trying to do it with custom tags. my customtag.py file is located in templatetags/custom_tags.py from django import template from app_1.utils import my_utils register = template.Library() @register.simple_tag def my_tag(): return my_utils() I use this template tag in a html page of another app called app2.html {% load my_tag from custom_tag %} {% my_tag.value1 %} I getting the error my_tag.value1 Did you forget to register or load this tag? I know I am doing something wrong with the initialization of custom tag file. Please help me what I am missing here. thank you. -
How can I do redirect from thread in Django?
func2 finish later then func1. I want to redirect twice, first to 'app/page' and after finish func2 to 'app/index' This code doesn't work def func1(request): # some code def func2(y): # some code return redirect('app/index') s_threading = threading.Thread(target=func2, args=(y)) s_threading.start() return render(request, 'app/page') -
Set initial values on ModelMultipleChoiceField CheckboxSelectMultiple widget using list
I have a ModelMultipleChoiceField in a form which is generated with a queryset. class NewEvaluationPriorityForm(forms.Form): priority_field = forms.ModelMultipleChoiceField( queryset=None, widget=forms.CheckboxSelectMultiple, required=False ) def __init__(self, user_type, qi_list, hgiours_list, is_hgiours_evaluation, school, *args, **kwargs): super(NewEvaluationPriorityForm, self).__init__(*args, **kwargs) if is_hgiours_evaluation is True: priorities = Priority.objects.get_new_hgiours_evaluation_priorities( hgiours_list, school ) else: priorities = Priority.objects.get_new_evaluation_priorities( qi_list, user_type, school ) self.fields['priority_field'].queryset = priorities self.fields['priority_field'].label = '' What I want to do is to set the initial values of the different checkboxes in the field using a list. I have tried the following (where I know there are 5 objects in the queryset): self.fields['priority_field'].initial = [True, False, True, False, True] But that doesn't work. What is it that I need to do? -
In Django where should I check if user is not logged in?
Django has two approaches. Regular DRF restricts user on Middleware level. So not logged in user doesn't reach anything. GraphQL, on contrary, uses "per method" approach. So middleware passes all the request and each method. But afterward method calls decorator. What is more secure and more proper approach? -
Django: Trying to select random result, but get Object has no len() error
I am building a Django-Rest API that returns a random object from a queryset class AdViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = AdSerializer queryset = Ad.objects.none() def get_queryset(self): if 'verify' in self.request.GET: # Return random object random_ad = Ad.objects.filter(verified=False).order_by('?').first() # return random_ad return random_ad return Ad.objects.all().order_by('-pk') But this code returns the object of type 'Ad' has no len() error. Removing the .first() command causes the API to return a queryset, so I know it is getting results. But I need a single (random) instance. Does anyone know what I am doing wrong? -
Django-How to retrieve posts data of logged in user friends
I am working on a Social network project!! It has models that saves User data ,Friends data and Posts data Users -> User Info Friends -> User friends Media -> All Posts from users How do i get the posts of friends of logged-in user . -
Mark GeoJSON information on OpenLayers map. Backend in django
I started writing a project that will run on a webserver. The backend is written in Python using the framework Django. The view this question is about shows a map. For doing this, I used openlayers. Obviously, this works within the browser. (The template and the static JavaScript file is very similar to the code in their quickstart example.) Where to go from here? I have some data given in GeoJSON format. Any Feature if of the Type Multipolygon. This data is not likely to change often. I want to show the areas that are covered be colored red or green. (Color and radius around points are given.) What's the problem? Well, I have a huge amount of data. Think of 200 Megabytes of raw json, converted to over 8000 points. (Since the first try was writing a browser application only, it creates VectorLayers that contains all those points. Yes, this works, but the performance is horrible. Think of an hour of loading. Try it out yourself: already on a webiste; the code, just pack it all on a webserver.) What's the goal? I guess I could speed up the site since there is no need to convert the GeoJSON … -
FATAL: password authentication failed for user "postgres" after running makemigrations
After trying python manage.py makemigrations on the remote server I get the following error: `django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres"` Does anyone know how to trouble shoot this issue? -
nginx cant't serve files correctly when deploy a django project with nginx and uwsgi on ubuntu 16.04
When I deploy a django project follow this tutorial:[http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html?highlight=django when I done the step Basic nginx test, after i type taopinpin.cn/media/media.png, the page response denied like this: enter image description here and my project like this: enter image description here mysite_nginx.conf file is : upstream django { server 127.0.0.1:8001; } server { listen 8000; server_name taopinpin.cn; charset utf-8; client_max_body_size 75M; location /media { alias /root/mysite/media; } location /static { alias /root/mysite/static; } location / { uwsgi_pass django; inlcude /root/mysite/mysite/uwsgi_params; } } I don't know where get an error, can you help me debug it ? Thank you a lot. -
django get token and userid after successful registration
I'm building a server with custom registration pages using rest and django (latest versions). I have 3 fields required (username unique, phone_number unique, password) and 1 optional. Schema is: User sends phone-number to server, we check if user exists and if don't - ask for registration. In both cases I want to send token and user_id as answer if credentials are correct. The topics from 2016's are not working in my case, i think because of latest framework and python updates. That's what i have now in view.py: class RegisterView(APIView): # works fine except it doesnt send token and user_id on finish renderer_classes = [renderers.JSONRenderer] def post(self, request): phone = request.POST.get('phone_number') name = request.POST.get("name", '') username = request.POST.get('username') password = request.POST.get('password') """check if some fields are missing""" try: User.objects.create_user(username, phone, password, name) return Response("""there should be token and user_id""") except KeyboardInterrupt: return Response("""error""") class CheckPhone(APIView): # works fine renderer_classes = [renderers.JSONRenderer] def post(self, request): phone_number = request.POST.get('phone_number') try: User.objects.get(phone=phone_number) return Response("""asks for login""") except User.DoesNotExist: return Response("""asks for registration""") class auth_(authentication.BaseAuthentication): def authenticate(self, request): # Get the username and password phone = request.POST.get('phone_number', None) password = request.POST.get('password', None) if not phone or not password: return Response("""no credentials""") credentials = { … -
How to update time on page in Django 2.x
It's loaded only once, but not every second. When I refresh manually it's updated. Whats wrong with my js? in script.js: function show() { $.ajax({ url: "/time", cache: false, success: function (html) { $('#logs').html(html) } }) } setInterval(show, 1000); show(); -
NoReverseMatch at /project
I am new to Django. I created a simple createview and then tried the updateview likewise but I got the NoReverseMatch Error. I tried many ways suggested online but still they didnt seem to work. This is the screenshot of the error I am getting NoReverseMatchError Below are my files urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url,include from mapp import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), url(r'^$',views.AboutView.as_view(),name='about'), url(r'^blogs/$',views.BlogsView.as_view(),name='blog'), url(r'^project/$',views.ProjectListView.as_view(),name='project_list'), url(r'^project/(?P<pk>\d+)/$',views.ProjectDetailView.as_view(),name='project_detail'), url(r'^project/create/$',views.ProjectCreateView.as_view(),name='project_create'), url(r'^project/(?P<pk>\d+)/$',views.ProjectUpdateView.as_view(),name='update'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views.py from django.shortcuts import render,redirect from django.views.generic import TemplateView,ListView,DetailView,CreateView,UpdateView from mapp.models import Project from mapp.forms import ProjectCreateForm,ProjectUpdateForm # Create your views here. class AboutView(TemplateView): template_name='about.html' class BlogsView(TemplateView): template_name='blogs.html' class ProjectListView(ListView): model=Project class ProjectDetailView(DetailView): model=Project class ProjectCreateView(CreateView): model=Project form_class=ProjectCreateForm redirect_field_name='mapp/project_detail.html' class ProjectUpdateView(UpdateView): model=Project form_class=ProjectUpdateForm redirect_field_name='mapp/project_detail.html' Project_detail.html {% extends 'base.html'%} {% block content %} <h1>Project Details</h1> <div class="container"> <h2>{{project.pname}}</h2> <img src="{{project.pimage.url}}"></img> <h2>{{project.ptech}}</h2> <h2>{{project.pdetails}}</h2> </div> <div class="container"> <p><a href="{%url 'update' pk=self.pk %}">Update</a> </div> {% endblock %} Forms.py from django import forms from mapp.models import Project class ProjectCreateForm(forms.ModelForm): class Meta: model=Project fields=('pname','pimage','ptech','pdetails') class ProjectUpdateForm(forms.ModelForm): class Meta: model=Project fields=('pname','pimage','ptech','pdetails') Project_form.html {% extends 'base.html' %} {% block content %} <form class="project-form" method="POST" enctype="multipart/form-data"> <div class="jumbotron"> {% csrf_token … -
Not a valid UUID while filtering queryset in Django
I'm using Django to make a simple booking system with a PostgreSQL as my database of choice. I have two models connected through M2M relation. Reservation class Reservation(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) service_start = models.DateTimeField(db_index=True) pax_name = models.CharField(max_length=50) pax_last_name = models.CharField(max_length=50) tags = models.ManyToManyField(Tag, related_name='tags') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Tag class Tag(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30) slug = models.SlugField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Now, when I make a simple filter query to find Reservations with exact set of tags, I get an error. List of tags ('Tags: ', [<Tag: ls>]) Filter query Reservation.objects.filter(tags__exact=tags) With an error ValidationError at / [u"'[<Tag: ls>]' is not a valid UUID."] How can I filter a query with a set of exact tags? -
Django migrations ignoring db_table when set using metaclass
I'm using a metaclass to automatically set my Django model db table names from camel case to '_' seperated names, e.g. MyGreatModel will have a table name like appname_my_great_model instead of the default appname_mygreatmodel: class PrettyModelBase(ModelBase): def __new__(cls, name, bases, attrs): super_new = ModelBase.__new__(cls, name, bases, attrs) module_name = camel_to_underscore(name) model_module = sys.modules[cls.__module__] app_label = super_new.__module__.split('.')[-2] db_table = '%s_%s' % (app_label, module_name) if not getattr(super_new._meta, 'proxy', False): super_new._meta.db_table = db_table return super_new class BaseModel(models.Model): __metaclass__ = PrettyModelBase class Meta: abstract = True class MyGreatModel(BaseModel): somefield = models.TextField(default="") However migrations doesn't seem to pick up this db_table name. If I run makemigrations, then CreateModel doesn not show db_table in the options for this model. If I hard-code it in the class Meta of MyGreatModel then it does. Moreover if I check the SQL to be run with python manage.py sqlmigrate... then it shows that it will create the appname_mygreatmodel table, not the delimited table name. However if I do run this migration and then examine the model in the Django shell, then MyGreatModel._meta.db_table shows my_great_model as I would expect from my metaclass. Why is Django migrations not picking up the db_table here? I'm using Django==1.10.5. Thanks for any help -
Send mail *without* mail queue in Django
Im using django_yubin to send mails via its mail queue. However, there are a few instances where I want to send the mail immediately without putting it on the queue. For example, when a user registers or resets their password. Or certain admin emails. I tried using Django's built in email system by from django.core.mail import send_mail as send_mail_core and then using the send_mail_core() function. This didnt work - looks like the send_mail in django.core.mail gets overridden by yubin Thanks for your help -
allauth custom adapter for custom user model
I used Django rest framework and custom user model. [urls.py] from django.contrib import admin from django.urls import path, include from rest_framework_jwt.views import refresh_jwt_token urlpatterns = [ path('admin/', admin.site.urls), path('', include('rest_auth.urls')), path('registration/', include('rest_auth.registration.urls')), path('refresh-token/', refresh_jwt_token), ] [model.py] from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError(_('Users must have an email address')) user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=email, password=password, username=username, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('Email address'), max_length=255, unique=True, ) username = models.CharField( verbose_name=_('username'), max_length=30, unique=True ) is_active = models.BooleanField( verbose_name=_('Is active'), default=True ) date_joined = models.DateTimeField( verbose_name=_('Date joined'), default=timezone.now ) salt = models.CharField( verbose_name=_('Salt'), max_length=10, blank=True ) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] class Meta: verbose_name = _('user') verbose_name_plural = _('users') ordering = ('-date_joined',) def __str__(self): return self.username def get_full_name(self): return self.username def get_short_name(self): return self.username @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All superusers are staff return self.is_superuser get_full_name.short_description = _('Full name') save_user() … -
Django media image not displaying
I am developing a django app were i am uploading images through the admin panel i have implemented this in my other apps but i can seem to get what is wrong with my configurations as follows settings.py STATIC_URL = '/static/' AUTH_USER_MODEL = 'ntakibariapp.Member' LOGOUT_REDIRECT_URL = 'ntakimbari:_login' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) urls.py " from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('ntakibariapp.urls')), path('accounts/', include('django.contrib.auth.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, ducument_root=settings.MEDIA_ROOT) models.py class Community_work(models.Model): where = models.CharField(max_length=80) time = models.TimeField(blank=False) date = models.DateField(blank=False) image_of_area = models.ImageField(upload_to='photos',blank=True) post_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.where template/communtity_work.html {% extends 'temp/base.html' %} {% block title %}community works{% endblock %} {% block body %} <div class="container"> {% for work in works %} <p>Picture of the area <img src="{{work.image_of_area.url}}"></p> <p>Where: {{work.where}}</p> <p>Time: {{work.time}}</p> <p>Date: {{work.date}}</p> {% endfor %} </div> {% endblock %} -
Is Django the right framework for me?
All I knew about Django before getting into it was that it allowed Python to be visible on the web. The more I get into it, the more I fear this won't do specifically what I had in mind as I feel I'm being pigeon-holed into a certain coding design whilst following the official tutorials. In short, I like to prototype ideas that I can code quickly in a hacky way. I like to manually create MySQL tables and perform extensive custom conditional update queries on them. For example, my current python code looks similar to if (some_conditional): c.execute("UPDATE t2 SET r2=r1-r2 WHERE regp-?<=5 AND.... As you can see, such a query involves lots of manual conditionals and quick manipulation of the MySQL database. I was hoping Django would quickly allow a way to UPDATE things, SELECT them, and print the results in the browser. Instead I'm embarking upon a tutorial that feels like I need to complete 10 degrees to understand it and all its abstraction. Django seems to abstract SQL entirely, forcing me to use classes and OOP methodology to update database "objects". The ability to manually hack and manipulate things just doesn't seem to be there in … -
set the choices of ChoiceField in Django Rest
using Django 2.0 with Rest 3.7.7. I have a Serializer class where a field is a ChoiceField and it's choices are the result of calling a function which takes the request.user as argument. Here's my code: class PostModelCreateSerializer(serializers.ModelSerializer): group = serializers.ChoiceField(choices='') # What I want to do is this # group = serializers.ChoiceField(choices= request.user.get_groups()) # get_groups() returns a queryset of groupModel class Meta: model = MYMODEL fields=[ 'id', 'group', 'content' ] Thank you -
"django-admin.py makemessages -l en" adds Plural-Forms to the output file
Every time I run django-admin.py makemessages -l en, it adds the following line to the djangojs.po file: "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" after that running python manage.py runserver break out whith this error: ValueError: plural forms expression could be dangerous Of course removing that line fix the error and make it go away. How can I prevent this line from being added? -
How to create an object inside the CreateView in Django?
I want to create and save an object in my View using CreateView. > example in django documentation, uses a form to create new object while I have the fields value (I know the user and the book he selected) and want to create it inside the view, something like this. from django.views import generic class BookReserveView(generic.CreateView): model = Reservation person = current_login_user # the user who logged in book = selected_book # selected book (I have the pk) success_url = reverse_lazy('book:reserve_book') # when the object saved go to this url and this is my Reservation model. class Reservation(models.Model): person = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Copy, on_delete=models.CASCADE) date_reserved = models.DateTimeField(auto_now_add=True) I tried this code and it worked for me. but I like to use generic views (CBV) from book.models import Copy,Reservation def BookReserveView(request,pk): book = Copy.objects.get(pk=pk) reserve_obj = Reservation(book=book, person=request.user) reserve_obj.save() return HttpResponse(str(reserve_obj))