Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change button wording depending on url
I am looking to change the wording of a button depending on a url path. I have tried to use some {% if blocks %} but unable to get it to work. I have tried to use a if block with a url == '' but nothing has worked. This is my url in my urls.py path('client/<int:pk>/update/', PostUpdateView.as_view(), name="post-update"), {% if url == 'http://localhost:8000/client/{client_ID}/update/' %} -
django iterate over a list that is an item of a queryset
I have a list that is generated by a method on one of my models. On the home page it works wonderfully, however when I go to a detail view of one project I can access all the parts of that project as they are direct fields of the Model, but I can't access the items in the list. Model: class Project(models.Model): date_published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) area = models.ForeignKey(Area, on_delete=models.PROTECT) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) summary = models.CharField(max_length=256) others = models.CharField(max_length=128, blank=True) deadline = models.DateField(null=True, blank=True) priority = models.ForeignKey(Priority, on_delete=models.PROTECT) closed = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) @property def updates(self): updates = [] sequence_id = 1 categories = set(self.update_set.all().values_list( 'category__id', flat=True)) for cat_id in categories: a = Update.objects.filter( project=self, category__id=cat_id).order_by('added').last() if cat_id == sequence_id: updates.append(a) else: for i in range(cat_id - sequence_id): updates.append('null') updates.append(a) sequence_id = cat_id sequence_id += 1 return updates The view is simple: class ProjectDetailView(DetailView): template_name = 'project_portal/project_detail.html' queryset = Project.objects.all() and here is the dynamic url that I am using: path('project/<int:pk>/', ProjectDetailView.as_view(), name='project_detail'), As for the template, I'm lost, here is one of the things I have tried: <!DOCTYPE html> … -
How to add a checkbox column in django_tables2
I am trying to add a checkbox column so that the users of the interface can select rows and move them. How do I add the checkbox column to a table? I have found the checkboxcolumn.py file in django, but I do not know how to properly implement it into my project. Here is my code for reference. tables.py import django_tables2 as tables from .models import Model60Mm, Model120Mm, Model122Mm class Table60mm(tables.Table): class Meta: model = Model60Mm template_name = 'django_tables2/bootstrap.html' class Table120mm(tables.Table): class Meta: model = Model120Mm template_name = 'django_tables2/bootstrap.html' class Table122mm(tables.Table): class Meta: model = Model122Mm template_name = 'django_tables2/bootstrap.html' class DateTable60mm(tables.Table): shot_time = tables.Column() class Meta: model = Model60Mm order_by = '-shot_name' template_name = 'django_tables2/bootstrap.html' views.py from django.shortcuts import render from django_tables2 import RequestConfig from django_tables2 import SingleTableView from .models import Model60Mm, Model120Mm, Model122Mm from .tables import Table60mm, Table120mm, Table122mm def home(request): return render(request, 'database/home.html') def sixty(request): table = Table60mm(Model60Mm.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/sixty.html', {'table': table}) def onetwenty(request): table = Table120mm(Model120Mm.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/onetwenty.html', {'table': table}) def onetwentytwo(request): table = Table122mm(Model122Mm.objects.all()) table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/onetwentytwo.html', {'table': table}) def sixtydate(request): table = Table60mm(Model60Mm.objects.all(), order_by='-shot_time') table.paginate(page=request.GET.get('page', 1), per_page=25) return render(request, 'database/sixtydate.html', {'table': table}) sixty.html template … -
Dynamically Add Form to Django Formset
I want to dynamically add a form to my Django formset. However, on button click nothing happens. I am using form models, but I am defining most elements within the template. I know this is not proper practice, but it was how I originally created my forms and I have not had time to migrate to complete form models. However, could this be causing my issues? I have never used formsets before so any tips would be greatly appreciated! I used Dave's solution here, but I am unsure as to why my implementation does not translate accordingly. template.html <div class="container"> <div id="form_set"> <form action="{% url 'presales' %}" class="presales_formset" data-total-url="{% url 'presales_total' %}" id="presalesForm" method="post" name="presalesForm"> <div class="field"> <label class="label is-large">High Level Task List</label> </div> {% csrf_token %} {{ presales_formset.management_form }} {% for presales_form in presales_formset %} <div class="section"> <div class="field"> <label class="label">Opportunity</label> <div class="select"> <select id="select_opportunity" name="select_opportunity"> <option value="">Opportunity</option> {% for opportunity in my_opportunities %} <option id="selected_opportunity" name="selected_opportunity" value="{{ opportunity.name }}">{{ opportunity.name }} </option> {% endfor %} </select> </div> </div> <label class="label">Task Description:</label> <div class="field"> <div class="control"> <input class="input" id="task_description" name="task_description" placeholder="Task Description"> </div> </div> <label class="label">Hours</label> <div class="field"> <div class="control"> <input class="input" id="hours" name="hours" placeholder="Hours"> </div> </div> <label class="label">Engineer … -
How to save manytomany relationship in Django
Actually am trying to make an social media website in which i have an section of groups in this logged in user can create a group and other user can join it so here is my group model class Groups(models.Model): name = models.CharField(max_length = 255) slug = models.SlugField(blank=True) description = models.TextField() user = models.ManyToManyField(User, related_name='membership') created_at = models.DateTimeField(auto_now=True) def unique_slug(self): slug = slugify(self.name) return slug Here is my views.py def add_group(request): groups = Groups.objects.all() form = forms.add_group() if request.method == 'POST': form = forms.add_group(request.POST) if form.is_valid(): group = Groups() group.name = form.cleaned_data.get('name') group.description = form.cleaned_data.get('desc') groups.user = request.user.id group.slug = group.unique_slug() group.save() # finally save it. return redirect('groups') return render(request,'add_group.html',{'form':form,'groups':groups}) and here is my many to many relation table So How can i save the relationship?? -
The QuerySet value for an exact lookup must be limited to one result using slicing error in django views
please help me out, i would be appreciated!, can anyone explain what my error is? thank you :) ........................................................................................................................................................................................................ def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated: c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.filter(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form":form, } return render(request, "post_detail.html", context) -
User is not JSON serializable ee
I have this error raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type User is not JSON serializable, please help me def get_followers(self, obj): return obj.profile.followers.all() /////serializers.py//////// from django.contrib.auth import get_user_model User = get_user_model() class ProfileRetrieveSerializer(serializers.ModelSerializer): """ Serializer that represents a profile. """ queryset=User.objects.all() followers = serializers.SerializerMethodField() class Meta: model = User fields = [ 'followers', ] def get_followers(self, obj): return obj.profile.followers.all() /////////////models.py///////////////// from django.contrib.auth.models import User from django.db import models class Profile(models.Model): """ Model that represents a profile. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) followers = models.ManyToManyField( User, related_name='following', blank=True ) class Meta: ordering = ('-member_since', ) I get this error raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type User is not JSON serializable [23/Jul/2019 19:16:13] "GET /api/users/profile/ttt/ HTTP/1.1" 500 102886 -
Bad value in primary key field
I am trying to make migrations but this error appear i tried to delete data base file and make migrations but still get this error (https://i.stack.imgur.com/NPnae.jpg) -
Read csv file in django view
I am new to django, I am working of datascience project that need to develop a user interface that interact with user using Django, how I can read csv file in django view in order to some anlysis and send them to template ? -
How to get all users with individual related objects in django?
I want to output all users with their related scores user = User.objects.all() scores = user.myuser.all() Where 'myuser' is a related name of the scores model, I tried the above code but I was getting myuser is not an attribute of the objects error. -
Whats the alternative to base64 encoded images
I am currently serving base64 encoded images via my Django REST API. The URL is something like www.mywebsite.de/api/images/<id> and my Django API is responding with an HTTPResponse. I am doing this because the Images are sensible and the Clients need to authenticate therefore (sending a Token) to get the images. Unfortunately I read that base64 encoded images have a lot of downsides, some are listed here: https://medium.com/snapp-mobile/dont-use-base64-encoded-images-on-mobile-13ddeac89d7c So I am asking myself now, as a beginner: What are the alternatives? How can I serve sensitive Images without Base64 encoding? I would be thankful for any hint into the right direction. Thank you in advance :) -
How do I get a datetime object with offset from a Django ModelForm
I need to capture a date string with users UTC offset. Django returns the error 'Enter a valid date/time' every time. The browser is sending a string like this '2019-07-24 12:45:00 -05:00' I am using bootstrap_datepicker_plus, (https://pypi.org/project/django-bootstrap-datepicker-plus/) to render a DateTimePickerInput field in my Django(2.1) ModelForm. I am trying to get a DateTime value that includes a UTF offset. I can see the date coming through in my is_invalid() method of my view when I print form.data['release_date']. It comes through like this '2019-07-24 12:45:00 -05:00'. Why doesn't' Django like this date format? ModelForm class Meta: model = Post today = datetime.datetime.today() tomorrow =pytz.utc.localize(today + datetime.timedelta(1)) twoWeeks = today + datetime.timedelta(14) dateFmt = '%Y-%m-%d %H:%M:%S %z' datejsFmt = 'YYYY-MM-DD HH:mm:ss Z' fields = ['title', 'body', 'release_date'] widgets = { 'release_at': DateTimePickerInput( format = dateFmt, options={ "format": datejsFmt, 'minDate': datetime.datetime.strftime(tomorrow, dateFmt), 'maxDate': datetime.datetime.strftime(twoWeeks, dateFmt), }) } Settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True DATETIME_INPUT_FORMATS += ('%Y-%m-/%Y %H:%M:%S %z',) CreateView def form_invalid(self, form): print(form.data['release_at']) print(parse_datetime(form.data['release_at'])) output from CreateView 2019-07-24 12:30:00 -05:00 None -
How to filter a list of displayed elements in django with a dropdown value
Right now I have a list of forms being displayed by Django: {% for form in forms %} <form method="post" class="{{ form.css_class }}"novalidate> {% csrf_token %} {% include 'bs4_form.html' with form=form %} <input type="hidden" name="selected_form" value="{{ forloop.counter0 }}"> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endfor %} I also have a dropdown being rendered above the forms: <label>Choose a component to modify: <select class="rule-component" name="component"> <option value="">Select One …</option> <option value="0">Option 0</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> </select> </label> My question is, how would I go about displaying no form when the page is entered, and a single form that corresponds with the dropdown value when that is selected? I've attempted something with JavaScript, but I'm not very familiar with it and I'm not sure how to get this to interact with the django templating language. The code below allows me to log the form element I want to display by linking it with the forloop.counter: <script type="text/javascript"> const formElement = document.querySelector(".rule-component") formElement.addEventListener('change', (event) => { const selectElement = document.querySelector("form input[value='" + formElement.value + "']").parentNode; console.log(selectElement) const result = document.querySelector('.result'); result.textContent = `You like ${selectElement.className}`; }); </script>``` -
How do I implement toast messages in Django?
I am trying to implement toastmessage in my django project. I followed this link https://pypi.org/project/django-toast-messages/ and made all the files and did everything mentioned but I cannot get a toastmessage no matter what. Please Help. -
Display single record from app to home page of the website in Django
I am trying to display record on the website home from the app. In the admin interface records are getting displayed but on the website home its not working. Site Structure Site structure website --MyWebsite ----templates --alert ----templates Code at alert/view.py def weather_single(request): weatheronly=Weatherreport.objects.last() return render(request, '../MyWebsite/templates/sidebar_left.html', {'weatheronly':weatheronly}) Code at MyWebsite/templates/sidebar_left.html {% for wresult in weatheronly %} {{ wresult.temp }} {{ wresult.forecast }} {% endfor %} Currently not getting any error message and no results at all. -
How to create a Django queryset from a list of values
I am given a list like so a = [1, 2, 3, 4] This list matches the id's stored in a django model we will call Books. I am trying to return a queryset of Books with the id's in the list. I am thinking of using Q objects and grab them by doing something like this Books.objects.filter(Q(id = 1) | Q(id=2) | Q(id=3) | Q(id=4)) Now i would just use the index like this: Books.objects.filter(Q(id = a[0]) | Q(id=a[1]) | Q(id=a[2]) | Q(id=a[3])) BUT, These list will be varying in length up to around 30 and hardcoding the index wont work, and hardcoding the query won't satisfy the varying length of lists. Is it possible to go this route? And if so, how can I accomplish returning the books with the id's that match the list? -
CSRF Token Problem with Dev Environment Django and React, Redux, Axios
I can't do a POST request via axios to my Django REST Framework API because I'm not able to get a CSRF Token. I can't render it with { % csrf_token % } because I'm developing the Front- and Backend in different Environments. Is there any way to get a CSRF Token, at least for the Dev-Environment, without rendering the page with Django? Or am I getting it right that this would make the whole idea of the CSRF Token Protection pointless? I'm using Webpack, Babel etc. for my Frontend Dev-Environment and a Docker Container for the Backend Django REST Framework Environment. I already tried to get the CSRF Token by simply sending a GET Request when the Frontend is loaded, but can't figure out to read it from the Response. I also tried disabling the CSRF Protection temporarily for the Dev-Environment but didn't find a way to disable it for the REST Frameworks Auth Views with csrf_exempt(). -
Do not display the list of the most viewed articles in the template
I want the article to appear first and then the article on the number of views. I make a list of the most popular articles on the site and so that the list of articles is displayed next to each other in order but for some reason they are not displayed in the template . I have a view model and articles should be sorted by it the more views views.py class ArticleIndex(ListView): model = Articles template_name = 'news/posts.html' paginate_by = 6 def article_tops(self): article_top = Articles.objects.all().order_by('-view') return {'article_top':article_top} posts.html {% for article in object_list %} <h1> {{ article_top }} </h1> {% endfor %} -
(Django) How to make the User FK register the User name instead of a Code (int)
In my models.py, I have the request_author field defined as: request_author = models.ForeignKey( User, on_delete = models.CASCADE ) This makes the request_author field to be registered with a user code (int) number in the API database. However, I would like to have it as the user name. How do I do that? -
Auth0 logs-in the incorrect user on custom django authentication backend
I'm using the Django Admin page to manage some basic CRUD operations of a large database. I've integrated Auth0 for login/authentication, which also bypasses the admin login page, and have written a custom authentication backend based on the Auth0 documentation for Django. Logins sometime work properly, redirecting to the Auth0 social auth sign in, requiring email and password. However, at other times, the login page is bypassed and redirects to the admin landing page, logged in as a user other than myself (I work with the user that's getting auto-logged, and he has never logged in on my local machine but is in the Auth0 and application database as a user). Auth0 logs for the application don't provide any insight to the problem. I have tried to enable the authentication portion using both the Auth0 provided guide (which uses the 'social_django' app and a custom authentication backend application) and the 'allauth' django application, both yielding the same results. I've also set the JWT token for the application to 60 seconds to ensure it expires before another login is attempted. I'm unsure if this is an issue with sessions data persisting. I have not set up a sessions backend but do … -
DjangoAdmin has_delete_permission executed from another Admin Class
I have two admin models, one is called Animal and another one is called Person. Each one have have their own has_delete_permission on their admin classes. In my logic, the instances of Animal can't be deleted if the animal is a dog. I am using has_delete_permssion for that. The code I am using is listed below. class Animal(models.Model): sound = models.CharField(max_length=25, blank=True, null=True) class Person(models.Model): sound = models.CharField(max_length=25, blank=True, null=True) class AnimalAdmin(admin.ModelAdmin): model = Animal def has_delete_permission(self, request, obj=None): if request.POST and request.POST.get('action') == 'delete_selected': animals = Animal.objects.filter( id__in = request.POST.getlist('_selected_action') ) print (animals) return True class PersonAdmin(admin.ModelAdmin): model = Person def has_delete_permission(self, request, obj=None): return True admin.site.register(Animal, AnimalAdmin) admin.site.register(Person, PersonAdmin) When I try to delete a Person instance that have the same ID of some Animals the instances of Animals are printed. This could be a serious problem if I was doing some logic like changing the database or showing a message to the user. The point is why has_delete_permission methods of different classes are also executed? -
Django reverse foreign key
I'm using python/django for 1 month now and I need help because I can't find any similar questions that has the answer I was looking for. I have Worker model and Job model. A Worker can have many jobs. I need to query the latest job that the Worker has. class Worker(models.Model): name = models.CharField(max_length=128) class Job(models.Model): worker = models.ForeignKey(Worker) type = models.CharField(max_length=64) position = models.CharField(max_length=64) location = models.CharField(max_length=128) start_date = models.DateField() I am currently using this sample code. The problem is that this returns similar Worker objects including its previous jobs. I just want to query the Worker with the latest job location and start date. for employee in Job.objects.all(): print(employee.worker, employee.location, employee.start_date) Sample Output (A, north, 2018-01-21) (A, south, 2018-09-13) (A, east, 2019-05-11) (B, west, 2019-01-01) Is there a way to use a for loop to a query like Worker.job_set.all() to have this expected output (A, east, 2019-05-11) (B, west, 2019-01-01) Hope you can help a newbie like me. Thank you in advance! :) -
How to pass a Django variable in HREF "mailto:" tag
I want to allow the user to click on a button in order to open his mailbox and send an email to the specific contact. I know in HTML I can use the tag <a href="mailto:example@gmail.com">, when the users clicks that tag, his mailbox will be open and the receiver will be "example@gmail.com". However I need a dynamic href which changes depending on project.user.email I would like to have something like that: <a href="mailto:{{project.user.email}}"></a> but naturally, this is not working. Is there a way to pass to a HREF mailto tag a Django variable? -
authenticate() is not running while adding new authentication backend
i' m trying to add a new authentication backend to my project with the following versions and code snippets: django: 2.2.1 python: 3.5.2 mysql-server: 5.7 settings.py ... AUTHENTICATION_BACKENDS = ['common.backends.MyOwnAuthenticationBackend'] common/backends.py from django.conf import settings from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class MyOwnAuthenticationBackend(ModelBackend): print('MOAB') def authenticate(self, username=None, password=None): print('AUTH') ... def get_user(self, username): print('GETUSER') try: return User.objects.get(pk=username) except User.DoesNotExist: return None While trying to log in i get back the MOAB, but none of the AUTH or GETUSER strings. What can be the reason for it? The main urls.py contains the following for authentication: urls.py from common import views as common_views from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views from django.urls import path ... url(r'^accounts/login/$', views.LoginView, name='auth_login'), ... . What did i miss? I read many questions and posts about it on the Internet, but i can' t figure out why the authenticate() method is not called at all. -
Invisible field of AbstractUser - Django, models.py
I use the first time class AbstractUser in Django 3+. Therefore, I create my custom user model with an obligatory field test from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): test = models.CharField(max_length=100) def __str__(self): return self.email then it modifies my settings.py file ... AUTH_USER_MODEL = 'app.CustomUser' ... I create migrations, next I login in to django admin and my field is still not visible. How to add a test field to my user so that it is always required and visible in Django / admin. Any help will be appreciated. My admin.py class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'test'] My forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email', 'test') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'test') admin.site.register(CustomUser, CustomUserAdmin)