Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter data in Django defends on the date input
I want to filter data with date range from the user input('Smoke_emission_date' field) + 2 months and show in the table. I use __range and relativedelta but invalid syntax, How to do? Views.py field = 'Smoke_Emission_Date' obj = VM.objects.First() field_object = VM._meta.get_field(field) field_value = field_object.value_from_object(obj) context = { 'jan_list': VM.objects.filter(Smoke_Emission_Date__range=field_value + relativedelta(months=+2)) } -
url parameter for django url pattern is not passed properly
An error occurred for the parameter being passed incorrectly Is that the action setting is wrong? Is the url parameter set incorrectly? I'm not sure if it's wrong with the view. if you kow what is reson thanks for let me know code: <form method="post" action={% url "wm:new_comment_for_skilpage" user_name=page_user category_id=category_num %}>{% csrf_token %} and url pattern is this path('new_comment_for_skilpage/<str:user_name>/<int:category_id>/' , views.new_comment_for_skilpage, name="new_comment_for_skilpage"), view is this def new_comment_for_skilpage(request, pk): user_name = request.GET.get('user_name') category_id = request.GET.get('category_id') if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.author = user_name comment.category_id = category_id comment.save() return redirect('/wm/myshortcut/'+user_name+"/"+category_id) else: return redirect('/wm/myshortcut/'+user_name+"/"+category_id) error: TypeError: new_comment_for_skilpage() got an unexpected keyword argument 'user_name' -
READ CSV FILE UPLOADED THROUGH DJANGO FORMS WITHOUT SAVING THE UPLOADED FILE AND CONVERT IT INTO A DICTIONARY
def upload_student_list(request, event_id): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES["file"] decoded_file = file.read().decode('utf-8').splitlines() csv_dict_reader = csv.DictReader(decoded_file) for x in csv_dict_reader: print(x) on printing x i am getting a null string. I am new to django .please try to solve my problem -
Django model relationship with circular relationship
I am new to Django and trying to understand the model relationships, here is my use case, I have a Creator object which can create multiple listing under a category. Category can have multiple listings from multiple Creators. Creator -- Creates a Listing about a service -- under a Category or multiple Category I am trying to find the thought process behind picking the correct relationship while defining this kind circular relationship. Which one of the model should go first is it Category which is first and Creator second and Listing at the end, is Creator,Category and Listing all belongs to a Many to Many relationship, if then how are they linked? -
Filter Django queryset by null value but if not null, limit by one result of that value
I have model Task that has a foreign key to Project that may be null (Task belongs to 1 or 0 Projects and one Project has many Tasks). I would like to implement a view where I show all Tasks that belongs to 0 Projects plus just one Task of each Project. I have tried something like this: def get_queryset(self): q1 = Task.objects.filter( project__isnull=True, user=self.request.user, folder=Folder.objects.get(name='Ready')) q2 = Task.objects.filter( project__isnull=False, user=self.request.user, folder=Folder.objects.get(name='Ready'), ).order_by('project').distinct('project') return q1.union(q2) -
DRF: Accessing Object in Serializer __INIT__()
How to Access Object in Serializer init() method, when I am using viewsets.ModelViewSet as View? -
Django Annotate With Sum And Min/Max At The Same Time In Search Form
I have a page of courses which are search results of a course search form. In the current code below, it currently allows a user to type in the min and max views and return courses that contain that Course "views" criteria. It incorrectly does this with the Course "views" field/column when it should be doing it on the Lesson "views" field/column I want to annotate (or subquery?) the sum of all lesson views but make sure a user is able to find all courses with lesson views that fall under their min/max search critera? Valid annotate that gets the total sum of all lesson views in a course: Course.objects.annotate(foobar=Sum("lesson__views")).order_by("foobar") Tried doing: if min_views_query: qs = Course.objects.annotate(foobar=Sum(Min("lesson__views"))).order_by("foobar") if max_views_query: qs = Course.objects.annotate(foobar=Sum(Max("lesson__views"))).order_by("foobar") Error: django.core.exceptions.FieldError: Cannot compute Min('Sum'): 'Sum' is an aggregate Code: Courses Forms.py: class CourseForm(forms.Form): min_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off','id':'min_views', 'type':'number', 'min':'0', 'placeholder': '0'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) max_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'max_views', 'type':'number', 'min':'0', 'placeholder': '1000000'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['min_views'].label = "Min Views:" self.fields['max_views'].label = "Max Views:" Courses Views.py: class CourseListView(ListView): model = Course def get_queryset(self): qs = super().get_queryset() self.form = form = CourseForm(self.request.GET) if form.is_valid(): min_views_query … -
Django display user form validation error message when inherited from UserAdmin
I am using the django User model with profile to extend the User with few more attributes. I require to ensure unique email id across the users in the User table. from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.admin import UserAdmin class UserForm(UserAdmin): class Meta: model = User fields = "__all__" readonly_fields = ('date_joined',) def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): raise forms.ValidationError(u'Email addresses must be unique.') return email This validation message is not displayed in the User form. The custom user admin is defined as class CustomUserAdmin(UserAdmin): def save(UserForm, commit=True): return super(UserForm, self).save(commit=False) if User.objects.filter(email=email).exists(): raise forms.ValidationError(_("Email already exists ya"), code='invalid') inlines = (ProfileInline, ) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) This validation message is seen in the traceback in debug mode and not in the UserForm. Require the message to show the error in the UserForm. I understand that there are 2 forms viz. UserCreationForm, UserChangeForm in the django auth. Using django 3.0, python 3.7 -
How to run a worker (continuously) on Azure App Service
I'm running a Django app on Azure App Service and planning to use django-background-tasks (or Django-Q) to run background tasks. Whichever I choose, I will need to run some sort of workers after deploying the app to Azure. For django-background-tasks, I will need to run python manage.py process_tasks For Django Q, I will need to run python manage.py qcluster And this is all fine if I run it from my computer's command prompt, but what about App Service? Is there anyway I keep these workers running? -
Remove "ADD NEW ITEM" Button Django Admin
How can i remove or hide "add new item" button from django admin panel -
Django Model formset problem with dynamically deleting the fields using jquery
Here, I have used a modelformset where i added a jquery to add and delete fields dynamically. When i try to add multiple items it works and saves the data as well but when i delete a field the rest of the fields after the delete field does not get save. The problem here is only when adding the form. The code works fine when editing the form. Here, i am using the same template the render both add and edit form. $(document).ready(function () { function updateEmptyFormIDs(element, totalForms){ var thisInput = element // get current form input name var currentName = element.attr('name') // replace "prefix" with actual number var newName = currentName.replace(/__prefix__/g, totalForms) // console.log(newName) // update input with new name thisInput.attr('name', newName) thisInput.attr('id', "id_" + newName) // create a new form row id var newFormRow = element.closest(".form-row"); var newRowId = "div_id_" + newName newFormRow.attr("id", newRowId) // add new class for basic graphic animation newFormRow.addClass("new-parent-row") // update form group id var parentDiv = element.parent(); parentDiv.attr("id", "parent_id_" + newName) // update label id var inputLabel = parentDiv.find("label") inputLabel.attr("for", "id_" + newName) // return created row return newFormRow } function deleteForm(prefix, btn) { var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); if … -
Django websocket stopping a running script?
I am building a Django app that run a long running function and display the results to the user using websocket in realtime. What I need help with is that, when the user press the stop button it should stop the currently running code. Any help will be appreciated. -
Django creating a database where table can have variable columns
I'm trying to create an applications where admin should have an option to create more columns, in the future. To achive this, I've made following models : class extendeduser(models.Model): def __str__(self): try: return self.user.email + ' : ' + self.user.first_name+' '+self.user.last_name except: return self.user.first_name+' '+self.user.last_name lid = models.CharField(max_length= 100) user = models.OneToOneField(User,on_delete=models.CASCADE) class ProfileFields(models.Model): def __str__(self): return self.field field = models.CharField(max_length=100) class FieldValues(models.Model): user = models.ForeignKey(extendeduser, on_delete=models.CASCADE) field = models.ForeignKey(ProfileFields, on_delete=models.CASCADE) value = models.TextField() The Idea is that Admin will add fields as rows like 'semester','year' and then I'll store their values in FieldValues table. Here the problem is that when I add FieldValues, the user_id which it takes is the row number of the user from the User table and not the id which is the primary key. So, how do I solve it? Alternate solutions will also be helpful on how can I achive my goal. -
How To Add/Modify An Imported App's Logic
Ive installed django-notifications and am wanting to change some of the packages behavior. At the moment, when a user views notifications at '/notifications/' or '/notifications/unread/' the notifications remain 'unread'. If I type '/notifications/mark-all-as-read/' into the url they are marked as 'read'. I am wanting the notifications to be marked as 'read' once a user views them in either '/notifications/' or '/notifications/unread/'. I am guessing id need to change the views.py in order to do this. I have never changed the logic of an intalled package before and was reading on how to do it. It seems I must override the view, such as like this: from notifications.views import AllNotificationsList # I cant find where or how to make the changes I want withing the app's views.py, but this is an example @login_required def custom_get_queryset(self): # custom logic here, changing all notifications to 'read' return custom_get_queryset(self) I am very confused however, as I dont see how Django would know what function im overriding and I feel id need to copy/paste the original functions code into my overridden one and add my additional logic. This doesnt seem right. I have some additional questions: 1- Is this the wrong way to change such … -
The 'foto' attribute has no file associated with it. and value [' '] on Datefiled
My friends, good night! I only have 1 week of involvement in programming, I am doing it for personal purpose. I tried everything before creating a case, as it seems that many had the same problem, I reviewed as much as I could, but so far I have not been able to correct the error. Obs .: The information is being registered in the table, even reporting the error My models: from django.db import models from django.contrib.auth.models import User from datetime import datetime from django.utils.dateparse import (parse_date, parse_datetime, parse_duration, parse_time) from multiselectfield import MultiSelectField Create your models here. class Familia(models.Model): primeiro_nome = models.CharField(max_length=100, blank=True) ultimo_nome = models.CharField(max_length=100, blank=True) GENDER_CHOICES = ( ('M', 'Masculino'), ('F','Feminino') ) genero = models.CharField(max_length=50, choices=GENDER_CHOICES) data_de_nascimento = models.DateField(null=True, blank=True) local_do_nascimento = models.CharField(max_length=100, blank=True) data_de_falecimento = models.DateField(null=True, blank=True) local_do_falecimento = models.CharField(max_length=100, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) foto = models.ImageField(upload_to='arvore', blank=True, null=True) def __str__(self): return str(self.id) @property def foto_url(self): if self.foto and hasattr(self.foto, 'url'): return self.foto.url else: return '#' class Meta: db_table = 'db_genealogia' @login_required(login_url='/login/') def set_familia(request): primeiro_nome = request.POST.get ('primeiro_nome') ultimo_nome = request.POST.get('ultimo_nome') data_de_nascimento = request.POST.get('data_de_nascimento', None) local_do_nascimento = request.POST.get('local_do_nascimento', None) data_de_falecimento = request.POST.get('data_de_falecimento', None) local_do_falecimento = request.POST.get('local_do_falecimento', None) genero = request.POST.get('genero') file = … -
How to set environment variable only to the scope of the Django project?
I'm working on multiple Django projects on a Windows machine and I wonder if I could set different environment variables for different projects/workspace (I'm using VSCode by the way). An example of the difficulties I'm having is that for different projects, I'm using different database connections, or different setting modules (like below). os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectA.settings') So for the above, if I set DJANGO_SETTINGS_MODULE to an environment variable, when I switch to projectB, an error will occur. Is there a way to achieve this, ie. environment variables that are only applicable to that workspace/project? -
Django ListView How to Show all Parent records and ONLY 1 child belonging to current User
I have a CBV (ListView) which displays a list of MAGAZINES in my template. While a user is logged in and looking at the entire MAGAZINE list, I want to show a flag next to the magazines for which the current user is subscribed. I have experimented with query_set, get_context_data, etc. without luck. I have a MAGAZINES model, and a SUBSCRIPTIONS model. The SUBSCRIPTION model has a foreign-key related to the parent MAGAZINE model by pk (related_name="magazineid"), and a USER_ID. I am able to iterate through the SUBSCRIPTIONS model and I see the magazines to which the user is subscribed. I want to show the entire MAGAZINES list with a "flag" next to those that the current user is subscribed, NOT just simply a filtered list showing only the magazines to which the user is subscribed. In SQL terms, this would be MAGAZINES left join SUBSCRIPTIONS where SUBSCRIPTIONS.user_id == self.request.user). I simply don't know the Django syntax to achieve this. Been looking at complicated examples on StackOverflow for a week now. I'm sure there's an easy solution, but I can't seem to find it. Thank you in advance! models.py Class MAGAZINES(models.Model): magazineid = models.CharField("MagazineUUID", primary_key=True, max_length=4) magazinename = models.CharField("Magazine Name", … -
Difference between two methods in django
What's difference between two methods and which is better for long run ? Is there any advantage one over other? To add a staff: (1st Method) views.py def add_staff(request): return render(request, 'hod_template/add_staff_template.html') def add_staff_save(request): if request.method != 'POST': return HttpResponse('Method not allowed') else: first_name = request.GET.get('first_name') last_name = request.GET.get('last_name') username = request.GET.get('username') email = request.GET.get('email') password = request.GET.get('password') address = request.GET.get('address') try: user = CustomUser.objects.create_user(username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=2) user.staffs.address = address user.save() messages.success(request, 'Staff Added Successfully') return HttpResponseRedirect('/add_staff') except: messages.error(request, 'Failed to Add Staff') return HttpResponseRedirect('/add_staff') urls.py path('add_staff/', add_staff), path('add_staff_save/', add_staff_save), add_staff.html <form role="form" action="/add_staff_save"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" placeholder="Password" name="password"> </div> <!-- same for first_name, last_name, username, address --> <div class="card-footer"> <button type="submit" class="btn btn-primary btn-block">Add Staff</button> </div> </div> </form> (2nd Method) make a form in forms.py of all fields first_name, last_name, username, address and then call in view and validate it. forms.py class StaffForm(forms.ModelForm): class Meta: model = Staff fields = ('first_name', 'last_name', 'username', 'address') views.py def add_staff(request): if request.method == 'POST': form = StaffForm(data=request.POST) if form.is_valid(): messages.success(request, 'Staff Added Successfully') form.save() else: form = StaffForm() return render(request, … -
integrate mongodb with Django
I currently have a project which is using mySQL. However I also have some data in a mongo database that I need to fetch. I know there is a python library called Djongo, but I think it's changing the backend database to MongoDB. I wonder if there is anyway I can fetch data from the mongoDB while the rest of project is still using mySQL? -
Django admin not allowing superuser to log in (Custom User Model)
I have created a custom user class which appears to be working correctly however whenever I try to log in to the admin, I keep getting the following error on the login page: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. I have already created several superuser which are all saving to the DB correctly with the is_staff/is_superuser/is_active flags set to True as you can see below: CustomUser.objects.all().values() <QuerySet [{'id': 1, 'password': 'test', 'last_login': None, 'is_superuser': True, 'username': 'test1', 'first_name': '', 'last_name': '', 'email': 'test1@test.com', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2020, 6, 1, 0, 17, 30, 297149, tzinfo=<UTC>), 'role_id': 1, 'user_type_id': 1, 'created_by_id': None, 'update_date': datetime.datetime(2020, 6, 1, 0, 17, 30, 298524, tzinfo=<UTC>), 'updated_by_id': None}]> I am officially puzzled as to what I have done incorrectly... Please help me figure this one out... models.py: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.conf import settings class UserType(models.Model): """ This model defines the types of users which are allowed to be created in the application. Examples include: API Read Only User API Full CRUD User Business User """ name = models.CharField(max_length=50, blank=False, null=False) description = models.TextField() active = models.BooleanField(default=True) … -
How to edit user's profile view with django
I am making a form in which the user can edit their profile, so currentley I have 2 forms, one that edits the User model(first_name, Username and Email) and other one that edits the Profile model(biography). The problem is that everytime I edit, just the User model is the one that gets saved while the Profile model doesnt. I think that the error is on the views.py file. views.py def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) form1 = UpdateProfileForm(request.POST, instance=request.user) if form.is_valid: form.save() form1.save() return redirect('profile') else: form = EditProfileForm(instance=request.user) form1 = UpdateProfileForm(instance=request.user) args = { 'form': form, 'form1': form1, } return render(request, 'profile-edit.html', args) forms.py class EditProfileForm(UserChangeForm): class Meta: model = User fields = ( 'first_name', 'username', 'email', ) exclude = ('password',) class UpdateProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'bio', 'profile_pic', ) exclude = ('user',) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=400, default=1) def __str__(self): return f'{self.user.username} Profile' profile-edit.html (I replaced the {{form.as_p}} and {{ form1.as_p }} to the following html code) <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="edit-profile"> <h3>Name</h3> <input type="text" name="first_name" value="{{ user.first_name }}" maxlength="30" id="id_first_name"> <h3>Username</h3> <input type="text" name="username" value="{{ user.username }}" maxlength="150" required="" id="id_username"> <h3>Bio</h3> … -
How do I get my Django context variables into my JS file?
I'm trying to get data from a Django Backend to display on a map with Google Maps API, but I can't figure out how to pass the variables into the Javascript. Can someone please help me figure out what I'm doing wrong? Django Method: def home(request): //stuff that processes the method return render(request, 'map/index.html', {'lats': lats, "longs": longs, 'lat': lat, 'long': long, 'names': names, 'scores': scores}) HTML Snippet: <script> src = getlocation.js></script> <!-- this implements the navbar--> <div id="navbar"></div> <script type = "module" src = ../../static/navbar.js></script> <!-- input tag--> <form method="post"> {% csrf_token %} <input id="address" type="text" name="address"> <input type="submit" style="display: none" /> </form> <script> var names = {{ names }}; var lats = {{ lats }}; var longs = {{ longs }}; var scores = {{ scores }}; var lat = {{ lat }}; var long = {{ long }}; </script> <!-- this implements the map--> <div id="map"></div> <script src = ../../static/index.js> </script> Javascript Snippet(index.js): let locations = new Array(names.length); for(let count = 0; count < names.length; count++){ locations[count] = [names[count], lats[count], longs[count], scores[count]]; } let curlat = lat, curlong = long; -
slice requires 2 arguments, 1 provided
I'm trying to add some values from another list synchronously in the for loop of django ’s template. When I use a given number everything works fine, but when I replace it to {{forloop.counter}} it reports an error slice requires 2 arguments, 1 provided I Googled it and the suggestion is that there should be no spaces in the code, but there are no spaces in my code, here the code in question. {% for i in invtypes %} <li> ... <p>{{data|slice:":{{forloop.counter}}"}}</p> </li> {% endfor %} The {{data}} is a list of extra data for invtypes so they have same length and sort。 -
Django: How to use javascript variable in url template tag
I want to use a javascript variable as the pk for my django url template tag. It has been asked before, but none of the solutions work for me. See for example Get javascript variable's value in Django url template tag. I tried the solution suggested by @Mike Lee, i.e.: var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, var.toString()); However, when I try this, it redirects to /12345, in other words the replacement is not made. A bit of context of what I am trying to do: I have flashcards. Studying flashcards is done via javascript. In my js file, there are variables to get the necessary cards, show the current card etc. I have a button in my html that is supposed to redirect to a page where you can edit the flashcard. So for example, I have: <a id="button" class="btn btn-default btn-warning" id='button-study' href="{% url 'flash:edit' card.id %}">Edit</a> card.id is just a placeholder - I need this to refer to whichever card is showing at any given time. When studying, when I look at the console, I can see the details of the current card, including the id, which is what I need to put in the url … -
Show different requests in different endpoints in Swagger (DJANGO)
I have 4 requests A,B,C and D defined in urls.py What I want to accomplish is -> I want A and B to be seen in the swagger form that can be accessed with url mydomain/firstapi and C and D to be seen in the swagger form that can be accessed with mydomain/secondapi. But what ends up happening is that both of these urls show the same swagger form. Requests A and B are listed below firstapi and request C and D are listed below secondapi as expected (but both of these groups can be seen in both urls which is precisely what I wanted to avoid) What I have tried is #urls.py firstapipatterns= ([ path('a', AView.as_view()), path('b', BView.as_view()), ], 'secondapi') secondapipatterns= ([ path('c', CView.as_view()), path('d', DView.as_view()), ], 'secondapi') urlpatterns = [ path('firstapi/', include(firstapipatterns)), path('secondapi/', include(secondapipatterns)), ]