Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Unit Test Blank DateTimeField
I am trying to unit test a form which includes a date selector. It is saved in the model as DateTimeField and in the form uses a DatePickerInput widget. This is the test: def test_form_validation_for_blank_items(self): user = User.objects.create_superuser('username') self.client.force_login(user) form = PersonalInformationForm(data={ 'first_name': '', 'surname': '', 'gender': '', 'dob': ''}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'first_name': ['This field is required.'], 'surname': ['This field is required.'], 'gender': ['This field is required.'], }) And the error that's thrown: AttributeError: 'NoneType' object has no attribute 'year' My other fields are fine, but I was wondering how to unit test a blank DateTimeField model with a DatePickerInput widget. Thank you. -
Django-REST-Framework REST API within django app
I'm wondering if there is a way to access REST API within the Django app. I created a REST API using the Django rest framework. In the same project, I'm having another app in which I want to fetch data using my own rest API. -
How to only save model objects that have changed?
I want to only save the records I update via the formset. At the moment ALL my updated_by fields change to the User that is logged in, not just the ones I change in the form. Views.py @login_required() def inventory_update(request): title = 'Update Inventory' UserInventoryFormset = modelformset_factory(Inventory, form=InventoryUpdateForm, extra=0) if request.method == 'POST': formset = UserInventoryFormset(request.POST) if formset.is_valid(): for form in formset: updated = form.save(commit=False) updated.updated_by = request.user updated.save() else: formset = UserInventoryFormset() context = {'formset': formset, 'title': title } return render(request, 'main/inventory_form.html', context) Models.py class Inventory(models.Model): item = models.CharField(max_length=50, unique=True) stock = models.IntegerField() par = models.IntegerField() date_updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.item Forms.py class InventoryUpdateForm(forms.ModelForm): class Meta: model = Inventory exclude = ['updated_by'] fields = ['stock', 'par'] -
How can I get all contacts in a email using contact Api Django
I was going through this. How to use google contacts api to allow my users to invite their gmail contacts to my django website What I need to do if I ask my user to write the email.I want to get contacts of that email not of user. What steps should be taken to get contacts. -
django list_filter in html
How do i import this list_filter into my html? do you have any documentation that easy to follow and easy to understand? is it possible? class ArticleListView(ListView): model = StudentsEnrollmentRecord s=StudentsEnrollmentRecord.objects.all() paginate_by = 50 # if pagination is desired searchable_fields = ["Student_Users", "id", "Section"] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context -
How to get active users from last X mins in Django
I have a website created in Django, How can I get a list of active users from last X mins. I want all not-logged in as well as logged-in users. -
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?