Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django and services as classes
Are there any conventions on how to implement services in Django? Coming from a Java background, we create services for business logic and we "inject" them wherever we need them. Not sure if I'm using python/django the wrong way, but I need to connect to a 3rd party API, so I'm using an api_service.py file to do that. The question is, I want to define this service as a class, and in Java, I can inject this class wherever I need it and it acts more or less like a singleton. Is there something like this I can use with Django or should I build the service as a singleton and get the instance somewhere or even have just separate functions and no classes? -
How to import model classes while using click cli
I want to create a command line interface for manage some of user-management actions inside a django project. But when I need to import my models, click errors: from .models import UserGroup ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package" I have tried replacing .models to my_app.models but it sends the same error. I'm using python 3.6 and django 2.2 and click 7.0. my models: class UserGroup(models.Model): pass class AccessRule(models.Model): pass and my click code is simple. its just: @click.command() def list_user_groups(): for user_group in UserGroup.objects.filter(): click.echo(user_group.title) if __name__ == '__main__': list_user_groups() I expect to use below command to get list of my user groups for now. $ python3 cli.py list-user-groups Admin Customer Seller -
Django-guardian: safe to delete GroupObjectPermission and UserObjectPermission tables if using direct foreign keys?
The docs of Django-guardian mention the option to use Direct foreign keys as a performance improvement suggestion. As the initial migrations that come with the app have similar models but with a Generic foreign key, I'm wondering if I can just remove the migrations from the package as they would just be two unnecessary tables, if I choose to go with the Direct FK approach. Is there a cleaner way of doing this? Are the migrations required for other functionality within the app or can I just remove the models and migrations and use Direct FK for all my models? -
applying tags to multiple models in wagtail
The Wagtail documentation on tagging states the net effect is a many-to-many relationship between your model and a tag class reserved for your model But what if you have multiple models that need to share the same tag class? Details: I'm building a Wagtail site where I've got two models (ModernPost and LegacyPost) that both need to be tagged with taggit. I also need a reverse-chron listing of all posts (i.e., both models), filterable by tag. I know how to generate the unfiltered listing, but the tag-filtered listing baffles me, because Wagtail's tagging recipe gives each model its own tag class, and I don't know how to construct a query that would, for example, return all ModernPosts and LegacyPosts tagged as "foo". It seems like the models would need to share a tag class for this to work. The taggit documentation mentions "GenericTaggedItemBase allows using the same tag for different kinds of objects" but swapping that class into the standard Wagtail recipe leads to errors -- apparently because modelcluster does not support GenericTaggedItemBase? So what's my best path forward? Am I thinking about this all wrong? -
Django user.save() fails on Column 'is_superuser' cannot be null
I am trying to update user password using this code: from django.contrib.auth.models import User u = User.objects.get(username='test') u.set_password('test') u.save() but it falis everytime on these errors (without long messages from whole error message): _mysql_connector.MySQLInterfaceError: Column 'is_superuser' cannot be null mysql.connector.errors.IntegrityError: 1048 (23000): Column 'is_superuser' cannot be null django.db.utils.IntegrityError: Column 'is_superuser' cannot be null AttributeError: 'NoneType' object has no attribute 'strip' I am confused because this code is from official site so error is probably somewhere between django and mysql. Thanks for advance -
Django REST giving a 403 forbidden on DELETE methods, but not POST
I am trying to delete an entry using an ajax call. when I am using the default 'delete' method from generics.DestroyAPIView, I am getting a 403 Forbidden, but if I add a post method, call the delete method immediately and change the ajax type to 'post' it works fine. Would anyone have an idea what causes this? Note that I overwrite the get_object function to get the object based on posted data. (could it be due to delete methods not allowing to post data? If so, why? And how would you pass the CSRF token??) ajax: $.ajax({ url: '{% url "account:api:post_details_delete" %}', type: 'delete', data: { csrfmiddlewaretoken: "{{ csrf_token }}", name: json.name, value: json.value } }); } url: path('post_details/delete/', PostDetailDeleteApiView.as_view(), name='post_details_delete'), view: class PostDetailDeleteApiView(generics.DestroyAPIView): serializer_class = PostDetailSerializer # the code below allows it to work if uncommented and type in ajax changed to 'post' # def post(self, request, *args, **kwargs): # return self.delete(request, *args, **kwargs) def get_object(self): """ Returns the post detail object to be deleted based on the name:value pair provided by the ajax call. """ data = self.request.data obj = Post_Detail.objects.filter( name=data.get('name', ''), value=data.get('value', '') ).filter( post__account__user=self.request.user ) if obj.exists(): return obj.get() else: raise Http404 serializer: class PostDetailSerializer(serializers.ModelSerializer): … -
django rest framework- serializers, read_only, and drf-nested-routers, how to set parent?
I have the following simple models for a todo list: class TodoList(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) class Todo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) todo_title = models.CharField(max_length=64) todo_body = models.TextField() completed = models.BooleanField(default=False) list = models.ForeignKey(TodoList, on_delete=models.CASCADE, related_name='messages') What I am trying to do is set up a nested route using drf-nested-routers. E.g.: /api/v1/todo-lists/ <- List Todo Lists /api/v1/todo-lists/{LIST_ID}/ <- CRUD a Todo list /api/v1/todo-lists/{LIST_ID}/todos/ <- List todos for a particular list /api/v1/todo-lists/{LIST_ID}/todos/{TODO_ID}/ <- CRUD for a particular todo I've got a Todo Serializer: class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'todo_title', 'todo_body', 'completed', 'list',) read_only_fields = ('id', 'list',) And a TodoByList Viewset: class TodoByListViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = TodoSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): return Todo.objects.filter(list_id=self.kwargs['todolist_pk']) def create(self, request, todolist_pk=None): todo_list = get_object_or_404(TodoList, pk=todolist_pk) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) The list view works great, however for create I am in a bit of a catch-22. The list parameter for my Todo model is required (rightfully so), and thus perform_create doesn't work since list is not set. But if I remove list from the read_only_fields in my serializer, .is_valid fails since I am not passing the list … -
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.