Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
operator does not exist: bigint = uuid LINE 1: ...NER JOIN "users" ON
I decided to change my default id today because I thought of scalability of my project. Since I changed the user main primary key to UUID I ran into a series of errors, some of which I could fix thanks to some questions on stackoverflow. I'm using the "oauth2_provider_access token" for my authentication from the oauth2_provider. I don't really know again from where this other one came from but when ever I try my API I'm stuck. My error log below [08/Feb/2023 08:46:54] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Internal Server Error: /admin/ Traceback (most recent call last): File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: operator does not exist: bigint = uuid LINE 1: ...NER JOIN "users" ON ("django_admin_log"."user_id" = "users".... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/template/response.py", line 114, in render . . . . . . File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute with self.db.wrap_database_errors: File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/db/utils.py", line 91, … -
Django annotate with dynamic value
Hi in my model i have property that fully is in cache, not in database class Model(models.Model): .... @property def _get_last_seen_cache_name(self) -> str: return f'{self.hostname.upper()}_last_seen' @property def last_seen(self) -> datetime | None: cached = cache.get(self._get_last_seen_cache_name, None) if isinstance(cached, datetime): return cached return None def update_last_seen(self) -> None: cache.set(self._get_last_seen_cache_name, get_now().replace(microsecond=0), None) How can i annotate with this value last_seen queryset. Want use sorting on this column in admin page. But for this, i need get values from cache on annotation, execute cache.get() with proper key name. Something like this, not working example: queryset = super().get_queryset(request) queryset = queryset.annotate(last_seen=Value(cache.get(Concat('hostname', Value('_last_seen')))), CharField())) or queryset = queryset.annotate(last_seen=Value(cache.get(f"{F('hostname')_last_seen}")), CharField())) I can annotate with literal value, but how annotate with dynamic value, that doesnt exist in database, but in cache or in memory only? How to do hostname substitution in a function? -
Correct Django serializer implementation for many to many field
I have two django models that are related with a many to many field: class Member(models.Model): user = models.OneToOneField(to=settings.AUTH_USER_MODEL) date_of_birth = models.DateField() bio = models.TextField() class Book(models.Model): name = models.CharField(max_length=255) author= models.CharField(max_length=255) description = models.TextField() read_by = models.ManyToManyField(to=Member, related_name='books_read') The serializers for these models are: class MemberSerializer(serializers.Model): id = serializers.IntegerField(read_only=True) user_id = serializers.IntegerField(read_only=True) class Meta: model = Member fields = ['id', 'user_id', 'date_of_birth', 'bio'] class BookSerializer(serializers.Model): id = serializers.IntegerField(read_only=True) class Meta: model = Book fields = ['id', 'name', 'author', 'bio'] I want to create an endpoint to be able to add a book to a member. The only way I could write a serializer for it was: class BookIdSerializer(serializers.Model): class Meta: model = Book fields = ['id'] def update(self, **kwargs): # logic to add book with passed id to the authenticated user's member profile This however feels very wrong for two obvious reasons: 1 - There is an entire serializer object just to receive a book id 2 - It is not even generic because it performs a very specific function of adding a book with passed book id to a member I am sure there is a better way of doing this. Kindly guide me if you know. -
Django images upload fails
I am using django to upload a image to the database (POST request) and show the same in the site. but for some reason my image is not uploading models.py - from django.db import models class image_classification(models.Model): pic=models.ImageField(upload_to='images') views.py from django.shortcuts import render from .models import image_classification from django.http import HttpResponse, HttpResponseRedirect # def home(request): # print('here you go ') # images=image_classification.objects.all() # url=images[len(images)-1].pic.url # return render(request,'home.html',{'print':'everything is ok','image':url}) def home(request): print('here you go ') images=[] images=image_classification.objects.all() if len(images) > 0: url=images[len(images)-1].pic.url else: url="place holder image url" return render(request,'home.html',{'print':'everything is ok','image':url}) #handles uploaded images def uploadImage(request): print('image handling ') img= request.FILES['image'] image=image_classification(pic=img) image.save() return HttpResponseRedirect('/') url of the app from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home,name='home') ] urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url.py for project (incase you need this) from django.contrib import admin from django.urls import path, include from ImageClassifier import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path("admin/", admin.site.urls), path('', include('ImageClassifier.urls')), ] lastly settings.py (not sure if this is needed) MEDIA_ROOT= os.path.join(BASE_DIR,'ImageClassifier/media/') MEDIA_URL= '/media/' STATIC_URL = "/static/" STATIC_ROOT= os.path.join(BASE_DIR, 'static') and this is the error i am getting on the … -
django web server running with iis doesn't run static css js image files
enter image description herehi I have a django web server project running on ISP and static file is not working How do I make changes to Internet Information Services (IIS) and web cofig file for static files to work? ` <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <!-- Your django path --> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\pax_web_server_app" /> <!-- Your djangoname.settings --> <add key="DJANGO_SETTINGS_MODULE" value="pax_web_server_app.settings" /> </appSettings> <system.webServer> <handlers> <add name="paxsite" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python311\python.exe|C:\Python311\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" /> </handlers> <staticContent> <mimeMap fileExtension=".tab" mimeType="static/css" /> </staticContent> </system.webServer> ` https://learn.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap I did the instructions on the microsoft website but it still didn't work -
Django Store Engine and Celery
Can I use django.contrib.sessions.backends.db with Celery in my Django project? I ask this because when I execute login(request, user, user.backend), request's session_key is not stored inside DjangoSession table. this is the piece of code: engine = import_module(settings.SESSION_ENGINE) # Create a fake request to store login details. request = HttpRequest() request.session = engine.SessionStore() login(request, user, user.backend) # Save the session values. request.session.save() -
django group by foreign key aggregation
i have models like this: class Coin(models.Model): symbol = models.Charfield() class User(models.Model): phone_number = models.Charfield() class Portfo(models.Model): class Meta: unique_together = ( "user", "coin", ) user = models.ForeignKey( to=User, on_delete=models.CASCADE, null=False, related_name="portfo", ) coin = models.ForeignKey( to=Coin, on_delete=models.CASCADE, null=False, related_name="owners", ) available = models.DecimalField( max_digits=40, decimal_places=20, default=Decimal(0), ) blocked = models.DecimalField( max_digits=40, decimal_places=20, default=Decimal(0) ) i want to aggregate portfo grouped by users like this: [ { "user_id":1, "portfo":{ "coin_1_symbol":Decimal("1"), "coin_2_symbol":Decimal("2"),... } }, { "user_id":2,... },... ] or this: [ { "user_id":1, "portfo":[ {"coin_symbol":"some_symbol","total":Decimal("1")}, {"coin_symbol":"some_symbol","total":Decimal("2")},... ] },... ] i tried aggregation with values but it returns this result: >> Portfo.objects.exclude(available=0,blocked=0).annotate(total=Sum(F("available")+F("blocked"))).values("user_id","total","coin__symbol") [{"user_id":1,"coin_1_symbol":"some_symbol","total":"Decimal("1")},{"user_id":1,"coin_2_symbol":"some_symbol", "total":Decimal("2")},...] is there any way to do this with django orm? Thanks for your help:) -
How to connect views with forms and save it in db Django
I have a form which trying to connect to multiple views where i get multipleModelChoice form-select and i actually dont know how to save them in db or connect them to my "WorkLog" model I got validation error which i called in "create_worklog" func with messages.error Any advices pls? models.py class WorkLog(models.Model): worklog_date = models.DateField(verbose_name='Дата', ) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, blank=True, related_name='contractor_user',on_delete=models.CASCADE) contractor_counter = models.ForeignKey(CounterParty, blank=True, related_name='contractor_user', on_delete=models.CASCADE) contractor_object = models.ForeignKey(ObjectList, blank=True, related_name='contractor_user', on_delete=models.CASCADE) contractor_section = models.ManyToManyField(SectionList, default=None, related_name='contractor_user' description = models.TextField(blank=True,) forms.py class WorkLogForm(forms.ModelForm): worklog_date = forms.DateField(label='Дата', widget=forms.DateInput( attrs={'type': 'date', 'class': 'form-control', 'placeholder': 'Введите дату'})) description = forms.CharField(label='Описание', widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Описание'})) class Meta: model = WorkLog fields = ( 'worklog_date', 'contractor_counter', 'contractor_object', 'contractor_section', 'description' ) views.py def object_list(request): get_counter = request.GET.get('counter') objects = ObjectList.objects.filter(contractor_guid__in=[get_counter]) context = {'objects': objects, 'is_htmx': True} return render(request, 'partials/objects.html', context) def sections_list(request): get_object = request.GET.get('objects') sections = SectionList.objects.filter(object=get_object) context = {'sections': sections} return render(request, 'partials/sections.html', context) def create_worklog(request): counter_party = CounterParty.objects.filter(counter_user=request.user) if request.method == 'POST': form = WorkLogForm(request.POST) if form.is_valid(): work_log = form.save(commit=False) work_log.author = request.user work_log.contractor_counter = counter_party work_log.contractor_object = object_list(request).objects work_log.contractor_section = sections_list(request).sections work_log = form.save() messages.success(request, 'Everything okay', {'work_log': work_log}) return redirect('create_worklog') else: messages.error(request, 'Validation error') … -
Django Wagtail dynamic Menu's based on User and User Role
Using Django-Wagtail and Wagtail Menu's. I want to build a system with the following types of characteristics. I have a class of user (Vendor, Supplier) Each created user would need to be one of these two classes. Each class of user has different roles and the roles differ from class to class. e.g. Vendor: finance, stock, admin Supplier: finance, stock, admin, driver. What I have done is create a class called UserType and both "Vendor" & "Supplier" inherit from this class. Then added a field to the User class that selects which type of user they are. class UserType(model.Model): common fields....... class Vendor(UserType): child_vendor_only_fields..... class Supplier(UserType): child_supplier_only_fields..... class User(AbstractUser): userVar = models.ForeignKey(UserType, on_delete=models.SET_NULL, null=True, blank=True) I have also used the wagtail admin to create custom roles for each of these classes as described above. Clearly what "Vendors" can create, read, update and delete varies from that of a "Supplier". And still within that what the finance role can do within the "Vendor" differs from what "Stock" can do. How would I create a dynamic menu that displays different menu's for these permutations? My initial thoughts were inspired by this. Simply adding a choicefield USER_TYPE_CHOICES = ( ('Vendor', 'Vendor'), ('Supplier', 'Suplier')) … -
Join and get queryset accordring to many to many field
I have MyUser model with ForeignKey and ManyToMany related fields city and skills: class MyUser(AbstractBaseUser): email = models.EmailField() skills = models.ManyToManyField('jobs.Skill') class Skill(models.Model): name = models.CharField() suppose this my table data in database {'email': 'some@email.com', 'skills': ['Python', 'Java']}, {'email': 'another@email.com', 'skills': ['JavaScript', 'C#', 'Python']} >>> MyUser.objects.all().count() output is 2 but iwant MyUser.objects. .......... answer to 5 my like following data {'email': 'some@email.com', 'city': 'London', 'skills': 'Python'}, {'email': 'some@email.com', 'city': 'London', 'skills': 'Java'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'JavaScript'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'C#'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'Python'}, -
Django-Pass data from html to python and wise versa
Index.html <form class="grid" method="POST" action={% url 'result' %}> {% csrf_token %} <textarea name="name" /></textarea> <button type="submit"">Detect</button> </form> <label>{{name}}</label> view.py def result(request): name = request.POST['name'] name=preprocessing(name) return render( request, "index.html", name=name ) urls.py urlpatterns = [ path("", views.homePage, name='result'), ] i am making a website using django where i have to get data from html page in python file and after getting data i have to perform some preprocessing on data. and after that again return back to the same page with some new information when i press a button. The problem is that i when i press button than i move to the same page button the new information is not displaying after clicking on a button -
Unit testing a unittest custom test runner in Django
I am trying to unit test a custom test runner using unittest framework but I get this error. File "/usr/local/lib/python3.7/dist-packages/django/test/runner.py", line 466, in setup_test_environment setup_test_environment(debug=self.debug_mode) File "/usr/local/lib/python3.7/dist-packages/django/test/utils.py", line 111, in setup_test_environment "setup_test_environment() was already called and can't be called " RuntimeError: setup_test_environment() was already called and can't be called again without first calling teardown_test_environment(). I understand that this error message is pretty self explanatory but the problem with running teardown_test_environment within the unit test ends up in this error message File "/usr/local/lib/python3.7/dist-packages/django/test/runner.py", line 588, in teardown_test_environment teardown_test_environment() File "/usr/local/lib/python3.7/dist-packages/django/test/utils.py", line 144, in teardown_test_environment saved_data = _TestState.saved_data AttributeError: type object '_TestState' has no attribute 'saved_data' Has anyone encountered something like this before? -
Django same function data not showing after page render
I am creating university management system using django. I have created faculty(teacher) registration form. For that, in my views.py def faculty_registration(request): data = {} form = FacultyRegisterForm() activetab = 'list' if request.method == 'POST': activetab = 'add' form = FacultyRegisterForm(request.POST) if form.is_valid(): userdata = User() if User.objects.filter(username=request.POST.get('email')).exists(): messages.error(request, f"This email already exists.") return redirect('/faculty/faculty_registration') else: userdatafirst_name = request.POST.get("first_name") userdata.username = request.POST.get('email') userdata.email = request.POST.get('email') try: fac_ID = Faculty.objects.last().id except: fac_ID = 0 LastInsertId = fac_ID+1 print('after_id',LastInsertId) password = User.objects.make_random_password() faculty_pw = password+str(LastInsertId) print("pass",faculty_pw) userdata.password = make_password(faculty_pw) print( "teacher_pasword",userdata.password) userdata.save() fac = Faculty() fac.faculty_college_id = request.POST.get("faculty_college") fac.faculty_programme_id = request.POST.get('faculty_programme') fac.salutation = request.POST.get("salutation") fac.first_name = request.POST.get("first_name") fac.middle_name = request.POST.get("middle_name") fac.last_name = request.POST.get("last_name") fac.phone = request.POST.get("phone") fac.email = request.POST.get("email") fac.address = request.POST.get('address') fac.department = request.POST.get('department') fac.highest_qualification = request.POST.get("highest_qualification") fac.years_of_experience = request.POST.get('years_of_experience') fac.previous_institute = request.POST.get('previous_institute') # fac.documents = request.POST.get("documents") if 'documents' in request.FILES: filename = request.FILES['documents'] if str(filename).lower().split('.')[-1] == 'pdf': if int(len(request.FILES['documents'].read())) < (3 * 1024 * 1024): fac.documents = request.FILES['documents'] else: messages.warning(request, "please upload a pdf within 3 mb") navshow = 'add' return redirect('faculty_registration') else: messages.warning(request, "please upload a pdf") navshow = 'add' return redirect('faculty_registration') fac.photo = request.FILES.get('photo', 'faculty_picture/def.png') fac.created_by_id = request.user.id fac.user_id = userdata.id fac.save() assign_role(userdata, 'teacher') html_content = render_to_string("email_template.html",{'title':'Kindly Note your … -
Retrive data from Database
1- am making a sample project for my learning I have a html code and how to retrieve data's from database through this code in Django Blood Group O+ O- A+ A- B+ B- AB+ AB- 2- after press search i need to display a selected blood groups results in that / new page 3- my views.py code as follows def search(request): return render(request,'search.html') and in database table name = home_index_bgs column names as follows NAME FATHERS NAME GROUP GENDER DONATED any one can help with this problem for this, its only for educational purpose not for any kind of project -
How can I get the records (of a specific model) of both request.user and a specific user?
I am not very professional in django rest... I wrote a blog with django rest framework and There is no problem when I want to get all the records related to the Article model or get a specific article, for example But what I want to do is to send an user id(or an user name) to the view when I click on the user's name. and as a result display all the records of the Article model related to the request.user and all the records of the Article model related to the user whose name was clicked. In fact, I want to click on the name of each user, in addition to getting the Articles of that user, the Articles related to the request.user will also be taken This is what I have done so far... #models.py class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField author = models.ForeignKey(User , on_delete = models.CASCADE) content = models.TextField(null = True) publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) status = models.BooleanField(default = False) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) pic = models.ImageField(upload_to="img", blank=True, null=True) def __str__(self): return self.user.username … -
Related object does not exists in django only admin login
showing RelatedObjectDoesNotExist in Django only when admin login all others can log in make changes and works fine. I am doing an crud application with user interface -
Django Summernote icons dont appear
I am working on a MAC and Windows for this issue. Summer note will not display icons in chrome or edge on either Mac or windows and deployed or locally. Everything works fine in safari and on my iPhone. I migrated and collected the static files and they showed up in my s3 bucket. Seems like everything is set up correctly since it does work. settings.py INSTALLED_APPS = [ 'django_summernote', ] SUMMERNOTE_THEME = 'bs5' SUMMERNOTE_CONFIG = { 'summernote': { 'width': '100%', } } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/', include('django_summernote.urls')), ] forms.py from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget class CreateVenueForm(ModelForm): class Meta: model = Venue fields = ('name', 'address', 'city', 'state', 'zip', 'description',) widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Gived your venue a title'}), 'address': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Number and Street name'}), 'city': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'city'}), 'state': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Give your event a title'}), 'zip': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Zip'}), 'description': SummernoteWidget(), } template <div class="row"> <div class="col">{{form.description.label}}<br/>{{form.description|safe}}</div> </div> -
Implement adding an image from gallery to favourites, which is displayed on a separate page// DJANGO/JS
Essentially I am creating a web gallery with Django/JS for a project, however the project needs to feature CRUD functionality. Currently I have a functioning modal when an image in the gallary is clicked, along with an "Add to Favourites" button when the user is logged in. I am struggling to come up with a way to append these images dynamically to the favourites HTML page. I am unsure whether this is easier done with JS or Django. Here is my current JS code: $(function() { $('.myImg').each(function() { $(this).click(function() { $('#myModal').css('display', 'block') $('#imgModal').attr('src', this.src) $('.navbar').css('display', 'none') }) /* Favourite image functionality */ var favouriteImages = [] imgSrc = $(this).attr('src', this.src); $('#favourites-btn').click(function () { favouriteImages.push(imgSrc) }) }) $('.close').each(function() { $(this).click(function() { $('#myModal').css('display', 'none') $('.navbar').css('display', 'flex') }) }) }) favouriteImages.forEach(function() { $('#favourites-gal').append(<img class='myImg'/>) }) At the bottom, with the favouriteImages.forEach function, I dont know how to include the src of the specific image that is being appended after clicking the Add to Favorites button. For reference: In the actual gallary of images the code structure of the HTML is: <div class="gal"> <img class="myImg" src="{% static 'img/artsy-gallery/artsy1.webp' %}" alt=""> <img class="myImg" src="{% static 'img/artsy-gallery/artsy2.webp' %}" alt=""> <img class="myImg" src="{% static 'img/artsy-gallery/artsy3.webp' %}" alt=""> … -
MYSQL Database Copy Using Python/Django
I need to create a copy of the database in my MySQL Server using Django Application After a little research, i found mysqldump as the better approach backup_file_path = f"/tmp/{src_database_name}_backup.sql" backup_db_command = f"mysqldump -h {SQL_DB_HOST} -P 3306 -u {SQL_DB_USER} -p{SQL_DB_PASSWORD} {src_database_name} > {backup_file_path}" print(backup_db_command) # TODO: remove with os.popen(backup_db_command, "r") as p: r = p.read() print(f"Backup Output: {r}") restore_command = f"mysql -u root -p{SQL_DB_PASSWORD} {dest_database_name} < {backup_file_path}" with os.popen(restore_command, "r") as p: r = p.read() print(f"Restore Output: {r}") My Queries: Any issues with this approach Any better approaches to do a copy of DB using Either python or Django ORM -
how to properly apply createview?
I have two models, author and book where the book is related to author, now I don't know how to add books to a specific author that I'm working with and redirect the user back to the detailview of that author, I'm also using inlineformset_factory.enter image description here I want to redirect the user to the detailview of the selected author, I also tried overriding the get_absolute_url in the models but it gives me error stating that there are no url to redirect to, I already checked the url names and I'm using the right one.enter image description here -
Serve TailwindCSS with django_plotly_dash
I have a Dash app in Django being served via django-plotly-dash and I'm using Tailwind for the styling across the site. Tailwind seems to be working everywhere except for the Dash app, where it is kind of working, but seems to be overwritten by the Bootstrap at some points. I can see the Tailwind styling without any issues if I run the Dash app on its own, but not when embedded in Django. Here's the view inside Django (and the code for this basic example): And here it is (with garish colors to see the difference) while running Dash and Tailwind without Django: Some of the Tailwind styling is being applied, such as the container mx-auto bit of the Dash layout, but others (e.g. coloring) are being dropped. Here's the code for the Dash app, which is split into layout.py, callbacks.py, and dashboard.py: layout.py: from dash import dcc, html layout = html.Div( className="bg-green-100 container mx-auto my-auto px-15 py-5", children=[ html.Div( className="bg-red-100 py-5", children=[ dcc.Dropdown( id="symbol-input", options=[ {"label": "Apple", "value": "AAPL"}, {"label": "Tesla", "value": "TSLA"}, {"label": "Meta", "value": "META"}, {"label": "Amazon", "value": "AMZN"} ], searchable=True, value="AAPL", ) ]), html.Div( className="max-w-full shadow-2xl rounded-lg border-3", id="price-chart" ) ] ) callbacks.py: from dash import … -
How can I serialize a Many to Many field with added data in Django Rest Framework, without extra keys in the response?
I am using Django 3.2 and Django Rest Framework 3.14. I have Users that should be able to follow other Users, like on a social networking site. When serializing a full User, I would like to get a list of those following Users, as well as additional data, such as the follow datetime. However, I would like the response to stay "flat", like this: { "username":"admin", "followers":[ { "username":"testuser", --additional user fields-- "follow_date":"2023-02-08 01:00:02" }, --additional followers-- ], --additional user fields-- } I can only seem to go "through" my join model using an extra serializer, and end up with this: { "username":"admin", "followers":[ { "user":{ "username":"testuser", --additional user fields-- }, "follow_date":"2023-02-08 01:00:02" }, --additional followers-- ], --additional user fields-- } Note how there is an additional user key "user":{ "username":"testuser", --additional user fields-- }, I don't want that there! My model looks something like this: class Follower(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, related_name="followers") follower = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, related_name="following") follow_date = models.DateTimeField(auto_now_add=True) My serializers look like this (extra fields trimmed for brevity): class UserSnippetSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class FollowerSerializer(serializers.ModelSerializer): user = UserSnippetSerializer(source='follower') class Meta: model = Follower fields = ['user', 'follow_date'] class FullUserSerializer(serializers.ModelSerializer): followers = FollowerSerializer(source='user.followers', … -
Django Many to Many Field Set in Model Save Method
I am trying to override the save method in a model with logic to update a couple of many to many fields. Using print statements I can see values updating as expected but the values are not persisted after save. In the below model the change_access_flag is changing as expected with a signal, the prints are executing with the appropriate values, but the allowed_departments and allowed_communities fields are not updating with the printed values. Model class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(null=True, blank=True, max_length=50) payroll_id = models.CharField(null=True, max_length=20) position = models.ForeignKey(Position, null=True, on_delete=models.SET_NULL) primary_community = models.ForeignKey(Community, null=True, on_delete=models.CASCADE, related_name="primary_community") region = models.CharField(max_length=2, choices=RegionChoices.choices, blank=True, null=True) allowed_communities = models.ManyToManyField(Community, blank=True, related_name="allowed_community") allowed_departments = models.ManyToManyField(Department, blank=True) access_change_flag = models.BooleanField(default=False) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Meta: verbose_name_plural = "People" ordering = ['position__position_code', 'user__last_name', 'full_name'] def save(self, *args, **kwargs): #Set Full Name field if self.user.last_name: self.full_name = f'{self.user.first_name} {self.user.last_name}' super().save(*args, **kwargs) #Change flag set in signals, set for events that require updating access settings if self.access_change_flag: self.access_change_flag = False #Allowed community access access_level = self.position.location_access_level self.allowed_communities.clear() if access_level == 'R': if self.primary_community.community_name == '#': region = self.region else: region = self.primary_community.region if region is not None: communities = Community.objects.filter(region=region) self.allowed_communities.set(communities) self.allowed_communities.add(self.primary_community) … -
Django Forbidden (CSRF token missing.)
I am facing a problem to submit a text in Django. When I click Insert, the message Forbidden (CSRF token missing.): appears. Can somebody help me? I put the CSRF token in the html file, but still no working. I do not know if the csrf is in the wrong part of the code or not. csrf_token %} load crispy_forms_tags %} Modal Header --> Show gabarit × Modal body --> {{commande}} if formset %} Variables endif %} <div id="modal" style="display:none;"> <div id="variables-container"></div> <button class="mb-2 btn btn-outline-secondary mr-2" id="insert-button" type="button" onclick="closeModal()">Insérer <div id='result'></div> </div> </div> </div> <script> function openModal() { var inputText = document.getElementById("input-text").value; var variableNames = inputText.match(/{(.*?)}/g); var variablesContainer = document.getElementById("variables-container"); variablesContainer.innerHTML = ""; for (var i = 0; i < variableNames.length; i++) { var variableName = variableNames[i].slice(1, -1); variablesContainer.innerHTML += "" + variableName + ":"; } document.getElementById("modal").style.display = "block"; } function closeModal() { var inputText = document.getElementById("input-text").value; var variableNames = inputText.match(/{(.*?)}/g); for (var i = 0; i < variableNames.length; i++) { var variableName = variableNames[i].slice(1, -1); var variableValue = document.getElementById("variable-"+ variableName).value; inputText = inputText.replace(variableNames[i], variableValue); } document.getElementById("input-text").value = inputText; document.getElementById("modal").style.display = "none"; document.getElementById("variables-button").style.display = "none"; var xhr = new XMLHttpRequest(); xhr.open("POST", "{% url 'gabarits:save-variables-text' %}", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange … -
Getting Bad Request from POST to DailyWc Model with a ForeignKey to Projects
I'm making a writing app using Django backend and Vue 2 frontend. I have two models— DailyWc and Project. Every day, when the user goes to the site, a new day is created for them to store text (DailyWc handles this). I wanted it to be possible for the user to also assign the text to a Project, with the default being "Unassigned." So, Project is associated with multiple dailywcs. There's a button on my site that the user can press to save their progress for the day. This is where my trouble comes in— I can't make post or update calls because I'm getting Bad Request. My understanding is that I should be able to just pass in the associated project id to make this work, but I think the DailyWc model as it is now is expecting a whole Project object with related fields. My models: # Create your models here. class Project(models.Model): name = models.CharField(max_length=255, default="Unassigned") start_date = models.DateField("today's date", default=datetime.date.today) end_date = models.DateField("end date", default=datetime.date.today) word_count_goal = models.PositiveIntegerField(default=0) def __str__(self) -> str: return f'The Project {self.name} started on {self.start_date} and will end on {self.end_date} with a goal of {self.word_count_goal} and an id of {self.id}.' class DailyWc(models.Model): …