Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why aren't my profiles being displayed in equal location?
So I have a page that displays the matches a user has matched with, other users. In the display page, the profiles are being displayed unevenly. Each profile card is sometimes a different size and being displayed in a slightly different uneven location. How can I get them to all be the same size and be displayed evenly? Is it due to the photo size? matches.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} <!DOCTYPE html> {% block head %} <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> </head> {% endblock %} {% block content %} <br> <title>Your Matches</title> <div class="container"> <h5>Your Matches:</h5> {% for item in match %} <div class="container"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading"> <h4 style="color:#CB2603 " >My Profile</h4></div> <div class="panel-body"> <div class="col-md-4 col-xs-12 col-sm-6 col-lg-4"> <img alt="User Pic" src="{{ item.photo.url }}" width="500" id="profile-image1" class="img-circle img-responsive"> </div> <div class="col-md-8 col-xs-12 col-sm-6 col-lg-8" > <div class="container" > <h2>{{ item.username }}</h2> </div> <hr> <ul class="container details" > <h3 >About me</h3> <p><span style="width:50px;margin:50px"></span>{{ item.description }}</p> </ul> <hr> <a href="{% url 'dating_app:message' item.id %}">Start messaging {{item.username}} now!</a> </div> </div> </div> </div> {% endfor %} </div> {% endblock content %} -
Saving the city of an unregistered user. Django
I want implement feature: saving the city of an unregistered user in my django app. Example I visited the site for the first time. And chose my city. (not registerd) I visited the site for the second time. Site identified my city. How can I do It with django? P.S. Could you please recommend articles or materials? Example of the site https://edadeal.ru/ (you can chose city in the top right corner red text) -
Is specifying a UniqueConstraint on two fields expensive in Django?
As per the documentations here, Django conveniently allows you to specifiy a list of fields that must be unique together. I imagine that for each row inserted in the database Django scans the entire table to verify the constraint. In a table with 1M+ rows I can imagine that this is a nightmare. Is this indeed how UniqueConstraint operates? Is it really this expensive? -
Populate dictionary values in a dropdown with django
I am returning a dictionary to a variable under views.py as follows: dict1={1:["a","b"],2:["c","d"]} def home(requests): return render(requests,'home/index.html',{"dict":dict1}) I have the following HTML Form with a drop down and a multi-select text area: index.html <select class="form-control" id="exampleFormControlSelect1"> <option>o1</option> <option>o2</option> </select> <select multiple class="form-control" id="exampleFormControlSelect2"> <option>title1</option> <option>title2</option> <option>title3</option> <option>title4</option> <option>title5</option> </select> I need to populate keys in the first dropdown and whenever I select a key from the dropdown, the other dropdown must be populated with values corresponding to the key.I tried with {%for} but I am unable to access the key-value pairs. -
Hi everyone, can someone please assist me with this error that i am getting when am doing migrations
django.db.utils.OperationalError: no such table: clients_contacts PS C:\Users\NonsikeleloZ\Desktop\SucccessProject> -
Format date in python as is done in django template
In a django template, datetime is formatted as follows: June 17, 2020, 7:56 p.m. How do I get this same formatting in Python? I think it has something do to with USE_L10N Thanks!! -
How to solve django.db.migrations.exceptions.InconsistentMigrationHistory
I am currently using Django 3.0.5. I got the error of InconsistentMigrationHistory after I ran migrations after modifying one of my models. I was also using SQLite as the database. I solved this by: 1.Deleting all the files in the migrations folder except the init.py file. Note, that I deleted the files from the migrations folder of the model that I had modified. 2.I deleted the sqlite file. 3.I ran the command python manage.py makemigrations 4.And finally python manage.py migrate -
How do I anchor part of a django page?
There is a link to contacts (they are on the main page at the bottom) and I need to click to transfer the user to the specified part of the page <li class="menu__item menu__item_footer"> <a href="{% url 'main:index' %}" class="menu__link">Контакты</a> </li> views.py: class ContactView(SuccessMessageMixin, FormView): template_name = 'main/index.html' form_class = EmailForm success_url = 'main/index.html' success_message = "Письмо успешно отправлено" def form_valid(self, form): email = form.cleaned_data['email'] send_mail('Caparol_Center_Spb', 'Теперь вы будете получать лучшие предложения шоу-рума', settings.EMAIL_HOST_USER, [email, ], fail_silently=False,) success_message = self.get_success_message(form.cleaned_data) if success_message: messages.success(self.request, success_message) if not Subscriber.objects.filter(email=email).exists(): Subscriber.objects.create(email=email) return redirect(reverse('main:index')) -
serializing a Django ModelSerializer into json?
I have defined a model with a property I'd like to be included in the serialization: class Flower(models.Model): health = CharField(...) @property def is_okay(self): return self.health == 'ok' class OKSerializer(serializers.ModelSerializer): is_okay = serializers.Field() class Meta: model = Flower fields = '__all__' Originally I was using the django.core.serializers to serialize into json: flowers = Flower.objects.all() serialized_flowers = serializers.serialize("json", flowers) Which was super nice, but Django does not serialize the custom property on the model, so I had to create my own serializer like you see above. However, when I try to do the same, I get an error: serialized_flowers = OKSerializer.serialize("json", flowers) # ERROR" 'OKSerializer' has no attribute 'serialize' This is probably because I'm using ModelSerializer, which has no serialize() function. Is there a way I can serialize into json using ModelSerializer like I had done before? Does ModelSerializer have a function for serializing into json? -
Vue JS project does not reflect changes on browser
I have an existing Vue JS project that had been worked on previously and loads correctly without any errors. But, any additional changes I make to HTML/CSS does not get reflected on the browser. I tried restarting the server, but it didn't change anything. I have tried to load it on different browsers, but that didn't work too. I am using WSL on windows. -
Can't able to pass data from views to template in Django
The code is given below views.py def dashboard(request): obj = Tools_booked.objects.all() authority = User.objects.get(email=request.user.email) profile_data = Profile.objects.get(user__username=request.user.username) # For testing the error print(type(profile_data.people_reached)) print(profile_data.scholarship) print(profile_data.task) print(profile_data.to_return) text = "hello world" dict = { 'tools':obj, 'blog_view':int(profile_data.people_reached), 'scholarship':int(profile_data.scholarship), 'tasks':int(profile_data.task), 'to_return':int(profile_data.to_return), 'text':text, } if authority.is_staff: return render(request, "backend/index.html", dict) authority = Profile.objects.get(user=request.user) if not authority: return render(request, "backend/index.html", {'tools':obj}) if authority.role == 'prin' or authority.authority == True : return HttpResponseRedirect(reverse('dashboard-admin')) return render(request, "backend/index.html", {'tools':obj}) index.html {% extends "backend/base_default.html"%} {% load static from staticfiles %} {% block content %} ... <h1>{{ blog_view }} </h1> <h1>{{ scholarship }} </h1> <h1>{{ tasks }} </h1> <h1>{{ to_return }} </h1> <h1>{{ text }} </h1> {% endblock %} In the above template tagging the tag 'text' hello world is get printed but the rest is not printed. But the output of these tags can be printed in the views, by accessing the terminal get output as <class 'int'> 0 0 0 These values need to be sent to HTML but its not working? -
django-autocomplete-light's suggestions displayed beyond the drop-down list
For some reason, suggestions from django-autocomplete-light are displayed beyond the drop-down list, to the right (there's narrow blue rectangle visible that indicates suggestions): I'm able to reverse the widget's url and obtain correct suggestions. Everything's working fine but rendering - when I click on this narrow rectangle, correct value appears in the edit box. I collected all the static files. I'm working on Linux 20.04 LTS, Chrome 83.0.4103.106, python 3.7.7, django 3.0.3, bootstrap 4.5.0 and font-awesome 4.7.0. Here is the code (except settings) that I wrote forms.py class OpinionForm(forms.ModelForm): # user field is defined as hidden and disabled such that it couldn't be changed user = forms.ModelChoiceField( widget=forms.HiddenInput, queryset=get_user_model().objects.all(), disabled=True ) # defining all the fields with autocomplete feature country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2(url="country_autocomplete") ) class Meta: model = Opinion fields = ("content",) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["country"].label = "Kraj" self.fields["content"].label = "Treść" models.py class Country(models.Model): name = models.CharField(max_length=200, null=False) def __str__(self): return self.name class Opinion(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL) content = models.TextField() created = models.DateTimeField(auto_now=True) urls.py urlpatterns = [ path("add_opinion", views.CreateOpinionView.as_view(), name="add_opinion"), path("country-autocomplete/", CountryAutocomplete.as_view(create_field="name"), ] views.py class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class CreateOpinionView(LoginRequiredMixin, CreateView): … -
How to update and upsert multiple documents in MongoDB in django
I want to upsert multiple documents with a single query in mongodb like we can do in mysql with duplicate key update. I have already tried the solution for upserting each doc through iteration via db.collection.update_one({'hotel_id': hotel_doc['hotel_id']}, {'$set': {**hotel_doc, **{'ut': ct}}, '$setOnInsert': {'ct': ct}}, upsert=True) Please help -
Django : Cannot resolve the URLs pattern : Always Index page content is displayed
I am learning Django. I build an app in which I am setting up the URL patterns but in all cases it's displaying the data for the index page. MyApp urls.py File : `urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$', views.users, name='users'), url(r'^$', views.help, name='help'), ]` MyProject urls.py file : `urlpatterns = [ url(r'^$', views.index, name='index'), url('admin/', admin.site.urls), url(r'^users/', include('appTwo.urls')), url(r'^help/', include('appTwo.urls')), ]` If I call /users or /help, the browser display the data for index file only. Is there something with a regex that I am doing wrong? -
How to use has_object_permission with APIView in Django Rest Framework?
Hi everyone I want to use a custom permission with APIView in my class UserDetail but I noticed that this permission is not executing, my permission is called "IsOwner", because I want to allow users to modify his own information based on the user id. Every time that I make a request I got an error: { "detail": "Not found." } views.py from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import status, permissions, generics, viewsets from rest_framework.response import Response from rest_framework.views import APIView from .serializers import MyTokenObtainPairSerializer, UserSerializer, GroupSerializer from .models import User from authentication.permisssions import CustomObjectPermissions, IsOwner from django.contrib.auth.models import Group from django.http import Http404 class ObtainTokenPairView(TokenObtainPairView): permission_classes = [permissions.AllowAny,] serializer_class = MyTokenObtainPairSerializer class UserList(APIView): """ List all snippets, or create a new snippet. """ permission_classes = [CustomObjectPermissions] serializer_class = UserSerializer def get_queryset(self): users = User.objects.all().order_by('-date_joined') return users def get(self, request, format=None): serializer_context = { 'request': request, } serializer = UserSerializer(self.get_queryset(), context=serializer_context, many=True) return Response(serializer.data) def post(self, request, format=None): serializer_context = { 'request': request, } serializer = UserSerializer(data=request.data, context=serializer_context) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserDetail(APIView): """ Retrieve, update or delete a snippet instance. """ permission_classes = [CustomObjectPermissions|IsOwner] serializer_class = UserSerializer def get_queryset(self): pk = self.kwargs["pk"] return … -
Dokku: Need some guidance in serving frontend (vue) and backend (django, drf)
I recently moved over to using Dokku and am wondering if someone can help me out with this. I am trying to run Vue and Django on a Linode server. Currently I have Django serving at my IP. Looks like in nginx, that port 80 is being listened to and Django is being served at /. I'd like to move Django to either be served at ':8000' as it is on my local machine or to be served at '/backend'. Then I'd like to serve Vue the way Django is currently being served () and it can hit the api at either previously mentioned Django location. -
Unable to create super user with CustomUser model in Djnago
Im have created a custom user manager to create users with mobile number in django. But now im unable to create super user. Im getting error AttributeError: 'CustomUserManager' object has no attribute 'mobile'. please find the below codes and help out. Thanks in advance from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from master.models import * class CustomUserManager(BaseUserManager): def _create_user(self, mobile, password=None, **extra_fields): """Create and save a User with the given mobile and password.""" if not mobile: raise ValueError('The given mobile must be set') mobile = self.mobile user = self.model(mobile=mobile, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, mobile, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(mobile, password, **extra_fields) def create_superuser(self, mobile, password=None, **extra_fields): """Create and save a SuperUser with the given mobile and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(mobile, password, **extra_fields) class CustomUser(AbstractUser): username = None mobile = models.CharField(_('Mobile Number'), unique=True, max_length=10) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) dob = models.DateField() date_created = models.DateTimeField(auto_now_add=True) profile_image = models.ImageField(upload_to='user_pics') email = models.EmailField(max_length=50) address = models.CharField(max_length=200) city = models.ForeignKey(City, null=True, on_delete=models.SET_NULL) state = models.ForeignKey(State, null=True, … -
The QuerySet value for an exact lookup must be limited to one result using slicing and
I want to get or create an object when a form is save My view @login_required def index(request, log_id): log = get_object_or_404(LogBook, pk=log_id) logmessages = LogMessage.objects.filter(logbook=log_id) logbook = LogBook.objects.get_or_create(logmessages=logmessages) form = CreateLogMessage(request.POST) if request.method == "POST": if form.is_valid(): logbook.done_status = False logbook.save() instance.save() I tried several answers from SO : Django:The QuerySet value for an exact lookup must be limited to one result using slicing but it returns another error get() returned more than one LogMessage -- it returned 8! This one The QuerySet value for an exact lookup must be limited to one result using slicing-Django return again, a different error 'int' object has no attribute 'all' So i am not sure what I am doing wrong. -
How to fix django-amdin not recongnised
This is the code i've tried I tried updating it using git clone https://github.com/django/django.git but it's the same Requirement already satisfied: django in c:\users\hp\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (3.0.7) Requirement already satisfied: asgiref~=3.2 in c:\users\hp\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from django) (3.2.7) Requirement already satisfied: pytz in c:\users\hp\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from django) (2020.1) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\hp\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from django) (0.3.1) C:\Users\HP>python -m django --version 3.0.7 C:\Users\HP>django-admin 'django-admin' is not recognized as an internal or external command, operable program or batch file. C:\Users\HP>git clone https://github.com/django/django.git Cloning into 'django'... remote: Enumerating objects: 82, done. remote: Counting objects: 100% (82/82), done. remote: Compressing objects: 100% (72/72), done. remote: Total 458425 (delta 35), reused 19 (delta 10), pack-reused 458343 eceiving objects: 100% (458425/458425), 191.37Receiving83 MiB/s objects: 100% (458425/458425), 192.20 MiB | 1.85 MiB/s, done. Resolving deltas: 100% (335466/335466), done. Updating files: 100% (6266/6266), done. C:\Users\HP>django-admin 'django-admin' is not recognized as an internal or external command, operable program or batch file.``` -
When displaying foreign key base Queryset on template
I have two models shown below class Services(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) service_sku = models.CharField(max_length=200, null=True) class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete = models.SET_NULL) service = models.ForeignKey(Service, null=True, on_delete = models.SET_NULL) I have created a function-based view based on the service model where I want to render a template displaying a list of field information from each instance from the service model. See below for my views and template views.py def service_list(request): service_list = Service.objects.all().order_by('service_sku') context = {'service_list':service_list} return render(request, 'accounts/service_list.html',context) template <div class="card card-body"> <table class="table"> <tr> <th>SKU</th> <th>Service Name</th> <th>Number of Ordered</th> </tr> {% for i in service_list %} <tr> <td>{{i.service_sku}}</td> <td>{{i.name}} </td> <td></td> </tr> {% endfor %} I want to display the number of orders of each instance, considering that the order model has a foreign key from the service model. The query set would have to be like the below shown. Order.objects.all().filter(service__id =3).count() Problem is that I must specify which id of that model would be for that queryset to work. I’ve tried to put the queryset format below within the template {{Order.objects.all().filter(service__id=i.id).count()} In the template it would look like how it does below template <div class="card card-body"> <table class="table"> <tr> <th>SKU</th> … -
Uploading multiple files to model using Django form
I am learning Django and I am stuck on understanding what is going on here. I have a form that looks like this: class BugReportForm(forms.Form): title = forms.CharField() severity = forms.ChoiceField(label='Severity:', widget=forms.RadioSelect(), choices=SEVERITY_CHOICES) info = forms.CharField(widget=forms.Textarea) file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) What I am trying to do is after they click Submit on this template which displays this form, I want to store everything into a model instance. Django Docs gives information on how to do all of this I am just having a issue understanding how to do this. https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/ For example, why is there a class inside of the views.py file? Nothing even creates it? Since I am using a form I was going to use this to retrieve all the data from the form name = request.POST.get('name'). Is that a good way to do that? I am doing it that way because I need the RadioSelect. What would I need aside from the form above to capture the uploaded files correctly? -
Is it possible to replay django-simple-history up to a specific ID to restore a delete database?
The situation is: I developped a webapp using django (and especially "django-simple-history"). I have a postgres database "db01" with a history model "db01_history" which is generated/filled using "django-simple-history". I accidentally deleted everything from "db01"and, sadly, I don't have any db backup. My question is: Is there some way to replay all historical records "db01_history" (up to a specific ID) onto original database "db01" ? (In other words, is there a way to restore a db using its historical model up to a specific date/ID ?) Giving db0_history -> db01 -
Django: Override get_queryset() in UpdateView
"Project" model class Project(models.Model): company = models.ForeignKey('projects.Company', on_delete=models.PROTECT, related_name='projects') title = models.CharField('Project title', max_length=128) start_date = models.DateField('Project start date', blank=True, null=True) end_date = models.DateField('Project end date', blank=True, null=True) estimated_design = models.DecimalField('Estimated design hours', max_digits=5, decimal_places=1, validators=[MinValueValidator(Decimal('0.01'))]) actual_design = models.DecimalField('Actual design hours', default=0, decimal_places=1, max_digits=5, validators=[MinValueValidator(Decimal('0.01'))]) estimated_development = models.DecimalField('Estimated development hours', max_digits=5, decimal_places=1, validators=[MinValueValidator(Decimal('0.01'))]) actual_development = models.DecimalField('Actual development hours', default=0, decimal_places=1, max_digits=5, validators=[MinValueValidator(Decimal('0.01'))]) estimated_testing = models.DecimalField('Estimated testing hours', max_digits=5, decimal_places=1, validators=[MinValueValidator(Decimal('0.01'))]) actual_testing = models.DecimalField('Actual testing hours', default=0, decimal_places=1, max_digits=5, validators=[MinValueValidator(Decimal('0.01'))]) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-update', kwargs={'pk': self.pk, 'slug': slugify(self.title)}) @property def has_ended(self): return self.end_date is not None and self.end_date < timezone.now().date() @property def total_estimated_hours(self): return self.estimated_design + self.estimated_development + self.estimated_testing @property def total_actual_hours(self): return self.actual_design + self.actual_development + self.actual_testing @property def is_over_budget(self): return self.total_actual_hours > self.total_estimated_hours My ModelForm class class ProjectForm(ModelForm): class Meta: model = Project fields = ['actual_design', 'actual_development', 'actual_testing'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'UPDATE')) My UpdateView class class ProjectUpdateView(LoginRequiredMixin, UpdateView): model = Project form_class = ProjectForm success_url = reverse_lazy('dashboard') At the moment, my ProjectUpdateView class is replacing the decimal values indicated on the my ProjectForm class. I should increment these numerical values by the numbers indicated on the form, and … -
what's some good open source django project which uses third party API
I am looking for some good open-source Django project which is calling some rest API from the code and using the response in the project. I have something similar to implement that's why looking for help. Please suggest some good open-source projects on GitHub for the same. -
Why I passed a context is_liked in template but cannot execute the {% if is_liked %} in template?
I have passed the is_liked to the context, but the {% if is_liked %} statement didn't execute in the template, I suspect it's the issue of context_objects_name but I cannot figure out. Please help me with that. Thanks home.html (simplified template) {% for post in posts %} <form action="{% url 'like_post' %}" method="post"> {% csrf_token %} {% if post.is_liked %} <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} </form> {% endfor %} Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context=context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect('http://127.0.0.1:8000/') class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5