Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to subtract current date time from Django Model datetime field using javascript
I have a django model that has a date time field. I am currently rendering a html table that contains a column which shows how long until this date time. I also want it to update on a timer using js. To do this I am assuming I need to subtract the current datetime given by js, from the python date time. Any ideas? The only other option I am aware of is by using {{djangofield|timeuntil:currentdate}}, however this does not include seconds which i would like it to. Thank you everyone! -
Syntax error: Manifest json on chrome browser
I'm getting syntax error in my manifest.json build file. It shows the error right at the beginning of my index.html file (Very strange). Does anyone know if this error causes my images and containers to not render on React? I've been stuck on this for awhile and I cannot figure out why. I've already tried: Add manifest_version 2 since that's chrome current version. Changed doctype! to DOCTYPE! in my index.html file. Checked for all syntax errors in dev env. Updated npm. And reran npm run build. Hosting on development server at http://127.0.0.1:8000/ through django runserver script. Below is my manifest.json { "manifest_version": 2, "app": "", "Short_name": "React App", "Name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" } ], "start_url": "./index.html", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } This is the error Manifest: Line: 1, column: 1, Syntax error. Picture of GET status of manifest.json Picture of Chrome Application window error -
"Invalid Syntax" by overwriting HTMLCalendar functions in Python
I want to create a webiste with a calendar in Django. Therefor i have found a tutorial on the web. Here you have to overwrite the functions from the HTMLCalendar When I use the Code from there comes the Error : File "/home/work/Desktop/Coden /Projects/Calendar/anotherone/cal/utils.py", line 18 d += f"<li> {event.title} </li>" The tutorial - when it comes to overwriting the functions: https://www.huiwenteo.com/normal/2018/07/24/django-calendar.html This is just a Django Project. I code on Ubuntu in Visualstudio code. Here the start from the files. I think it occurs because of the " and the following HTML Code. As you can see, is this not once in the file it comes again and again. I hope someone can give me a solution for the whole file. from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f"<li> {event.title} </li>" if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' I hope I can display the calendar after fixing … -
Reverse accessor clash when two models inherit from auth.AbstractUser
I have two separate django projects (Project A and Project B) each with their own models and databases. Project B uses the django.contrib.auth.User model while Project A uses a custom user model inherited from django.contrib.auth.AbstractUser. I wanted to be able to perform lookups on Project A models from within project B so I added the apps from Project A to the INSTALLED_APPS on Project B, but I run in to an issue with SystemCheckError: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. core.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. core.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. If I switch the AUTH_USER_MODEL to use <Project A>.User then it works just fine, but I was hoping to find a solution … -
Django's queryset.aggregate max() runs into issues after 9
I am running into an issue with the queryset.aggregate(max()) function in Django when the field I am querying has values larger than 9. I have a model named Build and I want to query this model to get the largest value in the BuildIdentifierfield. The code below works perfectly when the values in BuildIdentifier are less than 10. As soon as I have a value greater than 10, it will still only return 9. What am I missing here? I am only dealing with integers. previousBuild = Build.objects.filter(author = currentAuthor) largestIdDict = previousBuild.aggregate(Max('BuildIdentifier')) largestIdList = list(largestIdDict.values()) largestIdNo = largestIdList[0] LargestIdNo returns the correct value up until a value greater than 9 is added to the BuildIdentifier field, then it just keeps returning 9, even though there is definitely larger values in this field -
How to get the Modelfield - datetime.now
i've been strugling a lot with arithmetics on Dates. First of all i got the date between two datetimeFields (models) and thats ok. but i'd like to get the (To_do.end)-datetime.now() i've got the 2 datefields difference by the : To_do.objects.annotate( delta=ExpressionWrapper(F('end') - F('start'), output_field=DurationField()) since i've been trying the same with a variable=datetime.now() and still don't get it thats the test that im trying to get the succes def index(request): myDate = datetime.now() days_left1 = To_do.objects.annotate( delta=ExpressionWrapper(F('end') - myDate, output_field=DurationField())) return render(request, 'ongoingtest.html', { 'myDate': myDate, 'days_left1': days_left1, }) thats what i did to get the difference between the two model fields class HomeView(ListView): template_name = 'ongoing.html' model = To_do def get_queryset(self): return To_do.objects.annotate( delta=ExpressionWrapper(F('end') - F('start'), output_field=DurationField()) ) models.py: class To_do (models.Model): task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateTimeField(auto_now_add=True) end = models.DateTimeField(blank=False) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.task just get the To_do.end - datetime.now() -
Django model formsets - selecting the value of foreign key object
I am new to Django an trying to learn the model formsets, I am not sure how to phrase this question precisly in the title but I'll try my best to explain it here. So I have the following model which has some basic fields and then a parent field which is basically a ForeignKey to itself. The reason for having this field is that parent of any member will be some other instance of the same model. class FamilyMember(models.Model): name = models.CharField(max_length=20) age = models.PositiveIntegerField(null=True, blank=True) job = models.CharField(max_length=20, null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) def __str__(self): return self.name I have the following view to add new children to any FamilyMember instance where I am using the model formsets to create multiple children in one go. def add_child(request): member = FamilyMember.objects.get(name="Tom") # hard coded for testing purposes child_formset_factory = modelformset_factory( FamilyMember, fields=("parent", ), labels={"parent": "Child"}, ) if request.POST: formset = child_formset_factory(request.POST) # ... do the actual saving part here return HttpResponse("Done") formset = child_formset_factory(queryset=FamilyMember.objects.get( name="Tom").children.all()) return render(request, "family/add_child.html", {"formset": formset}) Now when I hit this view, I am able to see 3 drop down lists (since Tom has 3 children for now), but none of the … -
How to retrieve authentication token from initial HTTP Authentication Request in Swift for IOS App Development?
Currently, I have a Django-backend site with rest-framework-auth setup and functioning as far as the default web portal. I see many tutorials on how to remain authenticated with token authentication, but nothing that shows how to perform the initial authentication where you receive the authentication token. How do I make the initial request with the username and password to receive the token? I would prefer to do this using native classes like NSURLSession rather than installing Alamofire or similar libraries if possible. Sorry for no source code, but I have nothing to go off of with this issue. Also, if there are any issues with the nature of the question, I apologize again, this is my first post. -
django email confirmation error: TemplateResponseMixin requires either 'template_name' or 'get_template_names()'
I have a django project with a customUser model (email / password), and I'm trying to get email verification links working. They were working before, but now for some reason the path is failing. When you sign up for an account on my site you get an email with a registration-confirmation URL like so: http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/OA:1hxEiC:mbXKk8-is0YJz2FKHd_1d62KNv8/ But when you click this url, it leads to an error page with the message: ImproperlyConfigured at /rest-auth/registration/account-confirm-email/OA:1hxEiC:mbXKk8-is0YJz2FKHd_1d62KNv8/ TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' my main urls.py file has a urlpatterns list which looks like this: urlpatterns = [ #admin page path('admin/', admin.site.urls), path('playlist/', include(('playlist.urls', 'playlist'), namespace='playlist')), #users path('users/', include('django.contrib.auth.urls')), #accounts (allauth) path('accounts/', include('allauth.urls')), ... #django-rest-auth url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), #bug reports for this issue online point to a solution like so, but this isn't fixing the error url(r"^rest-auth/registration/account-confirm-email/(?P<key>[\s\d\w().+-_',:&]+)/$", allauthemailconfirmation, name="account_confirm_email"), #jwt url(r'^refresh-token/', refresh_jwt_token), ] Can somebody please help me figure out this error? I have looked at many other instances of this problem being posted online and have found many people solving it by catching the registration-confirmation path using a regular expression, I've tried every regex combination I could find in solutions posted online but haven't had any … -
How to create an email registration form and email login system in django
i want to create a email registration system with password1 and password2(confirmation password) and also a email login system in django. i have seen couple of solutions but did not work for me. Any help will be appreciated. accounts/forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class UserCreateForm(UserCreationForm): class Meta: fields = ("email", "password1", "password2") model = User def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exists(): raise forms.ValidationError('A user has already registered using this email') return email accounts/backends.py class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): usermodel = get_user_model() try: user = usermodel.objects.get(email=username) except usermodel.DoesNotExist: return None else: if user.check_password(password): return user return None settings.py AUTHENTICATION_BACKENDS = ['accounts.backends.EmailBackend'] Whenever i try to register a second user i have the following error: UNIQUE constraint failed: auth_user.username -
django.core.exceptions.ImproperlyConfigured: WSGI application 'crmapp.wsgi.application' could not be loaded; Error importing module
I am a beginner and trying to learn django but i get the following error, django.core.exceptions.ImproperlyConfigured: WSGI application 'crmapp.wsgi.application' could not be loaded; Error importing module. This is the error i get when i try to run server. Any help appreciated Thanks ""My WSGI.PY file looks like this"" import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crmapp.settings') application = get_wsgi_application()` ""SETTINGS.PY FILE"" WSGI_APPLICATION = 'crmapp.wsgi.application' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
How to have dynamically added fields to specific model fields and not all
i am building an application that has a model with three fields Company,Name, position. in the same model i want to have company name as one field while the user can add name and positions for multiple candidates. the reason am trying to do that is because i didnt find any proper way to set automatically select the foreign key based on the company name entered since foreign key is a drop down list and couldnt figure out the way to make foreign key field equal to company name entered. appreciate help and suggestions if any for the approach i have in mind. -
Send array of objects from a view to a template to use in javascript, django
As can be done so that from django through a view an array of objects (which is the result of a series of operations) can be sent to a template, but this arrangement will be used in a javascript code fragment which will handle make a graph -
How to render all permissions of a specific model in django templates?
Suppose I've a model called class UserProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) first_name = models.CharField(_("First name"), max_length=50) middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True) last_name = models.CharField(_("Last name"), max_length=50) dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False) profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True) class Meta: verbose_name = _("User profile") verbose_name_plural = _("User profiles") def __str__(self): return self.first_name + " " + self.middle_name + " " + self.last_name def get_absolute_url(self): return reverse("userprofile_detail", kwargs={"pk": self.pk}) I want to render default permission available to this model in the tabular form like below. I try to render forms manually but it display all the permissions like below with checkboxes. account.add_emailaddress account.add_emailconfirmation account.change_emailaddress account.change_emailconfirmation account.delete_emailaddress account.delete_emailconfirmation auth.add_group auth.add_permission auth.change_group auth.change_permission auth.delete_group auth.delete_permission -
How to using Spring @RequestMapping annotation with attribute name in Spring MVC
As I know in the Django Framework offers a way to name URLs so it's easy to reference them in view methods and templates. For example: # Definition in coffeehouse/urls.py path('',TemplateView.as_view(template_name='homepage.html'),name="homepage") # Definition in view method from django.http import HttpResponsePermanentRedirect from django.urls import reverse def method(request): .... return HttpResponsePermanentRedirect(reverse('homepage')) # Definition in template <a href="{% url 'homepage' %}">Back to home page</a> what is the name attribute in Spring @RequestMapping annotation? Is it the same with the name URL in the Django Framework? how to using @RequestMapping annotation with attribute name in Spring MVC? -
How to test PasswordChangeView
I'm trying to create a test for the get_success_url method of PasswordChangeView to see whether the redirect work as intended. The expected behavior I'm looking for -- with a valid form -- is to have the password changed, and to get a 302 redirect response. But for some unknown reason, I can't seem to pass valid form data, so I get a 200 response, and the test keep failing. Does anyone know why the test below give me an invalid form? What am I missing? test.py def test_success_url(self): client = Client() user = User.objects.create(username="anon", password="pw") client.force_login(user) data = { 'old_password': 'pw', 'new_password1': 'newpw', 'new_password2': 'newpw', } response = client.post('/anon/change-password/', data) user.refresh_from_db() self.assertEqual(user.check_password('newpw)) self.assertEqual(response, 302) views.py class UserPasswordChangeView(LoginRequiredMixin, PermissionMixin, PasswordChangeView): def get_success_url(self): return reverse("user:detail", kwargs={ "username": self.request.user }) -
remove help_text from django UserCreationForm
i am making registration page but i dont like text under username like : Required 150 characters or fewer. Letters, digits and @/./+/-/_ only. or under password: Your password can't be too similar to your other personal information. you get the point pls help,thankyou i tried to find other questions but they all remove help_text from added field as email, but i need to remove from username,password... class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email' , 'password1', 'password2'] and then i render it in html as crispy form {% csrf_token %} <fieldset> <legend class="hello4"> <i>Join Today</i> </legend> <div > {{form|crispy}} </div> </fieldset> <div> <button type="submit" class="btn btn-light">Sign Up</button> </div> </form> -
Override update in Django Rest Framework without reimplementing the entire method?
So, I've been looking for a pattern or standard for this for a while, but I can't seem to find one. Suppose I have some serializer: WhateverSerializer(serializers.ModelSerializer): class Meta: model = Whatever fields = ( 'special', 'field_1', 'field_2' #a bunch more... ) And I want to have some special update behaviour just for the field special but no other fields. Is there a way to to override update without having to redo the entire update method like this? def update(self, instance, validated_data): special_behaviour(instance.special) instance.field_1 = validated_data.get('field_1', instance.field_1) instance.field_2 = validated_data.get('field_2', instance.field_2) #a bunch more... I've tried calling the ModelViewSet.update method, but it actually takes different parameters than the one you override in the viewset, and I'm not sure how exactly to pass the ones I have into that method. -
Getting the primary key of a ForeignKey field without querying the database again in Django
I have the following models: class Model1(models.Model): ... class Model2(models.Model): ... model1 = models.ForeignKey(Model1) Now, lets say I have an object of Model2 with pk=241 which is related to another object of Model1 with pk=102. I am querying them as follows: model2 = Model2.objects.get(pk=241) Now, if I want the pk of the referenced Model1 object. I do the following: model2.model1.pk This should not query the database again according to what I understand about tables, but if I run the following: from django.db import connection connection.queries I get a list of 2 queries. Why do I need to query my database again to only get the primary key of my related object? Is there a way to avoid doing this? I am aware of select_related(), however, what if I want to call the Model1 objects pk in the save() method of the Model2 class? Moreover, is select_related() required even if I want to just retrieve the pk of the related object and nothing more? -
scroll down or open link
with a hard work I've achieved to make A scrool down to a specefic div when clicking on a specific menu item, the issue that I have is in another menu item contact that opens another page contact.html. it does't work when using href="{% url 'contact' %}" <div class="main-menu mean-menu float-right"> <nav> <ul> <li class="active"><a href="#hero-area">home</a></li> <li><a href="#feature-area">about<i class="icofont"></i></a></li> <li><a href="#gallery-area">gallery<i class="icofont"></i></a></li> <li><a href="#instructor-area">services<i class="icofont"></i></a></li> <li><a href="{% url 'blog' %}">blog<i class="icofont"></i></a> <ul> <li><a href="{% url 'blog' %}">Blog</a></li> <li><a href="blog-details.html">Blog Details</a></li> </ul> </li> <li><a href="{% url 'contact' %}">contact</a></li> </ul> </nav> </div> .JS CODE $('.main-menu ul li a').on('click', function(e) { e.preventDefault() $('html, body').animate( { scrollTop: $($(this).attr('href')).offset().top, }, 500, 'linear' ) }) var menuLi = $('.main-menu ul li'); menuLi.on('click', function(){ var currLink = $(this); if( menuLi.hasClass('active') ){ menuLi.removeClass("active"); currLink.addClass('active'); } }); View def contact(request): return render(request, 'sc_drive/contact.html') URL path('contact', views.contact, name='contact'), -
ModelChoiceField lists tuples instead of simple values
I have a django form with a ModelChoiceField input and it lists the result as tuples instead of simple values. I have no clue on how to do it. DJANGO class PayThis(forms.Form): amount = forms.FloatField(required=False) cost2 = forms.FloatField(required=False) year = forms.ModelChoiceField(required=False,queryset=AnAgricol.objects.values_list('anul').all()) HTML <option value="(2019,)">(2019,)</option> I expect to get this: < option value="2019">2019< /option > -
Django forms with variable user entries
I want to create a django form that captures user entry such as name, address, age. For this type of information I can create a model such as class GeneralInfoPremium(models.Model): state = models.CharField(max_length = 2, choices = STATE_choices) class_code = models.CharField(max_length = 4) manual_premium = models.DecimalField(decimal_places = 2, max_digits = 10) class GeneralUserInfo(models.Model): firstname = models.CharField() lastname = models.CharField() address = models.CharField() # etc.... However, I also want to capture maybe some information like their class schedule or family information. class UserSchedule(models.Model): course_number = model.IntegerField() course_name = model.CharField() # etc.... class FamilyInfo(models.Model): family_member_type = models.CharField(choices = MEMBER_CHOICES) # mother, father, sibling family_member_name = models.CharField() # jon doe # etc.... where by each user, the number of courses and number of family members could vary. I would like the form to look something like below with a simple submit button to send things off to be saved. My question is, how should I structure the form template considering there are multiple models? -
Misunderstanding about Django collectstatic
I'm currently getting my Django website ready for production and have run into a small hitch. I've looked at the page https://docs.djangoproject.com/en/2.2/ref/contrib/staticfiles/, and it seems I need to run the collectstatic command to process all my static files and put them in one directory. The problem is that I have about 80GB worth of static files, and to copy them into a new STATIC_ROOT takes up a large amount of redundant hard drive space. Is there any way to keep this large set of datafiles in a file structure outside of the django website, and to serve them from there? -
I am trying to create a registration form to add data to 2 tables simultaneously. But I am not sure what to write after the POST method
I want to create a user into auth_user. And use its id(primary key) to fill in an entry into User_Profile to take it as a Foreign key. Models.py: class User_Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contact_number = models.IntegerField() birth_date = models.DateField(null=False) address = models.CharField(max_length=200) role = models.ForeignKey(Role, on_delete=models.CASCADE) Forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] class UserProfileForm(forms.ModelForm): class Meta: model = User_Profile fields = [ 'contact_number', 'birth_date', 'address', 'role'] Views.py: def registration_view(request): form = UserForm(request.POST) form2 = UserProfileForm(request.POST) else: context = { 'form': form, 'form2': form2 } return render(request, 'Schoool/registration_form.html', context) -
How can I send a notification on creating a new post using django-webpush?
I need to add a web push notification on creating a post but it does not work. I have tried following this documentations, https://www.digitalocean.com/community/tutorials/how-to-send-web-push-notifications-from-django-applications#conclusion Added this to my CreatePost View at Views.py self.object.save() for user in User.objects.all(): user_id = self.object.user.pk user_site = get_object_or_404(User, pk=user_id) payload = {'head': self.object.group, 'body': str(self.object.user)+' Uploaded a post.'} try: send_user_notification( user=user_site, payload=payload, ttl=1000) print('Success!') except: print("Fail") return super().form_valid(form) I expect it to send a push notification to all users in my site.