Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicate entries are returning when filtering model
//Model class ClientUserSelectedPodcast(AuditModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_selected_podcast', null=True,blank=True) client_unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='user_selected_unit', null=True, blank=True) client_superunit = models.ForeignKey(SuperUnit, on_delete=models.CASCADE, related_name='user_selected_super_unit', null=True, blank=True) selected_type = models.CharField(max_length=100, default="FAVOURITE") class Meta: ordering = ('-pk',) //view class GetNewClientsCountViewSet(APIView): def get(self,request,*args, **kwargs): from podcast.api_serializers import UnitMiniSerializer from datetime import datetime data=[] total_listener_count={} client_count=Client.get_new_clients_count() gender_wise_count={} # gets the podcast unit count of this month podcast_count=Unit.get_new_podcast_unit_count() user_counts=ClientUser.get_new_client_user_count() most_listened_units,most_liked_units=ClientUserSelectedPodcast.get_total_listened_liked_podcast() inhouse_listened_units,inhouse_liked_units=ClientUserSelectedInhouse.get_total_listened_liked_inhouse() podcast_listener_count=ClientUserSelectedPodcast.get_total_podcast_listeners() inhouse_listener_count=ClientUserSelectedInhouse.get_total_inhouse_listeners() podcast_wise_count=ClientUserSelectedPodcast.get_gender_wise_listeners() inhouse_wise_count=ClientUserSelectedInhouse.get_gender_wise_inhouse_listeners() total_listener_count['podcast']=podcast_listener_count total_listener_count['inhouse']=inhouse_listener_count gender_wise_count['podcast']=podcast_wise_count gender_wise_count['inhouse']=inhouse_wise_count # most liked show of this month most_liked_show= ( ClientUserSelectedPodcast.objects .filter(selected_type='FAVOURITE', created_at__month=datetime.now().month) ) print(most_liked_show) data.append({ 'clients':client_count, 'podcast':podcast_count, 'user':user_counts, 'total_listener_count':total_listener_count, 'most_listened_units':most_listened_units, 'most_liked_units':most_liked_units, 'inhouse_listened_units':inhouse_listened_units, 'inhouse_liked_units':inhouse_liked_units, 'gender_wise_count':gender_wise_count }) return Response(data) i want to get the Most liked show for this month i.e selected*type='FAVOURITE'. Queryset: <QuerySet [<ClientUserSelectedPodcast: ClientUserSelectedPodcast object (552)>, <ClientUserSelectedPodcast: ClientUserSelectedPodcast object (551)>, <ClientUserSelectedPodcast: ClientUserSelectedPodcast object (550)>] The problem here is that query is returing different objects but the value in them is same ie the object 552 and 551 has the same entries i.e 552 -> {'user':224, clientunit:'94ba2e2a47254028b0d3d59eeb5b257d', 'selected*_type':FAVOURITE'}, 551-> {'user':224, clientunit:'94ba2e2a47254028b0d3d59eeb5b257d', 'selected_type':FAVOURITE'} What i want if this occurs duplicate occurs i want to take the count as one and want to return the most liked show for this month -
Why is the full path not saved in the database
I have this function in a Django model to save the profile picture to the database: def photo_directory_path(instance, filename): return "user_{0}/profiles/{1}/images/{2}".format(instance.owner.id, instance.id, filename) Here is the model that uses that function: class FounderProfile(models.Model): background_image = models.FileField( upload_to=bg_directory_path, null=True, blank=True, ) profile_picture = models.FileField( upload_to=photo_directory_path, null=True, blank=True, ) tagline = models.CharField(max_length=100, null=True, blank=True) first_name = models.CharField(max_length=30, null=True, blank=True,) middle_name = models.CharField(max_length=30, null=True, blank=True,) last_name = models.CharField(max_length=30, null=True, blank=True,) bio = models.TextField(max_length=5000, null=True, blank=True,) date_of_birth = models.DateField( null=True, blank=True,) owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name="founderprofile") And here is the settings for handling images: STATIC_URL = "static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles/") MEDIA_ROOT = os.path.join(BASE_DIR, "storage").replace("\\", "/") MEDIA_URL = "/storage/" and my main urls.py file: urlpatterns = [ path("", include("pages.urls")), path("admin/", admin.site.urls), path("api/v1/", include("api.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am using Django Rest Framework and a Vue3 front end. My question is why are the files not saved with the full url which also includes the domain name which in my case is "http://localhost:8000"? Because now I have to add "http://localhost:8000" to the image path otherwise the image does not show and it's not going to work in production -
how do I call delete function in django admin
I am trying to use the Django admin delete function to ensure that the corresponding quantity is deleted from the associated page when the delete function is clicked. For example, I have a class called RestockModel. When I add a new Restock item, the restock quantity can be automatically added in the StockListModel. However, when I need to delete the Restock item, the quantity in StockListModel is not deleted immediately. How can I call the django admin delete function to this statement? Here is the code that how I made the quantity can be added when I create a new restock item: class restockInfo(admin.ModelAdmin): list_display = ["product", "delivery_order_no","restock_quantity", "supplier_name", "created_date"] readonly_fields = ["created_date"] search_fields = ['created_date'] def save_model(self, request, obj, form, change): product = obj.product restock_quantity = obj.restock_quantity if restock_quantity and product.quantity_in_store: if restock_quantity >= 0: obj.product.quantity_in_store = product.quantity_in_store + restock_quantity # don't forget to save stock after change quantity obj.product.save() messages.success(request, 'Successfully added!') super().save_model(request, obj, form, change) else: messages.error(request, 'Invalid Quantity, Please Try Again!!!') return restockInfo This is my restock models: class restockList(models.Model): product = models.ForeignKey("stockList", on_delete=models.CASCADE, null=True) delivery_order_no = models.CharField(max_length=255, null=True) restock_quantity = models.IntegerField(null=True) supplier_name = models.CharField(max_length=255, null=True) created_date = models.DateTimeField(auto_now_add=True, blank=True, editable=False) class Meta: db_table = "restocklist" … -
Does chatgpt provide accurate codes of programming language?
I have seen chatgpt provide codes but i am not sure if its reliable I am expecting the answers to be accurate and reliable. Since chatgpt is a machine learning system i hope it can be amazing if it can give us detailed and be able to let us upload pictures so that we are able to come up with defined structure of answers -
400 Bad Request for djoser based registered user activation
I am new to django and am trying to build a use registration system using djoser, I am getting the email for activation but the activation process is not working, please suggest any solutions, here are the files: models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email settings.py """ Django settings for art_portal project. Generated by 'django-admin startproject' using Django 4.2.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path from datetime import timedelta import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in … -
CSRFToken with Django backend and React frontend
I'm trying to set up CSRF cookies between my django backend and react front end. Currently on my backend I have these two view: @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({'success': 'CSRF cookie set'}) @method_decorator(csrf_protect, name='dispatch') class LoginView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request): data = request.data username = data.get('username') password = data.get('password') user = authenticate(request=request, username=username, password=password) try: if user is not None: login(request, user) return JsonResponse({'message': 'User is authenticated'}) else: return JsonResponse({'message': 'Either password or username is invalid, try again'}, status=400) except: return JsonResponse({'message': 'Something went wrong when authenticating'}) When I test them using Postman they work. I just call the CSRF cookie and copy that cookie and paste it into the X-CSRFToken header of the login on Postman. So both of them work, but then when I test it using the front end it doesnt. From my research this is what I've done. The top one is a CSRFToken.js and the bottom is a piece of my Login.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; const CSRFToken = () => { const [csrftoken, setcsrftoken] = useState(''); const getCookie = (name) => { let cookieValue … -
Issue with adding stock on Django website - Request reset or not hitting server
I'm encountering an issue with my Django website where clients are unable to add stock after a certain period. Our team has tested the functionality successfully from our own computers, but when our client tests it from their side, the request seems to be reset or not hitting the server, even though it initially shows a 200 OK response. We suspect it might be related to antivirus software, as our client is only using the Windows Antivirus Defender. Have any of you experienced a similar issue or have any insights on what could be causing this behavior? Any suggestions or guidance would be greatly appreciated. Thank you! checked all neceessary debug -
How can I serialize a list of objects and return the object if validated?
I have the below in one of my viewset classes: serializer = ResponsesSerializer(data=queryset, many=True) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data response = Response(validated_data, status=status.HTTP_200_OK) return response For testing purposes, queryset is the below list of objects that is being passed to my ResponsesSerializer, where only the first object has a record key: queryset = [ { "C_Ethnicity.r1": 0, "C_Ethnicity.r2": 0, "EaseOfFind.r1": 0, "EaseOfFind.r2": 1, "Leg.r1": 0, "Leg.r2": 0, "record": 17 }, { "C_Ethnicity.r1": 0, "C_Ethnicity.r2": 0, "EaseOfFind.r1": 0, "EaseOfFind.r2": 1, "Leg.r1": 1, "Leg.r2": 0, }, { "C_Ethnicity.r1": 0, "C_Ethnicity.r2": 0, "EaseOfFind.r1": 0, "EaseOfFind.r2": 1, "Leg.r1": 1, "Leg.r2": 0, } ] In the response, the serializer expectedly raises a validation error for the last two objects without a record key, but I don't know why the first object is then empty: [ {}, { "non_field_errors": [ "Missing 'record' key in dictionary." ] }, { "non_field_errors": [ "Missing 'record' key in dictionary." ] } ] This is the ResponsesSerializer: class ResponsesSerializer(serializers.Serializer): def to_internal_value(self, data): return data def validate(self, data): if 'record' not in data: raise serializers.ValidationError("Missing 'record' key in dictionary.") return data I'm new to serializers, and in this case I just want to add validation criteria that each object in the list can … -
'password_reset_done' not found.'password_reset_done' is not a valid view function or pattern name
Here is my urls.py file urlpatterns =[ path("accounts/",include(("django.contrib.auth.urls","auth"),namespace="accounts")), path('',include('app1.urls') ] My application name is app1 The urls in app1 are only view functions -
Django: creating a data migration for a model that is deleted in another migration results in error
I have a Django app with a Character model, which I am migrating to a brand new model (and database table) called Content. I first created the new model, added the migrations for it, then added a data migration to migrate data from Character to Content, and then I removed the Character model and created a migration for that. While working on the steps one by one, and running the new migration on every step, it all worked (locally). But when running ./manage.py migrate on the staging database I get this error: LookupError: App 'characters' doesn't have a 'Character' model. This how how my data migration looks like: content/migrations/0002_auto_20230630_1434.py from django.db import migrations def run_data_migration(apps, schema_editor): Content = apps.get_model("content", "Content") Character = apps.get_model("characters", "Character") # Migration logic here class Migration(migrations.Migration): dependencies = [ ("content", "0001_initial"), ("characters", "0009_alter_character_avatar_alter_character_avatar_crop"), ] operations = [migrations.RunPython(run_data_migration)] Important to know is that 0009_alter_character_avatar_alter_character_avatar_crop is the migration step before the complete removal of the Character model. So since I am depending on that step before the removal and I am using apps.get_model instead of trying to use the Character model directly, I would've thought this just worked? How do I make sure that the data migration within … -
Newbie one-to-many relationship problem in admin
I am writing a simple application where there is a one to many relationship similar to that of Parent to Child, where one parent may have many children. In this case I give the child a foreign key referring to to the parent. The Parent object doesn't mention children because the relationship is in the other direction. That is fine, but in the admin system the page showing the parent insists that the child fieldd be filled in. There are however cases where a parent has no children. How do I tell the admin system that the child field may be left blank? Thanks for any help. -
Importing within file causes error when running Django test but not when using relative import
I have a directory that looks like this AppDir/ ChildDir/ file1.py file2.py tests/ my_test.py Inside the my_test.py file is the import from ..ChildDir.file1 import MyClass This runs fine when file2.py is not being imported in file1.py, however when I added these imports to file1.py: from file2 import myfunc_a, myfunc_b It gives me the error: ImportError: Failed to import test module: ... Traceback (most recent call last): File "/usr/lib/python3.11/unittest/loader.py", line 407, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ... ModuleNotFoundError: No module named 'file2' Executing file1 directly works, its only when running ./manage.py test that it throws this error. However, if I change the import in file1.py to: from .file2 import myfunc_a, myfunc_b ./manage.py test runs fine, however executing file1.py directly throws an error. -
i have this Erorr and i don't fix it [closed]
because I want to run server in django, it's gives an error Error loading mysql.connector module: MySQL Connector/Python C Extension not available (DLL load failed while importing _mysql_connector: The specified module could not be found.) run server but dont' run -
jquery to realtime update a django for loop
Good Afternoon, I am learning on how to use jquery in django and if possible I would like some help on realtime updating a table column in my django app. I have a column with order.status attributes wich can be: orderAwaitingPayment, orderPlaced, orderPackaging, orderReady, ortherOnTheWay and orderDelivered. I already can get a variable order_status and order_number from django channels: <script> const orderSocket = new WebSocket( "ws://" + window.location.host + "/ws/order/" ); orderSocket.onmessage = function(e) { var data = JSON.parse(e.data); var order = data.order var order_number = order.order_number var res_order_status = order.order_status console.log(order_number, res_order_status); }; </script> I have a django template that update the order.status and change color's badge depending on order.status from django database when the page reload but now i would like to update without refreshing the page with jquery. {% for order in orders %} ... <td style="font-size:18px;"> <a href="{% url 'v_dashboard_order_detail' order.order_number %}"> {% if order.status == 'orderAwaitingPayment' %} <span class="badge bg-danger">{{ order.get_status_display }}</span> {% elif order.status == 'orderPlaced' %} <span class="badge bg-primary">{{ order.get_status_display }}</span> {% elif order.status == 'orderPackaging' %} <span class="badge bg-secondary">{{ order.get_status_display }}</span> {% elif order.status == 'orderReady' %} <span class="badge bg-success">{{ order.get_status_display }}</span> {% elif order.status == 'ortherOnTheWay' %} <span class="badge bg-dark">{{ order.get_status_display … -
Django printing multiple form fields
Hello I'm very new to django and python and would ppreciate if you could help me out. I want to create 2 fields, namely password and confirm password but the webpage renders 2 sets of each. this is the code: class RegistrationForm(UserCreationForm): email = forms.EmailField(label="", widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Email Address'})) first_name = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'First Name'})) last_name = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Last Name'})) ph_number = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Phone Mumber'})) password_1 = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Password 1'})) password_2 = forms.CharField(label="",widget= forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Password 2'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'ph_number', 'password_1', 'password_2' ) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['username'].widget.attrs['placeholder'] = 'User Name' self.fields['username'].label = '' self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small></span>' self.fields['ph_number'].widget.attrs['class'] = 'form-control' self.fields['ph_number'].widget.attrs['placeholder'] = 'Phone Number' self.fields['ph_number'].label = '' self.fields['ph_number'].help_text = '<span class="form-text text-muted small"><small>Your number can\'t be more than 10 digits.</small><small>Your phone number is too short</small></span>' self.fields['password_1'].widget.attrs['class'] = 'form-control' self.fields['password_1'].widget.attrs['placeholder'] = 'Password' self.fields['password_1'].label = '' self.fields['password_1'].help_text = '<ul class="form-text text-muted small"><li>Your password can\'t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can\'t be a commonly used password.</li><li>Your password can\'t … -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__blog_post.author_id
I am trying to migrate the changes in my model but getting this issue: django.db.utils.IntegrityError: NOT NULL constraint failed: new__blog_post.author_id Code: from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): author= models.ForeignKey(User,on_delete=models.CASCADE,null=True) text= models.TextField(max_length=300) created= models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.text -
Login Token in Django
hello I have a problem witch I have a User model in my Account app and I have a user inside it with this information { "id": 2, "username": "johndoe", "email": "example@gmail.com", "password": "password123" } my problem is when I POST this JSON data to my LoginView I get this error: (ValueError: Cannot query "johndoe": Must be "User" instance. { "email": "example@gmail.com", "password": "password123" } LoginView, Token code: user = User.objects.get(email=email) token, created = Token.objects.get_or_create(user=user) return Response(data={'token': token.key},status=status.HTTP_200_OK) my User model: class User(AbstractUser): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) full_name = models.CharField(max_length=255, default="") simple_description = models.CharField(max_length=255, default="tourist") biography = models.TextField(null=True, blank=True, default="") profile_picture = models.ImageField(null=True, blank=True) def __str__(self): return self.username I tried to set my User model as the default of the Django User model but when I wanted to create a superuser for my admin panel, it created a regular user with a long password that I didn't put that -
SyntaxError: Expected property name or '}' in JSON
I have a code with Django and JS. At fist I pass a json file to my JS with Django like this : from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework.renderers import JSONRenderer import json from .models import Adam class AdamViewset(ModelViewSet): queryset = Adam.objects.all() class MainView(APIView) : def get(self, request) : data = json.dumps(list(Adam.objects.values())) return Response({'data' : data}, template_name='doroste.html') but important part is javascript const dataStr = '{{data}}'; const dataJson = JSON.parse(`${dataStr}`) console.log(dataStr) I expected to get a json but instead I got this error : SyntaxError: Expected property name or '}' in JSON I searched for it but I couldn’t find solution CAUSE MY LIST USES "" INSTEAD OF '' SO IT IS OKAY -
Don't buy namecheap shared hosting for DJANGO/PYTHON [closed]
I purchased namecheap sharedhosting plan for my django python app.It does support some functionality but there is a lot of django packages that need root access. Example : MySqlClient/DJOSER ETC. They provided me refund though but it took me a lot of time to finally come to this conclusion. So, I'm writing this thread as a soloution/to not waste your time on that shit. Just buy a VPS hosting and do whatever you want. Their website shows it's support python but it's just basic / not even basic as my experience. So if you're a beginer like me don't bother. It took more than 24 hours or maybe more to finally come to the conclusion. -
is this a valid option to verify the correct user logged in Django?
im learning Django from scratch and in a simple practice project i have a login for create new post. before i know about LoginRequiredMixin and UserPassesTestMixin, I wanted to try someting by myself in the template like this: {% if user.is_authenticated and user == post.author %} "Show forms and things like that and can edit or delete if is the author of the post" {% else %} "Ask the user for log in" {% endif %} but just out of curiosity, is this safe or is it a valid option? xd i try to implement a user permission and authentication in Django. just for curiosity, know whats happens -
Error 404 - HTML page not rendering for other apps than main application
So I've created several apps in my Django project and I have one main app called main_app. The other apps are called profile_app, settings_app, messages_app. The issue: The issues that I have is that whenever I try to run a certain view function from e.g profile_app in main_app using the app namespace and URL name (e.g profilepage_app:"profile-redirect"), I receive a 404 error stating "Page not found". I have done the following: Registret all apps. Linked the urls.py file in my settings URL. Tried to create a test view function inside the main_app and it works perfectly, but the same function does not work in the profile_app. Created another test app in order to see if I still have the same issue (I did). So the problem is that whatever link from all apps (except main_app) that I try to display in the browser generats the "Page not found"-error. My questions: Why does this happen? How can I resolve this issue? Has this something to do with my settings file? The error: My view: from django.conf import settings from django.shortcuts import render, redirect from django.views.generic import View from profile_app.forms import * from profile_app.models import * from messages_app.models import Message user = … -
Receive the value of an input field in the backend: Django
This is a follow-up to my previous question How to get the value of input field entered in navigation . I'm trying to get the value of an input field in the backend- Django. In views.py, I've included the following: Code: def vis(request): if request.method == 'POST': examples = request.POST.get('examples') # Process the value of examples print(examples) # not getting printed on the terminal return render(request, "vis.html") To get the value assigned for the placeholder, I used the below. function getExampleValue() { const fid = document.getElementById("examples").value; console.log(fid) const fpath = `/path/${fid}.json`; fetch(fpath) .then(response => response.json()) .then( data => { var x = data.x }) However, I cannot directly specify the filename in fetch since it fails to load from the file system in Django. So I want to receive the value and pass it to fetch, the value received (filename) will be used for loading a file from the path using fetch. So I specified form in vis.html. <form class="form" id="myForm" action="{% url 'visualization' %}" method="post"> But I am not able to receive the value in the backend. I want to receive the value set for the placeholder in examples: <input id="examples" class="input" name="examples" placeholder=" " onfocusout=getExampleValue() /> Complete HTML … -
Trouble deleting customer record in django using Bootstrap5 Modal/Jquery
I'm trying to delete a customer record when clicking on the modal popup delete button in bootstrap 5 but when I click on 'Yes, I want to delete' , nothing happens and I'm not sure where I'm going wrong. i've checked some of the other queries around this topic but still unable to get it to work. Below is what I have so far. Really appreciate any help on this! Customer record card with button <div class="p-3 text-primary-emphasis bg-primary-subtle border border-primary-subtle rounded-3"> <div class="card"> <div class="card-header"> <strong>{{ customer_record.first_name }} {{ customer_record.last_name }}</strong> </div> <div class="card-body"> <p class="card-text"> <strong>Email: </strong> {{ customer_record.email }} </p> <p class="card-text"> <strong>Phone: </strong> {{ customer_record.phone }} </p> <p class="card-text"> <strong>Address: </strong> {{ customer_record.address }} </p> <p class="card-text"> <strong>City: </strong> {{ customer_record.city }} </p> <p class="card-text"> <strong>Postcode: </strong> {{ customer_record.postcode }} </p> <p class="card-text"> <strong>Created At: </strong> {{ customer_record.created_at }} </p> <p class="card-text"> <strong>Company: </strong> {{ company_info.name }} </p> <p class="card-text"> <strong>ID: </strong> {{ customer_record.id }} </p> </div> </div> </div> <br/><br/> <a href="{% url 'update_customer' customer_record.id %}" class="btn btn-primary btn-sm">Update Customer Information</a> <a href="{% url 'delete_record' customer_record.id %}" class="btn btn-danger btn-sm deleteCustomer" data-bs-toggle="modal" data-bs-target="#deleteCustomer{{customer_record.id}}">Delete Customer</a> Delete customer modal <div class="modal fade" id="deleteCustomer{{ customer_record.id }}" tabindex="-1" aria-labelledby="deleteCustomerLabel" aria-hidden="true"> … -
problems with the current date when modifying a record
I need help with my following form: enter image description here When I'm going to insert the year in the Año field (I'm currently working with the datetimepicker library which works perfectly) the idea is that the current year appears by default in the Año field. I managed to solve this with the following JavaScript code: $('#anno').datetimepicker({ format: 'YYYY', date: moment().format("YYYY"), locale: 'es', }); The real problem is when I try to modify a record it exists, because the date: moment().format("YYYY") property, being active when I am going to modify a record, will have the current year and not the year of the record. When this property is deactivated, then in the case of inserting, no value appears in the field (but the datetimepicker has the current year marked) and in the case of modifying the same thing happens (the datetimepicker has the year of the record marked). I attach the code of my form.py: class OcupacionForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['tipoocupacion'].widget.attrs['autofocus'] = True class Meta: model = OcupacionPortador fields = '__all__' widgets = { 'anno': TextInput( attrs={ 'autocomplete': 'off', 'class': 'form-control datetimepicker-input', 'id': 'anno', 'data-target': '#anno', 'data-toggle': 'datetimepicker' } ), 'tipoocupacion': Select(attrs={'class': 'select2', 'style': 'width: 100%'}), 'mes': … -
How to use multiple forms in a single page in django
Hi i am pretty new to django. I am making a app for taking tiny notes. You can click on the texts (which is a django forms but it doesnt have the outlines) and edit them. I will make the submit form button appear when we change the content with javascript but for now lets leave it that way. With the "+" button you can add more Note instances. Now, the problem is when i want to edit the notes the only way i know is using forms, and when i do that i have to call another form for each Note instance...(i suppose). What i want on my website is, you can simply edit the content or title by clicking the text area, and submiting it(I can give https://trello.com as an example!). views.py def document_page(request, title): document = Document.objects.get(title=title) notes = document.notes.all() form = NoteForm(request.POST or None, request.FILES or None, instance=notes[0]) if form.is_valid(): form.save() return HttpResponseRedirect('/note/document/' + title) return render(request, 'note/document_page.html', {'document': document, 'notes': notes, 'form': form}) models.py class Note(models.Model): title = models.CharField(max_length=16, default='note-title') content = models.TextField(max_length=512, default='content') creation_date = models.DateTimeField(auto_now_add=True) document = models.ForeignKey(Document, on_delete=models.CASCADE, blank=True, null=True, related_name='notes') def __str__(self): return self.title forms.py class NoteForm(ModelForm): class Meta: model = …