Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django backend in Rest-framework resource for eCommerce
I want to create an eCommerce store's entire backend in django (using Restful framework APIs), I am looking for resource available online especially on github. Ofcourse I have done extensive research but I am unable to find anything that is recently updated and yet simple enough for me to understand, as I am not expert in django yet. All I want is a resource from where I can see overall flow and model it by using their models, views, serializers and permissions as a reference -
How can I save local video file to django FileField?
I create a local video file (.mp4) by adding a logo to an existing video with the following code: logo_path = os.path.join(MEDIA_ROOT, 'logo.png') logo = (mp.ImageClip(logo_path) .set_duration(video.duration) .resize(height=50) # if you need to resize... .margin(right=8, top=8, opacity=0) # (optional) logo-border padding .set_pos(("right", "top"))) video_path = os.path.join(MEDIA_ROOT, 'test7.mp4') audio_path = os.path.join(MEDIA_ROOT, 'temp-audio.m4a') final = mp.CompositeVideoClip([video, logo]) final.write_videofile(video_path, codec='libx264', audio_codec='aac', temp_audiofile=audio_path, remove_temp=True ) I want to save the new video to a FileField of my model. Here is the code: f = open(video_path) flick.videoWithWatermark.save("videoWithWaterMark.mp4", File(f)) I keep getting the error: 'ascii' codec can't decode byte 0xd1 in position 42: ordinal not in range(128) How can I save the video to a FileField? -
Wagtail i18n: only show links to pages that are translated
I'm building an i18n website with Wagtail 2.11.3 and followed the documentation at https://docs.wagtail.io/en/stable/advanced_topics/i18n.html?highlight=i18n, and four languages. I also use django.middleware.locale.LocaleMiddleware to determine the user's preferred language, which "kind of" works (read below). So I have four languages: WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [ ('de', "Deutsch"), ('fr', "Français"), ('it', "Italiano"), ('en', "English"), ] Only parts of the website should be multi-lingual, some pages are only available in one language. I ended up having four page trees, one for each language, and I'm able to create translations. However, as pointed out, I have some pages that aren't translated at all, but still have a localized version (auto-created when I create a page). So here https://docs.wagtail.io/en/stable/advanced_topics/i18n.html?highlight=i18n#basic-example is an example how the language links can be implemented in the template, but I only want to show the links to pages already translated. Using django_debug_toolbar I couldn't find a template variable to check if a page is translated. How can I accomplish that? Also related: Using django.middleware.locale.LocaleMiddleware the preferred language is detected, and I'm on /about_us. However, if I not explicitly set the language code preceding the url (like /de/about_us), the following pages will change back to my browser's language as I navigate at the … -
How can you output the values in the same page?
I'm trying to build an email scrapper on Django and that when you enter a URL, the result should be outputted in the same page. For now, the result is outputted in another page but I want it to be in the same one. I don't know how should I do this. I know I should be using an AJAX request but don't know how to make the form take the action of the AJAX request. Any help I would really appreciate it! form: <form class="card card-sm" action="{% url 'emailsearcher' %}" id='InputSearch' method="GET"> <div class="card-body row no-gutters align-items-center"> <div class="col-auto"> <i class="fas fa-search h4 text-body"></i> </div> <!--end of col--> <div class="col"> <input type="text" class="form-control form-control-lg form-control-borderless" placeholder="Introduce URL" name="Email" id="InputSearch" value="{{ Email.get }}" aria-describedby="searchHelp"> </div> <!--end of col--> <div class="col-auto"> <button class="btn btn-lg btn-success" type="search" onclick="total()">Find Email Address</button> </div> <!--end of col--> </div> </form> -
How to get multiple related models with as few queries possible
I am having some difficulty linking/obtaining data from 3 models all related to one another. I'm thinking i've either designed them incorrectly or I don't fully understand how to work with parental and many-to-many fields. There are 3 models (full models shown at end of question): ClubManager Where club names are entered ClubTimetables The timetable, relevant to the ClubManager DaysOfTheWeek Mon-Sun, used by ClubTimetables For which I am trying to retrieve information from all of them: the name of the club, its timetable(s) and for each timetable the days of the week it's linked to. However, I can't seem to do it in a way that doesn't constantly hit the database. First thing I tried was to get ClubManager and select_related it's timetable but couldn't figure out how to preselect the DaysOfTheWeek it was connected with. The approach I am trying now is to instead get the ClubTimetable and use select_related and prefetch_related on both the models it's linked with, like so timetable = ClubTimetables.objects.select_related('attached_to').prefetch_related('weekday') for t in timetable: print(t.attached_to.name) This results in such a query connection.queries [{'sql': 'SELECT "club_clubtimetables"."id", "club_clubtimetables"."sort_order", "club_clubtimetables"."address_line_1", "club_clubtimetables"."address_line_2", "club_clubtimetables"."address_city", "club_clubtimetables"."address_county", "club_clubtimetables"."address_country", "club_clubtimetables"."map_coord_lat", "club_clubtimetables"."map_coord_lon", "club_clubtimetables"."attached_to_id", "club_clubtimetables"."start_time", "club_clubtimetables"."end_time", "club_clubmanager"."id", "club_clubmanager"."name" FROM "club_clubtimetables" INNER JOIN "club_clubmanager" ON ("club_clubtimetables"."attached_to_id" … -
DRF: Route with and without arguments
I have a pretty simple urls.py: router = routers.DefaultRouter() router.register(r'products', views.ProductViewSet, basename = "product") urlpatterns = [ url('^api/', include(router.urls)), ...] where Product looks like this: class Product(models.Model): user = models.ManyToManyField(User, related_name="User", blank = True) name = models.CharField('name', max_length=120) What I want is a view that returns products from a user, if a user is handed to it, and returns all products when no user is submitted. I read multiple posts 1, 2, 3 but I could not solve it. Getting all products works: class ProductViewSet(LoginRequiredMixin, viewsets.ViewSet): login_url = "/login/" def list(self, request): data = [{"products": Product.objects.all(),}] results = ProductSerializer(data, many = True).data return Response(results) Serializer.py: class ProductSerializer(serializers.Serializer): products = serializers.CharField(max_length = 120) Can I add another method to my ProductViewSet, and how do I have to alter the urls.py so that I can call (for User with id=1): http://127.0.0.1:8002/api/products/1 -
Django rest-auth, I dont understand Token Authentication and permissions. Cant get credentials
Simple twitter like app, trying to understand permissions and authentication. So i have 3 views for now, all posts views, specific person's posts, and a create post view. Looks like this: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def posts(request): posts = Post.objects.order_by("-created") serializer = PostSerializer(posts, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes((IsAuthenticated,)) def profile(request, name): posts = Post.objects.filter(user__username=name) serializer = PostSerializer(posts, many=True) return Response(serializer.data) @api_view(['POST']) @permission_classes((IsAuthenticated,)) def post_create(request): data = request.data print(request.user) serializer = PostSerializer(data=data) if serializer.is_valid(): serializer.save(user=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Relevant settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'network', # my app ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I'm using rest-auth and allauth currently for logging in and registration, their URLs are working fine i think and I can register users and login and get my tokens. However, whenever i go to one of the URLs, it just says { "detail": "Authentication credentials were not provided." } Even though I LITERALLY just logged in using the rest-auth URL and/or admin. I think I have a slight idea on whats going on after hours of searching, I need to somehow pass in my token whenever I … -
Django change value in queryset from null to string
I'd like to change the value of specific properties in a queryset from null and "null" to "Field does not exist" and "Field exists but does not have value". The model contains a property for custom fields that is returned as null if the field doesn't exits, or "null" if the field exists but does not have a value. Thus the returned list has the following objects: [ "object_1": { "custom_field": null }, "object_2": { "custom_field": "null" } ] I'd like to change both of these values to "Field does not exist" and "Field exists but does not have value" in the result but I do not want to update these values, just change how they are returned. Is that possible? -
Multifield foreign key constraint with Django Models?
What I'm curious about is if the following is possible. Consider these two sets of tables: # report +----+-------------+------+ | id | report_name | year | +----+-------------+------+ | 1 | RPT | 2018 | | 2 | RPT | 2019 | | 3 | RPT | 2020 | +----+-------------+------+ # report_details +----+-----------+----------------+---------+---------+ | id | report_id | report_name_fk | year_fk | details | +----+-----------+----------------+---------+---------+ | 11 | 1 | RPT | 2018 | ABC | | 12 | 2 | RPT | 2019 | DEF | | 13 | 3 | RPT | 2020 | GHI | +----+-----------+----------------+---------+---------+ And: # report +----+-------------+------+ | id | report_name | year | +----+-------------+------+ | 1 | RPT | 2018 | | 2 | RPT | 2019 | | 3 | RPT | 2020 | +----+-------------+------+ # report_details +----+----------------+---------+---------+ | id | report_name_fk | year_fk | details | +----+----------------+---------+---------+ | 11 | RPT | 2018 | ABC | | 12 | RPT | 2019 | DEF | | 13 | RPT | 2020 | GHI | +----+-----------+----------------+---------+---------+ Lets say I want to change the report_name in the table report for year = 2020 to just TST. I want that to CASCADE to related tables … -
how to check if the logged in user is a member of M2M field in the template? django
i have build a project to for real estate , a real estate owned by one person (account) and have multiple admins M2M class RealEstate(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,default='') admins = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='managers') code = models.UUIDField(unique=True,default=uuid.uuid4,editable=False) in the template (navbar) if logged in user was owner or an user within admins(managers) list create new post will appear i tried this {% if request.user.realestate.owner or request.user in request.user.realestate.managers.all %} <a class="nav-link" href="{% url 'listings:new_post' %}"> <i class="fas fa-user-plus"></i>+create new post</a> </i> {% else %} # some more condition but the after the or not worked request.user in request.user.realestate.managers.all to check if the logged in user is in the admins list or not , but doesnt work !is there something i have to change in the template!? or is it a right way to set similar conditions ? thank you -
how to make two different logins for users and admins
Here I m using django allauth for user management and I want to make two different logins for users and admin. Also the problem is how to save the user rating and review in the database. -
TypeError: UserAdmin() takes 1 positional argument but 2 were given
I am making an abstract user in which i get this error please solve it . i want make a custom user model django. Error (venv) python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/mraries/Documents/shift_api/shift/admin.py", line 24, in <module> admin.site.register(User,UserAdmin) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 134, in register self._registry[model] = admin_class(model, self) TypeError: UserAdmin() takes 1 positional argument but 2 were given Admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import gettext as _ from .models import … -
OperationalError: foreign key mismatch in Django
I'm receiving this error when I try to apply this changes: class Category(models.Model): name = models.CharField(primary_key=True, max_length=64) class Auction(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=100, default="") image_url = models.CharField(max_length=100, default="https://elitescreens.com/images/product_album/no_image.png") category = models.ForeignKey(Category, on_delete=models.CASCADE, default="undefined", related_name="auction_category") Every auction object has a category associated, but I can't avoid the mismatch error. What have I done wrong? I know there are similar questions in stackoverflow but they weren't enough to help me out in this -
Consume an API in Django REST, server side, and serve it ,client side, in Angular
I have an Angular app that consume API client side. Since it's bad practice to do so (I don't want to expose my API credentials), I decided to split into backend/ frontend before myapp get to big. I succeed to implement my Angular into a Django REST framework app and everything is working fine. But now I need to change my API logic and have DRF consume the external API I had: Angular <---API---> ext data Now I have: Django/ Angular <---API---> ext data What I need: Angular <---API---> Django <---API---> ext data But I am very confused about how to accomplish it. I have experience with setting up API endpoints in DRF, but only for data from models within DRF. I know as well how to consume API in Django. But how can I chain two API calls? Do I have to create a model to store the queries and then the response? Do I need to write serializers even if the returned data is json all the way? How my frontend will now that the data from the external API is available? What I need is someone to explain me what is the pattern for this task. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use activity.set() instead. React client/Django server|
I'm a beginner with a few months under my belt but am practically new to django. class Locations(ViewSet): def create(self, request): user = VacaUser.objects.get(user=request.auth.user) location = Location() # activity = Activity.objects.filter() location.user = user location.title = request.data["title"] location.time = request.data["time"] location.description = request.data["description"] location.photo = request.data["photo"] try: location.save() # location.set(activity) location.activity = Activity.objects.get(pk=request.data["activity"]) serializer = LocationSerializer(Location, context={'request': request}) return Response(serializer.data) except ValidationError as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) class Location(models.Model): time = models.DateField(models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)) user = models.ForeignKey("VacaUser", on_delete=models.DO_NOTHING, related_name="vacauser") title = models.CharField(max_length=50) description = models.TextField(max_length=200) activity = models.ManyToManyField("Activity", related_name='activities', blank=True) photo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) class Activities(ViewSet): def create(self, request): activity = Activity() activity.name = request.data["name"] try: activity.save() serializer = ActivitySerializer(activity, context={'request': request}) return Response(serializer.data) except ValidationError as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) class Activity(models.Model): name = models.CharField(max_length=50,) ` POSTMAN EXAMPLE : This is one of my fixtures. { "id": 1, "time": "2018-04-12", "user": { "id": 1, "bio": "Me", "user": 1 }, "title": "Hawaii", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mattis lectus sit amet velit viverra viverra. Cras efficitur volutpat sem.", "photo": "http://localhost:8000/https%3A/res.cloudinary.com/db1peeart/image/upload/v1601909566/Michael/hawaii2_jwrmwb.jpg", "activity": [ { "id": 1, "name": "Swimming" }, { "id": 2, "name": "Beach" }, { "id": 3, "name": "Hike" }, … -
Django Javascript: Why Won't My Function Change The Styling
I have a like button that is part of a form that uses a javascript function. The function seems to work as intended (adding or subtracting a like from the like count) so it must be changing the class of the button but it won't update the styling unless i refresh the page. I want the styling to turn the button background white when it is liked and transparent when not liked. Script: $(document).ready(function() { $('.like_form').submit(function(e){ e.preventDefault() const post_id = $(this).attr('id') console.log(post_id) const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() const trimCount = parseInt(likes) console.log(trimCount + 1) var element = document.getElementById("like_button"); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'post_id': post_id, }, success: function(response){ if (element.classList.contains("liked_post")){ res = trimCount - 1 element.classList.remove("liked_post") } else if (!$(this).hasClass("liked_post")) { res = trimCount + 1 element.classList.add("liked_post") } $(`.like_count${post_id}`).text(res +' Likes') }, error: function(response){ console.log('error', response) } }) }) }); form: <form action="{% url 'like_post' item.id %}" class="like_form" id="{{ item.id }}"> {% csrf_token %} {% if user in item.likes.all %} <button type="submit" class="like_btn liked_post" name="post_id" value="{{ item.id }}"><div class="liked_btn" id="like_button">Like</div></button> {% else %} <button type="submit" class="like_btn" name="post_id" value="{{ item.id }}"><div class="liked_btn" id="like_button">Like</div></button> {% endif %} </form> -
Django:Permission || List View filter Objects based on current user
I am looking for a way to list only certain objects on which user has reader access. I have looked at Django Documentation and implemented has_object_permission but that does't work for List View. This is my my_permissions.py file from rest_framework import permissions ACCESS_LIST = ["1", "2", "3"] #This is for example this list will be based on user access class IsUserAdmin(permissions.BasePermission): def has_object_permission(self, request, view, obj): user = request.session['samlUserdata'] return obj.Number in ACCESS_LIST This is my view file from .models import DemoGroup from .serializers import dmSerializer from rest_framework.viewsets import ModelViewSet from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework import generics from django.http import JsonResponse from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.permissions import BasePermission from .my_permissions import IsUserAdmin ACCESS_LIST = ["1", "2", "3"] #This is for example this list will be based on user access class DemoViewSet(ModelViewSet): permission_classes = (IsUserAdmin,) serializer_class = dmSerializer queryset = DemoGroup.objects.all() # Overriding List View def list(self, request): user = self.request.session['samlUserdata'] queryset = DemoGroup.objects.filter(Number__in=ACCESS_LIST) serializer = dmSerializer(queryset, many=True) return Response(serializer.data) Currently I am able to filter List View with queryset but I want to explore if there is other efficient method which Django Rest Frameworks provides like permissions which can be … -
Django - get an IP from which model inst was changed
In my models.py I have: class User(AbstractUser): def save(self, force_insert=False, force_update=False, *args, **kwargs): created = self.pk is None super(User, self).save(*args, **kwargs) print("Hello") pprint(kwargs) user = kwargs.get('instance', None) ip = request.META['REMOTE_ADDR'] I want to log an IP from which User model inst was changed. But I can't since request is not in models. How can I get access to it? Thanks. -
Invalid syntax with path in Django 3.1.5
I'm getting a syntax error even though I've checked the code many times. I'm new with Django so I'm not sure if I'm missing something else. So this is my code in my urls.py: # Django from django.contrib import admin from django.urls import path, include from django.conf import settings # media from django.conf.urls.static import static urlpatterns = [ # Admin url path path('admin/', admin.site.urls, name='admin'), # Posts url paths path('', include(('posts.urls', 'posts'), namespace='posts')), # User url paths path('users/', include(('users.urls', 'users'), namespace='users')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I'm following a tutorial and I've literally copy-pasted what was working for the tutor and it throws the same error as shown in the image. Error Any ideas what this might be? -
Django: Is it possible to add constraint on model level only (Not on DB level)
Is there a way to add a unique constraint on model level only (not on DB level) in Django? -
Django filter datetime based on month and day only in a range
I am trying to filter model objects in between a certain range. If I consider the year then I am able to do it fine like below: today = datetime.date.today() start_date = today + datetime.timedelta(days = 1) end_date = today + datetime.timedelta(days = 7) for required_day in required_days: filter_dict.update({ required_day + "__range" : [start_date, end_date] }) list_of_Q = [Q(**{key: val}) for key, val in filter_dict.items()] if list_of_Q: model_objects = Model.objects.filter(reduce(operator.or_, list_of_Q)) But what I would like to do is to filter only by the values of day and month of the datetime. I tried as below: for required_day in required_days: filter_dict.update({ required_day + "__month__gte" : start_date.month, required_day + "__day__gte" : start_date.day, required_day + "__month__lte" : end_date.month, required_day + "__day__lte" : end_date.day, }) But I am not getting the correct values here. How can I rectify it? -
Django Default Image is showing
why i can't see default image here below are my model and profile.html file: Model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_pics',default='default.jpg') def __str__(self): return f'{self.user.username} Profile' Profile.html: {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{user.email}}</p> </div> </div> <!-- FORM HERE --> </div> {% endblock content %} Thank you in advance... -
Django Add Field Error to Non-Model Form Field
Can anyone help me understand how to properly send a field error back to a non-model form field in django that is not using the standard django form validation process? Rendering the form again with error and user data still entered for correction and resubmission? Example html for a simple username field that is validated on the model level: <!--form--> <form id="profile" class="small" method="POST" action="{% url 'profile' %}"> {% csrf_token %} <!--Username--> <label for="username">Username <span style="font-style: italic;">(create a unique display name that will appear to other users on the site)</span></label> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="username">@</span> </div> <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="username" name="username" value="{% if profile and profile.username is not None %}{{ profile.username }}{% endif %}"> </div> <button type="submit" class="btn btn-primary" name="profile_form" value="profile_form">Save</button> </form> View class ProfileView(View): def get(self, request, *args, **kwargs): # get request... def post(self, request, *args, **kwargs): if request.method == "POST": # check if profile_form submitted if 'profile_form' in request.POST: # get user form data profile_data = request.POST.dict() # get current user profile user_profile = Profile.objects.get(my_user=request.user) # check username entry against current if user_profile.username == profile_data['username']: messages.success(request, "This is the current user.") else: try: # try to save the new username user_profile.username = profile_data['username'] … -
Django add object on database after clicking button
I'm new to Django and I'm trying to create an events web app, I already have created the events, and when I'm on that particular event (with URL /event/pk/) of that particular event I have a join button, which has to add the logged user id and the event id to a model attend. My attend model is the following: class Attend(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) event_id = models.ForeignKey(Event, on_delete=models.CASCADE) In the Join button I added a POST form like this: <form action="{% url 'event-join' object.id %}" method="POST"> <button type="submit" id="event-info-join" class="icon" title="Join Event"> <i class="material-icons" title="Join Event">add</i>Join Event </button> </form> And in my urls ('event/int:pk/' because I want to refresh the page after joining): path('event/<int:pk>/', EventJoinView, name="event-join"), And the view I created is the following, my intention here is getting the request and the pk of the event, with that request get the user id using request.user.pk (which I think it is not working), create a new attend object and save it in the attend model: def EventJoinView(request, pk): if request.method == 'POST': event = Event.objects.get(pk=pk) user = request.user new_attend = Attend(user_id=user.pk, event_id=event.pk) new_attend.save() With this I am getting "CSRF verification failed", I know this would be solved by … -
Admin: Show related inline ManyToMany objects as MultipleChoiceField
I've overridden the UserAdmin class and wanted to add a user profile and some related objects as inline. I get now a table with related objects. But that's not really ideal for my application, it's a bit cumbersome to change the related objects, and there's no need to add new objects this way. I'd like to have simple MultipleChoiceField containing the related objects. Is there an easy way to achieve this? Here's my userprofile/admin.py: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from django_admin_listfilter_dropdown.filters import RelatedOnlyDropdownFilter from driverslog.models import Branch from driverslog.models import Car from .models import Userprofile User = get_user_model() class ProfileInline(admin.TabularInline): model = Userprofile can_delete = False max_num = 0 extra = 0 fk_name = 'user' class CarInline(admin.TabularInline): model = Car.users.through can_delete = True verbose_name = _('Car') verbose_name_plural = _('Cars') extra = 0 class BranchInline(admin.TabularInline): model = Branch.users.through can_delete = True verbose_name = _('Branch') verbose_name_plural = _('Branches') extra = 0 class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, BranchInline, CarInline) list_display = ('username', 'first_name', 'last_name', 'is_staff', 'is_superuser', 'represents') list_filter = ('is_active', 'is_staff', 'is_superuser', ('groups', RelatedOnlyDropdownFilter), ('branches', RelatedOnlyDropdownFilter), ('profile__represent', RelatedOnlyDropdownFilter), ('car', RelatedOnlyDropdownFilter)) def represents(self, obj): return obj.profile.represent.count() represents.short_description = _('Represents') admin.site.unregister(User) admin.site.register(User, …