Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data not filling in with Edit Profile form Django
I'm using the following line to fill in data into the form. form = EditProfileForm(request.POST, instance=request.user) However, no data fills into the form. I just get the empty form. Not sure what's going wrong. I have a profile html where the data from each user shows up, but the line above is not working on the edit page. The model is the default user model. Django version 2.2.3. #views.py def editprofile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): agree = form.save(commit=False) agree.save() args = {'form': form} else: form = EditProfileForm(request.POST) args = {'form': form} return render(request, 'profile_edit.html', {'form':form}) Here is my forms.py: class EditProfileForm(UserChangeForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': "form-control"})) last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': "form-control"})) email = forms.CharField(label= 'Email', widget=forms.EmailInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] def save(self, commit=True): user = super(EditProfileForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user -
How to chain select_related functions in Django?
I have the following tables in my database: class A(models.model): ... class B(models.model): a = models.ForeignKey(A) class C(models.model): b = models.ForeignKey(B) data = models.TextField(max_length=50) What I want to do is get the C object with a pk of 215, and select the related B object, and also select the related A object of the B object. Right now, what I am doing is this: c = Models.objects.select_related('b').select_related('a').get(pk=215) However, I get the following error: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'a'. Choices are: b Is this possible to actually get all 3 objects with just one database hit? Thanks for any answers. -
In Django, is it better to store complex chaining save methods in models, or in views?
Lets say I have models similar to something like this: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... def save(self, *args, **kwargs): super(Y, self).save(*args, **kwargs) self.x.do_something() self.x.save() class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Z, self).save(*args, **kwargs) self.y.do_something() self.y.save() In other words, if a Z object is saved, its referenced Y object is updated and saved, which in turn saves its referenced X object. Right now, as it clear from the code, the complex save process is stored entirely in the models module. In production, the save method of Z should be ideally made atomic. Anyway, my question is this: should this sort of logic be stored in views instead? Like there could be a view like so: @transaction.atomic def my_view(request, z_pk): z = Z.objects.select_related('y').select_related('x').get(pk=z_pk) z.save() y = z.y y.do_something() y.save() x = y.x x.do_something() x.save() ... Obviously, for the above scenario, the model module would be simplified into something like this: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) Which one of … -
Where I should to put the "firebase_admin.initialize_app" command in a django application?
I'm a beginner in this field. My question is basically, where do I need to put the following code Like in the settings.py archive or views.py? I'm using it in the views.py but I'm not sure where. Do I need to create a new .py archive? Also, I'm trying to add some information to the cloud firestore. import firebase_admin from firebase_admin import auth, credentials, db from firebase_admin import firestore cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': 'xxxxx', }) db = firestore.client() -
No 'Access-Control-Allow-Origin' header on the requested resource in Django
I have read relevant question and understand what is cors. I followed each step. Install pip install django-cors-headers Add MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'a9.core.access.middleware.AccessMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = ['corsheaders','otree'] And python3 manage.py migrate However, I still get the error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.1 Is there something I am missing to make it work correctly? -
Django authentication failed with error 'csrf token missing or incorrect' when logon from cellphone
I implemented custom authentication in my django app. I was able tto logon from several different devices: desktop, cellphone, etc. The problem is if I have a logged in session running from desktop, I will get the CSRF verification failed error on my cell. But not the other way around. I I already logged on in my cell phone, I do not have any problem logging on from my PC. Here is my login view def login_page(request): form = LoginForm(request.POST or None) context = { "form": form, 'namespace':'accounts', } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None # if redirect_path == '/': redirect_path = '/dashboard/' if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/") # return redirect("dashboard/") else: # Return an 'invalid login' error message. print("LOGIN FAIL: Someone is trying to login and failed!") print("LOGIN FAIL: Username: {} and password: {}".format(username, password)) return HttpResponse("invalid username or password") else: return render(request, "accounts/login.html", context) -
How to form a queryset from two fields(columns) of the same model(same object)?
I'm trying to form a query set to load into a select form. This queryset has values that come from 2 fields of the same model(same object) from another model. For example, I have a GameId(object) stored in my database with a slug = 1sunariatl. This game id has GameId.home = ari and GameId.visitor = atl. I want to create a new form (PlayForm) with a select field(driving) that lets the user choose between the home team and the visitor team. (Select field in form will show "atl" and "ari") How do I form a new queryset based on these specific field values of the same object? models.py class GameId(models.Model): week = models.CharField(max_length = 100) day = models.CharField(max_length = 100) home = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='home') visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='visitor') class Play(models.Model): driving = models.CharField(max_length = 100) forms.py class GameIdForm(forms.ModelForm): class Meta: model = GameId fields = [ 'day', 'week','home', 'visitor' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['home'].queryset = Team.objects.all() class PlayForm(forms.ModelForm): def __init__(self, round_list, *args, **kwargs): super(PlayForm, self).__init__(*args, **kwargs) self.fields['driving'].queryset = #insert code here class Meta: model = Play fields = [ 'driving' ] -
Is auth customization secure in django?
I've extended user model with o2o relationship model (UserProfile). I want to make logging in with email/password instead of username/password. So I customized the auth backend. Is logging in vulnerable with that way of authentication? from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmAuth(ModelBackend): def authenticate(self, request, 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 def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None -
Problems with saving and showing data with using from multiple checkboxes
Oay, let's start from the beginning ... I create a blog in Django. And I want to create something like a "playlist" containing several related posts (I hope you will understand) . But I have problem because I don't know how to display all posts in this "playlist". What is more I don't even know if I save all data in correct way, so if something is wrong please help. models.py: class Queue(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ManyToManyField(Post) def __str__(self): return self.title forms.py: class QueueForm(BSModalForm): post = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=((x.id, x.title) for x in Post.objects.all())) class Meta: model = Queue fields = ['title', 'description', 'post'] views.py: class QueueCreateView(BSModalCreateView, LoginRequiredMixin): template_name = 'blog/queue_form.html' form_class = QueueForm def form_valid(self, form, **kwargs): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): reverse_user = self.request.user return reverse('profile', kwargs={'username': reverse_user}) html file: {% for queue in queues %} {{queue.title}} {{queue.post}} {% endfor %} -
Define & Use Custom renderer Django Rest Framework View
I'm trying to override a CSV renderer import for a django rest framework view. Here's how so: class CustomCSVRenderer(BaseCSVRenderer): def render(): do something def tablize(): do something I've defined the CustomCSVRenderer in the same python class views.py as the view in question: class MyView(ListAPIView, CustomMixinSet): renderer_classes = (CustomRenderer, JSONRenderer) When I try to debug this implementation, my pdb debugger never hits the CustomCSVRenderer and instead I get a response based on some underlying renderer used by django restframework. What could be the issue? How do I know what renderer django rest framework is using? -
Add a django like system to posts
I am attempting to add a like system so users can like a post. I am unsure how to do this at the moment, and need some suggestions on the way to approach this. I need a user to be able to like/dislike posts. And that the colour of a button changes depending on whether a user has liked a post or not. -
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 …