Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing variable through Django template url tag
I am trying to pass a variable through the Django template url tag with little success. My path in the urls.py: path("viewListing/<int:listingID>", views.bookListing, name="viewListing") In the template, I am using javascript to generate the listingID with a for loop. for(j=0; j<5; j++){ var thisID = (data[j].id) imgA.href = "{% url 'viewListing' thisID %}"; } However, I am getting this error Reverse for 'viewListing' with arguments '('',)' not found. 1 pattern(s) tried: ['viewListing/(?P<listingID>[0-9]+)$'] If I pass a number instead of thisID, for instance 1, the code works fine. So my question is, how can I make this work with a variable. -
How to serve a django server which running on http://127.0.0.1:9090 on www.website.com/api/ using apache?
I am running a Django server which I am using as a backend framework and for creating the API calls for the project. The Django server is running on the IP address 127.0.0.1:9090. Now apache server is handling my website traffic for www.careeranna.com (configured using a cPanel) ServerName www.careeranna.com DocumentRoot /home/roshan/public_html/ ServerAdmin webmaster@careeranna.com UseCanonicalName Off ## User roshan # Needed for Cpanel::ApacheConf <IfModule userdir_module> <IfModule !mpm_itk.c> <IfModule !ruid2_module> <IfModule !mod_passenger.c> UserDir disabled UserDir enabled roshan </IfModule> </IfModule> </IfModule> </IfModule> How should I go about it? -
Could I improve this django model structure?
I am attempting to make an expense reporting website. I incur expenses at work which I report in an excel spreadsheet sent via email attachment. Each spreadsheet can include up to 15 expenses. The ideal website would accept user information (for populating the areas of the spreadsheet that don't change, their expenses, export the user inputs into a spreadsheet, attach a receipt photo and send as an email attachment. I'm aware there are apps that do this, but I've chosen this as my project to continue learning Python, web development and give me something useful (if I can make it, which is feeling unlikely right now). I've gone through the MDN Django tutorial (local library). My focus now is on the models. I am using Django and would be grateful for feedback regarding my initial model structure. I feel like my model structure should be simpler than I'm making it, but I don't know how to reduce it. Specifically, I'm wondering if I need to have a separate model for each expense and a model for the report as a whole. Or can I just have a report model including the fields that I currently have in the expense model? … -
NoReverseMatch with slug variable, works with hard coded value
I'm updating some code from a Django 1.11 project to Django 2.x, and in one template (contacts list view with FK back to Clients), I am getting "NoReverseMatch" since it is not seeing the slug value in the URL parameter. If I hard code the value it works, and the same variable displays the proper value for each record if I just display as text on the page. I don't see why the variable is getting dropped, but probably something stupid I've done. This works: <td class=""> <a href="{% url "clients:view" slug='sony' %}"> {{ contact.client.slug }} </a> </td> This gets the NoReverse Error <td class=""> <a href="{% url "clients:view" slug=contact.client.slug %}"> {{ contact.client.slug }} </a> </td> In both cases, the variable {{ contact.client.slug }} returns the proper data. urls.py: import ... app_name = "clients" urlpatterns = [ path("ajax/validate_client_code", validate_client_code, name="validate_client_code"), path("", ClientListView.as_view(), name="list"), path("new/", ClientCreateView.as_view(), name="new"), path("edit/<slug:slug>/", ClientUpdateView.as_view(), name="edit"), path("delete/<int:pk>/", ClientDeleteView.as_view(), name="delete"), path("<slug:slug>/", ClientDetailView.as_view(), name="view"), ] Can anyone point out my mistake? Has to be something really simple, but I just cant see it. -
Get all possible values of a M2M field in a model
I have three models : class Country(models.Model): name = models.CharField(max_length=200) class City(models.Model): name = models.CharField(max_length=200) country = models.ForeignKey(Country,on_delete=models.CASCADE) class Restaurant(models.Model): city = models.ManyToManyField(City) In my database, there is 120 cities and 25 countries. But the restaurants created are located in 20 cities only. Problem : I need a query to retrieve all the cities where my restaurants are located. And another query to retrieve all the countries where my restaurants are located. -
Django REST nested object serializers
I have the current api as set below, and my intention is to make it to show desired output. I'd like to add age and nationality as shown below(see Desired output) to the type as nested, but it seems to only show in straight format not nested. What's best way to make it nested? "type" : [ { "age" : "27", "nationality" : "usa" } Current API [ { "name" : "Jay", "school" : "college", "type" : "usa" "age": "27" "nationality": "usa" }, ] Desired API [ { "name" : "Jay", "school" : "college", "type" : [ { "age" : "27", "nationality" : "usa" }, ] } ] Serializers.py class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = ("name", "school", "type", "age", "nationality") def update(self, instance, validated_data): instance.name = validated_data.get("name", instance.name) instance.school = validated_data.get("school", instance.session) instance.type = validated_data.get("type", instance.session) instance.age = validated_data.get("age", instance.session) instance.nationality = validated_data.get("nationality", instance.session) instance.save() return instance models.py class School(models.Model): name = models.CharField(max_length=255, null=False) school = models.CharField(max_length=255, null=False) type = models.CharField(max_length=255, null=False) age = models.CharField(max_length=255, null=False) nationality = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.name, self.school) views.py class ListSchoolView(generics.ListCreateAPIView): """ Provides a get method handler. """ queryset = School.objects.all() serializer_class = SchoolSerializer -
How to override existing image uploaded by user
models.py from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) There is multiple users so i want it to delete the previous picture that is on the profile. As of right now when you upload a picture it will keep the old one as well which takes up space. -
Django CreateView form not submitting
My form has been working fine, until around 2 - 3 hours ago and I am not sure when it went wrong since I haven't tested it every time I made a change. When I press submit to create the page and make it live, it doesn't do anything at all. HTML: {% extends 'public/base.html' %} {% load staticfiles %} {% load crispy_forms_tags %} {% block head %} <link rel="stylesheet" type="text/css" href="{% static "public/css/create-post.css" %}" /> {% endblock %} {% block content %} <div class="container"> <div class="form-create"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-success" value="Publish"> </form> </div> </div> {% endblock %} {% block script %} tinymce.init({ selector: '#id_text' }); $("#id_created_date, #id_published_date").flatpickr(); {% endblock %} Views: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from .models import Post, Category from django.views.generic import ListView, DetailView, CreateView, UpdateView # Create your views here. class IndexView(ListView): model = Post template_name = "public/index.html" class PostEdit(object): model = Post fields = '__all__' success_url = '/' class PostCreateView(LoginRequiredMixin, PostEdit, CreateView): success_url = '/' fields = ['title', 'text', 'category', 'image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, PostEdit, UpdateView): success_url = '/' fields = ['title', 'text', 'category', 'image'] class … -
image not saved to the database
I have a model with Usuario where the profile foto goes and it saves perfectly in the database, so to be able to add more images as if it were a gallery, I created another model called Gallery, I copied the same specificiation of what was already working in the model Usuario, however he is not saving the photos in the database, and I do not know where I am going wrong. I appreciate any help. and I need the Gallery model to receive the foreign Usuario key views.py def gallery(request): gallery = Gallery.objects.all() form = GalleryForm() data = {'gallery': gallery, 'form': form} return render(request, 'gallery.html', data) def gallery_novo(request): if request.method == 'POST': form = GalleryForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sistema_perfil') else: form = GalleryForm return render(request, 'gallery.html', {'form': form}) models.py class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, blank=False) user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) email = models.EmailField(blank=False) foto = StdImageField( blank=False, variations={ 'large': (600, 400), 'thumbnail': (100, 100, True), 'medium': (300, 200), }) telefone = models.CharField(max_length=20, blank=False, verbose_name="Celular") cpf = models.CharField(max_length=19) data_nascimento = models.CharField(max_length=8, blank=False, verbose_name="Data de nascimento") sexo = models.CharField(default='M', max_length=2, choices=SEXO_CHOICES) pet = MultiSelectField( max_length=100, choices=PET_CHOICES, verbose_name="Selecione seus pets") endereco = models.CharField(max_length=50) numero … -
Django with Vue Tutorial
I know this probably isn't best place to ask this question but I am desperate. I made most of stuff I needed in Django, and now I need to figure out Vue. The problem I have is that I can't find any tutorial on how to pass data from Django to Vue. I was planning on using Vuetify, but I am open to suggestions. I am also new to Vue, so I don't understand it yet, can you refer me to some tutorial that will help me? Thank you -
Is it possible to integrate django-filebrowser to TinyMCE 5?
I have tried different ways, but nothing works for me. TinyMCE 5 works in admin. Filebrowser also works for FileBrowseField. Now I need a file manager to browse inside editor. Is it possible to integrate django-filebrowser-no-grappelli==3.7.5 to TinyMCE 5? in settings.py I have (currently installed django-tinymce==2.7.0) FILEBROWSER_SHOW_IN_DASHBOARD = True FILEBROWSER_DIRECTORY = '' FILEBROWSER_EXTENSIONS = { 'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff'], 'Video': ['.mp4', '.webm','.ogg'], } Thank you for your help. -
django foreign key table fields in html template
I have two tables(article,comment) are related one to many relashionship using a foreign key. I would have want in the html template list and some fields from the table one article but that I create don't work ,here the code : models.py class article(models.Model): name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=254) age = models.CharField(max_length=254) def __unicode__(self): return str(self.id) class comment(models.Model): field_1 = models.CharField(max_length=100, blank=True, null=True) field_2 = models.CharField(max_length=254) field_3 = models.CharField(max_length=254) field_fk= models.ForeignKey('article', blank=True, null=True) def __unicode__(self): return str(self.id) views.py def index(request): apps = article.objects.all() comments = comment.objects.all() return render(request, 'index.html', {'apps':apps,'comments':comments}) html template : {% for b in apps %} <p>{{ b.field_1 }}</p> <p>{{ b.field_2 }}</p> <p>{{ b.field_3 }}</p> {% for c in b.field_fk.comments %} <p>{{ c.name }},{{ c.last_name}},{{ c.age}}</p> {% endfor %} {% endfor %} in my example in the template don't show me name , last_name and age is empty the paragraph -
List of elements per category within for loop
I have a case, where on my template view I would like to display list of all objects (Issues) and categories (Sprints). I already applied also another filtering to display Issues that belongs to particular Project. I've managed so far to display Sprints and within each Sprint I am displaying list of issues. How can I apply additional filtering on issues, that only issues belongs to particular sprint will be displayed? Final result should be to display list of all issues divided per sprint. My code below: #views.py class ProjectBacklogView(DetailView): model = Project template_name = 'project-backlog.html' context_object_name = 'backlog' def get_context_data(self, **kwargs): context = super(ProjectBacklogView, self).get_context_data(**kwargs) context['project'] = Project.objects.all() context['issue'] = Issue.objects.all().order_by('sprint') # context['epic'] = Epic.objects.all() # context['initiative'] = Initiative.objects.all() context['sprint'] = Sprint.objects.all() return context # template.html {% extends 'base-project.html' %} {% block content %} {% for sprint in backlog.sprint_set.all %} <h4>{{ sprint.name }}</h4> <div id="simpleList" class="list-group" style="margin-bottom: 2%;"> {% for issue in backlog.issue_set.all %} <div class="list-group-item"> <div style="float:left;"><strong><a href="{% url 'issue-edit' issue.pk %}">{{ issue.title }}</a></strong></div> <div style="float: right;"><a href="#" class="btn btn-success btn-circle btn-sm"><i class="fas">{{ issue.remaining_estimate }}</i></a></div> <br /><br /><hr style="border-top: dashed 1px;"></hr> <div style="float: left;"><small>Assignee: <strong>{{ issue.assignee }}</strong></small></div> <div style="float: right;"><small>Initiative: <strong>{{ issue.initiative }}</strong></small></div><br /> <div style="float: left;"><small>Priority: <strong>{{ … -
PasswordResetConfirmView is getting skipped and PasswordResetDoneView is shown directly
I was trying to use the standard django password reset, but instead of getting directed to the PasswordResetConfirmView I'm directly directed to the PasswordResetDoneView the code is below (I didn't put the html as it doesn't really matter and would just make the question longer) urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('password-reset/',auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'),name='password_reset'), path('password-reset-confirm/<uidb64>/<token>',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm.html'), path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done') ] -
django NameError: name 'form_class' is not defined
****this is my views.py file**** from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages def signup(request): if request.method =='POST': form = form_class(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') messages.success(request, f"Account created for {first_name}!") return redirect('main-profile') else: messages.error(request, "Error") return render(request, 'first/signup.html', {'form': form_class()}) my html code is in image I'm using my own written form notdjango created UserCreationForm and I gave my form class name "form_class". Is it right? I don't know Plz help. this is my office project and i need to submit on monday i'm new to django -
Django docker - could not translate host name "db" to address: nodename nor servname provided, or not known
I'm relatively new to Django and Docker and am following a tutorial to build a mini application. However, I'm getting stuck with the following error: django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known My docker-compose file looks as follows: version: '3' services: db: image: 'postgres' ports: - '5432' core: build: context: . dockerfile: Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 ports: - '8000:8000' volumes: - .:/code depends_on: - db links: - db:db My settings.py file contains the database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } I've seen the post here and here however both have not fixed the issue. Would appreciate some guidance. Thanks. -
Accessing model instance from validator
How would I access the instance of the model that is being validated from within the validator for a specific field? models.py def question_instances(value): #validator # not sure how to get model instance within this function industry = model_instance.industry questions = Question.objects.filter(industry=industry) if questions.count() > 3: raise ValidationError('Too many questions for this industry') class ExampleQuestion(models.Model): industry = models.ForeignKey(Industry, on_delete=models.CASCADE) question = models.CharField(max_length=200, validators=[question_instances]) def __str__(self): return self.industry.industryname -
Django kwarg always 'pk'?
I'm working on a django application with django rest framework. I am trying to filter the data returned, using a url like so: router.register(r'^api/rates/(?P<name>\w+)', views.RateViewSet) Here is the view: def get_queryset(self): if 'name' in self.kwargs: n = self.kwargs['name'] return Rates.objects.filter(name=n) However for some reason the first kwarg is always named 'pk' no matter what i do. Even though I set it to name in the regex url. But when I add a second kwarg with something like api/rates/one/two, than the entire thing (one/two) is attached to the name key. Am I doing something wrong? How can I fix this? -
cleaned_data not picking up updated integer values from form in django
I am a bit new to Django but was able to find all the answers for my problems except this one. I wanted to submit a form that had both integer fields and text area fields So with usual form submission, I was able to get data from the form and use the form.cleaned_data to save the form When I wanted to update the same form I retrieved that specific table data and loaded it into form for easy changes. But when I tried to resubmit the form by changing the values, the form was sending previous data of integer fields that I fed to form rather than the changed values. But it is sending the updated text area values as usual. This is the image when data is retrieved and fed into the form. Before editing And this is After I editing the formAfter editing printed request.post data after I submited the form with updated values It returns previous values rather than updated values <tr><th><label for="id_Number_of_existing_programmes">Number of existing programmes:</label></th><td> <input type="number" name="Number_of_existing_programmes" value="5" required id="id_Number_of_existing_programmes"></td></tr> Here number is stored in value rather than inside the html tags with is usually the case with text fields like this <textarea name="Department_center" … -
I want show user's products in related user's profile with template tags in Django
I render user's profile page with view.py (birth date bio etc.). But I should show products about profile page's owner (profile owner's products). I builded custom user model and I couldn't add related products in this model. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=55, blank=True, null=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) products = models.ManyToManyField(Product, blank=True, related_name="Products") followers = models.ManyToManyField(User, null=True, blank=True, verbose_name="Followers", related_name="Followers") country = models.CharField(max_length=30, blank=True) job = models.CharField(max_length=30, blank=True) def save(self, *args, **kwargs): print(self.user.username) if not self.slug: self.slug = self.get_slug() print(self.slug) print(self.user.username) super(Profile, self).save(*args, **kwargs) def __str__(self): return "{username}".format(username=self.user.username) def get_slug(self): slug = self.user.username.replace("ı", "i") return slugify(slug) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() views.py @login_required def profile(request, slug): # detail = Profile.objects.filter(id=id) # profile_detail = Profile.objects.filter(slug=slug) profile_detail = get_object_or_404(Profile, slug=slug) context = { "profile_detail": profile_detail } return render(request, "profile_pages/profile.html", context) user_template_tags.py @register.simple_tag def user_products(request): user = request.user products = Product.objects.filter(seller=user) return products -
Unittests for Django Filter
How to test django filters? I have I view where I use restframework djangofilters and I don't know how to test them. Appreciate any help this is my products views.py class ProductFilter(django_filters.rest_framework.FilterSet): # to search case insensitive class Meta: model = Product fields = ['title', 'color', 'price'] filter_overrides = { models.CharField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'icontains', }, } } class ProductsList(generics.ListAPIView): queryset = Product.objects.all().exclude(quantity=0).order_by('-id') serializer_class = ProductSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filter_class = ProductFilter # getting items from child categories too def get_queryset(self): queryset = Product.objects.all().exclude(quantity=0) category = self.request.query_params.get('category', None) if category is not None: queryset = queryset.filter( Q(category__parent__title__icontains=category) | Q(category__title__icontains=category) | Q(category__parent__parent__title__icontains=category) ).distinct() return queryset -
Validate user on update request in Django REST framework
I want to have an API where a user can update his own listings. Currently any authenticated user can update any listing which I found using Postman. I want to validate the user so that the API returns an error as a response if the user is not trying to update his own listing. Here is my code: # serializers.py class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing fields = '__all__' # api.py class ListingViewSet(ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly] serializer_class = ListingSerializer def get_queryset(self): return Listing.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) # urls.py router = routers.DefaultRouter() router.register('api/listings', ListingViewSet, 'listings') urlpatterns = router.urls -
python return number of times a licence used under specific server at specific time from a csv
i have a csv file, named user_log.csv. i need to count that how many times each licence on specific server and on every specific time is being used. The log file csv is like this and the code that i have written is following file = open('/user_log.csv', "r") reader= csv.reader(file) time={} for row in reader: licence_name = row[2] server = row[1] if licence_name in time.keys(): if server in licence_name: time[row[2]][row[1]]['count'] += 1 else: time.setdefault(licence_name,{}).setdefault(server,{})['count'] =1 else: time.setdefault(licence_name,{}).setdefault(server,{})['count']=1 return render(request, "stats.html", {'no_of_line':time}) the output i get is something like this How shall I do it? -
A slow-loading video in the main bootstrap slider, after adding static file on amazon S3.in django app
My video clip (in Djando app) in the purchased bootstrap theme slowly loads after adding static files to amazon S3. Every 2 seconds there is a pause in loading. How to solve such a problem? Are there special buckets to handle such files? Reduce videos? Change the file type? How to verify if other users are displaying well. -
How Do I Display Datetime In User's Timezone in Django?
These answers didn't help: Getting correct local time zone to display for end-users in Django web app Django different timezones in same application All datetime data is stored in UTC in my database. I would like my users to see the datetime in their local timezone instead of UTC. I've tried the code below: settings.py TIME_ZONE = 'UTC' USE_TZ = True views.py from django.shortcuts import render from home_app import models from django.utils import timezone import pytz def home_view(request): timezone.activate(pytz.timezone('Asia/Kolkata')) sample_queryset = models.TimeModel.objects.all() return render(request, 'home/home.html', {'sample_queryset': sample_queryset,}) home.html {% for row in sample_queryset %} {% load tz %} {% localtime on %} {{ row.time }} {% endlocaltime %} {% endfor %} However, after all, the same UTC time from the database is being printed. Other details: Django 1.11 SQLite (for now; will use Postgres in production) Python 3.6.8