Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get current user info inside model form in django admin
I have the below code structure. I want to get the request.user information inside StaffForm. How do I pass the user info to that class class UserProfileAdmin(admin.ModelAdmin): class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): pass class StaffForm(UserProfileForm): def __init__(self, *args, **kwargs): pass class Meta: model = models.UserProfile fields = () class SuperUserForm(UserProfileForm): def __init__(self, *args, **kwargs): pass class Meta: model = models.UserProfile fields = () search_fields = [ 'email', 'name' ] def get_form(self, request, obj=None, **kwargs): if request.user.is_superuser: return self.SuperUserForm else request.user.is_staff: return self.StaffForm -
how to limit foreign key choices in the form page?
below are my models, I want to display only those groups in post form in which the user is joined in. Example: if I joined in "mcu" group then only that group should be displayed, how should I do that?? GROUP MODEL class Group(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField(blank=True, default='') members = models.ManyToManyField(User, through='GroupMember') class GroupMember(models.Model): group = models.ForeignKey(Group, related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) class Meta: unique_together = ('group', 'user') POST MODEL User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=250,default='') message = RichTextField() group = models.ForeignKey(Group, related_name='posts', null=True, blank=True,on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message'] -
i can't connect between app URLs in Django
I have a small problem with URLs file in Django, I'm trying to connect between app URLs, review, and the main urls I have python 3.9.1 Django 3.2.0 I have been searching and try many things on StackOverflow but still, I don't find why the server doesn't work just when I put this line with a red arrow on the comment, please help!! -
How to make a python date time object based on model object values?
Here I have a Task model. Which has start and end datetime fields. User will have a option to set the notification setting while creating Task. (e.g. send notification before 30 minutes/1 hour). TaskNotification model has OneToOne relation with the Task model.Which is responsible for creating notification. The notification created at the time of task model creation. Now problem is while sending notification. I got stuck while sending notification to the users at the right time . I tried to run the task_notification function in background but stucked while getting the right time. Is it a good approach for my use case or is there any better approcah ? class Task(): title = models.CharField(max_length=255) desc = models.TextField(blank=True, null=True) users = models.ManyToManyField(User, blank=True) start_datetime = models.DateTimeField(default=timezone.now) end_datetime = models.DateTimeField(default=timezone.now() + timezone.timedelta(minutes=30)) class TaskNotification(): notification_options = [ ('minute', 'minute'), ('hour', 'hour'), ('day', 'day'), ] task = models.OneToOneField(Task, on_delete=models.CASCADE=) send_before = models.PositiveIntegerField(default=10) notification_option = models.CharField(max_length=10, default='minutes', choices=notification_options) is_viewable = models.BooleanField(default=False) function def task_notification(): tasks = Tasks.objects.filter(is_viewable=False) task_notifications = TaskNotification.objects.filter(task__in=tasks) for notif in task_notifications: event_start_time = notif.task.start_datetime notif_send_before = notif.send_before # will be an integer notif_time_option = notif.notif_time_option # minutes/hour/days if notif_send_req_time: # stucked here how to implement the logic notif.is_viewable=True notif.save() I will … -
Display choices from model (without using django forms)
We have an old django application developed, unfortunately it does not use django forms. It has many dropdowns implemented as follows (and form data is getting stored to the backend using ajax) <div class="form-group" data-enquiry-flag="2"> <label class="form-custom-label">Possession</label> <div class="btn-group" role="group"> <select name="possession_month" id="possession_month" class="form-control btn possession-btn btn-primary"> <option value="">----Select----</option> <option value="Jan" {% if enquiry.possession.possession_month == "Jan" %} selected {% else %} {% endif %}>Jan</option> <option value="Feb" {% if enquiry.possession.possession_month == "Feb" %} selected {% else %} {% endif %}>Feb</option> ... <option value="Dec" {% if enquiry.possession.possession_month == "Dec" %} selected {% else %} {% endif %}>Dec</option> </select> <select name="possession_year" id="possession_year" class="form-control btn possession-btn btn-primary"> <option value="">----Select----</option> <option value="2020" {% if enquiry.possession.possession_year == "2020" %} selected {% else %} {% endif %} >2020</option> <option value="2021" {% if enquiry.possession.possession_year == "2021" %} selected {% else %} {% endif %} >2021</option> ... <option value="2035" {% if enquiry.possession.possession_year == "2035" %} selected {% else %} {% endif %} >2035</option> </select> </div> </div> Earlier its model was something like this: class Possession(models.Model): possession_month = models.CharField(_('Possession Month'), max_length=5, blank=True) possession_year = models.IntegerField(_('Possession Year'), blank=True, null=True) # ... Other fields class Enquiry(models.Model): possession = models.ForeignKey(Possession, verbose_name=_("Possession"), null=True, blank=True, on_delete=models.CASCADE) Which I am modifying like this, from its accepted … -
Django: How to view all registered user Information in HTML template while login user have access to view anything, but user is not admin / superuser
i am new to Django: I am Creating a Website in which i want to show to All user Profiles in a Template to log-in user and when log-in user click to any user name visible in table field, information related to specific user will visible to log-in user .. In HTML Templates.. all registered user is visible in a table where i added the profile view link ***But in my scenario while i click the user name where i added view profile link the link is only showing log-in user information not the clicked user information *** My Project is Ecommerce My App are : Indenter, Login, Logout, Purchaser, Register, Supplier. - Ecommerce. URLs : from django.contrib import admin<br /> from django.urls import path, include urlpatterns = [ path('', include('Register.urls')), path('Login', include('Login.urls')), path('Logout', include('Logout.urls')), path('Purchaser', include('Purchaser.urls')), path('Intender', include('Intender.urls')), path('Supplier', include('Supplier.urls')), ] - Ecommerce.Register.URLs : urlpatterns = [ path('(?P<username>\w+)/profile_detail', views.profile_detail, name="profile_detail"), ] - Ecommerce.Register.views.py : This view i am calling in the Template to view the User information. def profile_detail(request, username): u = User.objects.get(username=username) user = request.user return render(request, 'profile_detail.html', {'user': user, 'user_url': u, }) tempaltes/indenter_home.html In this template in the table where all user is visible in usernaem field … -
What is the scope of global variables in the views.py?
If I declare a global variable myglobalvar in my views.py myglobalvar = "value" def home(request): print(myglobalvar) def thatOneLink(request): myglobalvar = "different value" When someone calls thatOneLink what is the scope of the change? Will myglobalvar = "different value" only for this request? Or only for the session? Or until the server restarts? In JSP by default there were settings on the scope. Django seems to have another package for that: https://pypi.org/project/django-scopes/ But in the very default case without any additional packages, how does Django handle scopes? Or do they have different names or definitions? -
overwite create method in djoser serializers
I am trying to overwrite create method after inheriting UserCreateSerializer from Djoser, but it does not get called when user-created serailizers.py djoser settings -
"Incorrect type. Expected pk value, received list." Error DRF React
Error when attempting post request Many to Many relation via React and Axios Question is how can i post list through axios along with image when I put list in request It shows an error "Incorrect type. Expected pk value, received list." View class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): print(request.data['categories']') file_serializer = serializers.PostSerializer(data=request.data) print(request.data.dict()) if file_serializer.is_valid(): print(request.data) file_serializer.save(owner=self.request.user) return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class PostSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') comments = serializers.PrimaryKeyRelatedField(many=True,queryset=Comment.objects.all()) categories = serializers.PrimaryKeyRelatedField(many=True,queryset=Category.objects.all()) class Meta: model = Post fields = ['id', 'title', 'body','owner','notify_users' ,'comments', 'categories','image'] Axios Request const handleSubmit = (e) => { e.preventDefault(); let form_data = new FormData(); form_data.append("image", postimage.image[0]); form_data.append("title", title); form_data.append("body", body); let catory = categories.map(val=>val.id) console.log(catory) let data = { title:title, body : body, categories:catory, image:postimage.image[0], notify_users : notifyuser } console.log(data.categories) //form_data.append("notify_users", notifyuser); form_data.append("categories",catory) console.log(catory) console.log('error here',form_data.get('categories')) authRequest.post('/posts/',form_data,{ headers: { 'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; Github -
Django multi-table inheritance different from Postgres table inheritance
So I'm looking at Django's multitable inheritance, and how it differs from Postgres' table inheritance. Say I have the following models: models.py class Mayor(models.Model): name = models.CharField(max_length=255) class City(models.Model) name = models.CharField(max_length=255) mayor = models.ForeignKey(Mayor, on_delete=models.CASCADE) class Capital(City): embassy = models.BooleanField(default=False) Now, if I build the db from this, I get a table that looks something like: cities: +----------+------------------------+---------------------------------------------------------+ | Column | Type | Modifiers | |----------+------------------------+---------------------------------------------------------| | id | integer | not null default nextval('main_city_id_seq'::regclass) | | name | character varying(255) | not null | | mayor_id | integer | not null | +----------+------------------------+---------------------------------------------------------+ capitals +-------------+---------+-------------+ | Column | Type | Modifiers | |-------------+---------+-------------| | city_ptr_id | integer | not null | | has_embassy | boolean | not null | +-------------+---------+-------------+ This isn't idea, as it means that to get capital cities' mayors, I have to do 2 joins, one from capitals to cities, and then from cities to mayors. In Postgres, we can have: cities: +------------+-------------+------------------------------------------------------+ | Column | Type | Modifiers | |------------+-------------+------------------------------------------------------| | id | integer | not null default nextval('cities_id_seq'::regclass) | | name | text | | | mayor_id | realinteger | | +------------+-------------+------------------------------------------------------+ where the below table is listed as a 'child' capitals: +------------+--------------+------------------------------------------------------+ … -
Djongo Model Error “Select a valid choice. That choice is not one of the available choices.”
I'm using djongo package for a connector backend under django to the mongodb and define my models on it. models.py: class EventModel(BaseModel) name = models.CharField(max_length=20) class CalendarModel(BaseModel): name = models.CharField(max_length=20) color = models.CharField(max_length=20) event = models.ForeignKey(to=EventModel, on_delete=models.SET_NULL, null=True) and admin.py: from django.contrib import admin from .models import CalendarModel, EventModel @admin.register(CalendarModel) class CalendarAdmin(admin.ModelAdmin): exclude = ['_id'] @admin.register(EventModel) class EventAdmin(admin.ModelAdmin): exclude = ['_id'] At first it is ok with like that on sqlite backend and it's work when djongo backend without foreignkey field but send me an error when its on djongo backend and has foreignkey field. It said: error image And I can't create a new object with relation on it. How I can fix it? -
Field 'id' expected a number but got ObjectId
I'm studying djongo and i'm trying to create a platform that automatically assign a random amount (between 1 and 10) bitcoins to all new registered users. My code is following: #views.py def register_page(request): if request.user.is_authenticated: return redirect('order_list') form = RegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,'Account successfully created, welcome '+ username) newUserProfile(username) #<------ this is the function to generate the profile with random BTC return redirect('login') context = {'form':form} return render(request, 'api/register.html', context) #models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) BTC = models.FloatField() balance = models.FloatField() pending_balance = models.FloatField() pending_BTC = models.FloatField() #utils.py def newUserProfile(username): user = User.objects.get(username=username) id = user.id BTC = round(random.uniform(1,10),2) profile = UserProfile.objects.create(id=id, user=user, BTC=BTC, balance = 0, pending_balance = 0, pending_BTC = 0) profile.save() When i push the register button on my webpage i get: Exception Type: TypeError Exception Value: Field 'id' expected a number but got ObjectId('606d892cb5d1f464cb7d2050'). but when i go in the database the new profile is regularly recorded: # userprofile tab {"_id":{"$oid":"606d892cb5d1f464cb7d2050"}, "id":49, "user_id":49, "BTC":3.26, "balance":0, "pending_balance":0, "pending_BTC":0} # auth_user tab {"_id":{"$oid":"606d892cb5d1f464cb7d204f"}, "id":49, "password":"pbkdf2_sha256$180000$nNwVYtrtPYj0$/wwjhAJk7zUVSj8dFg+tbTE1C1Hnme+zfUbmtH6V/PE=", "last_login":null, "is_superuser":false, "username":"Aokami", "first_name":"", "last_name":"", "email":"Aokami@gmail.com", "is_staff":false, "is_active":true, "date_joined":{"$date":"2021-04-07T10:27:56.590Z"}} How to resolve this, or atleast avoid the error page since i obtained anyway what i needed? -
Django orm get other foreign key objects from foreign object
I'm puzzled with this probably easy problem. My Models: class DiseaseLibrary(models.Model): name = models.CharField(max_length=255) subadults = models.BooleanField(default=False,blank=True) adults = models.BooleanField(default=False, blank=True) def __str__(self): return self.name class BoneChangeBoneProxy(models.Model): anomalies = models.ForeignKey('DiseaseLibrary', on_delete=models.CASCADE, related_name='anomalies') technic = models.ForeignKey('Technic', on_delete=models.CASCADE, related_name='technic_proxy') bone_change = models.ForeignKey('BoneChange', blank=True, null=True, on_delete=models.CASCADE, related_name='bone_change_proxy') bone = TreeManyToManyField('Bone', related_name='bone_proxy') From DiseaseLibrary I'd like to get all Objects that link to it via related_name "anomalies". Namely "technic_proxy", "bone_change_proxy", "bone_proxy" which are ForeignKeys to other models. I would expect to get access by the related name "anomalies" and _set >>> ds = DiseaseLibrary.objects.all().first() >>> ds.name 'Some nice name' >>> ds.anomalies <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x107fa4f10> >>> ds.anomalies_set.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'DiseaseLibrary' object has no attribute 'anomalies_set' >>> How can I access all ForeignKey values in model BoneChangeBoneProxy through model DiseaseLibrary? -
django-plotly-dash, 'Error at Line 0 expected string or bytes-like object' in base.html?
I am working through a tutorial on connecting django-plotly-dash to a Django project. Before I added the Plotly components, I was able to access my templates without issue. Once I set up the various Plotly requirements, I now get this error when I try to go to the main page: error capture I'm not sure where to start figuring out what this is telling me, there are some similar issues on Google (and Stack Overflow) bet I am not seeing finding anything that seems related. Also, I'm basically a noob, so be gentle. -
How to get the value of a specific field in a form in Django view function?
I am trying to achieve a load-up process in my system where the user will input the load amount and add it to a user's current load. How can I get the amount entered in my view function? Here's my function in my views.py def LoadWallet(request, pk): user = get_object_or_404(User, id=request.POST.get('user_id')) user_wallet = user.wallet if request.method == 'POST': form = LoadForm(request.POST) if form.is_valid(): user_wallet = user_wallet+form.instance.load_amount User.objects.filter(id=pk).update(wallet=user_wallet) return HttpResponseRedirect(reverse('user-details', args=[str(pk)])) and the form in my template file <form action="{% url 'load-wallet' user.pk %}" method="POST"> {% csrf_token %} <label for="load_amount">Load amount</label> <input type="text" class="form-control" id="load_amount" onkeyup="replaceNoneNumeric('load_amount')"> <button type="submit" name="user_id" value="{{ user.id }}" class="btn btn-md btn-success" style="float: right; margin: 10px 5px;">Load</button> </form> Right now I tried this but it's returning "name 'LoadForm' is not defined". Should I declare the LoadForm first? Is there a better way to implement this? Thank you! -
django - set verbose_name to object name
How can I set the score charFields verbose_name in GamePlayers to the person.name attribute that it relates to? The Person model has data that is already created & is not empty. class Game(models.Model): name = models.CharField(verbose_name="Game Title", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) person = models.ManyToManyField( Person, through='GamePlayers', related_name='person' ) class Person(models.Model): name = models.CharField(verbose_name="Name", max_length=250) def __str__(self): return self.title class GamePlayers(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) score = models.CharField(max_length=6, verbose_name=person.name) def __str__(self): return f"game: {self.game.title}" -
Django multi-table inheritance: parent data not saved
I'am using Django multi-table inheritance for the first time. I have 2 child models (Psychosocial 1 and Psychosocial 2) that inherit from one parent model (Invalidite) I am using Class Based Views (Create and Update) and Have developped forms and templates for Psychosocial 1 and Psychosocial 2. All is working well for Psychosocial 1 but not for Psychosocial 2. When I create a instance of Psychosocial 1, an instance of Ivalidite is created and fields from Invalidite are saved. I do the same with Psychosocial 2 but even if an instance Invalidite is created when an instance of Psychosocial is created but fields from Invalidite are not saved. When I debug in form_valid() method of Psychosocial2Create CBV, all fields from Invalidite return None. I do not understand what is the problem? class Invalidite(models.Model): """ A class to create a disability instance. """ hdq_ide = models.AutoField(primary_key=True) hdq_pat = models.CharField('Patient', max_length=4, null=True, blank=True) hdq_num = models.IntegerField('Test HDQ n°', null=True, blank=True) class Meta: db_table = 'crf_hdq' verbose_name_plural = 'Invalidites' ordering = ['hdq_ide'] def __str__(self): return f"{self.hdq_ide} - {self.hdq_pat}" class Psychosocial1(Invalidite): """ A class to create a psychosocial 1 instance. """ ide = models.AutoField(primary_key=True) ver = models.BooleanField("Fiche verrouillée", null=True, blank=True, default=False) ps1_dat = models.DateField('Date … -
Django for loop in template goes crazy
this loop: {% for address in item.customeraddresses_set.all %} {% if address.Is_Default_Billing_address == 1 %} <td> {{ address.Zip }} </td> <td> {{ address.Street }} </td> <td> {{ address.City }} </td> <td> {{ address.Country }} </td> {% else %} <td>---</td> <td>---</td> <td>---</td> <td>---</td> {% endif %} {% empty %} <td>---</td> <td>---</td> <td>---</td> <td>---</td> {% endfor %} goes crazy, I added another address and set it as Billing address, and now it prints empty and the address: xxx xxx WC-1000 +4528832155 xxx@xxx-computer.dk --- --- --- --- 25813 Am Hasselberg 8 Husum Germany 2. april 2021 whats going wrong here? -
adjust the number of rows by rowspan
I want to send the django lists template to html, but I can not sure the number of values in the list. When that have 2 values I can make a beautiful table, but when the values in the list change to less or more than 2, the size of table was not fit. Is any method to let the rowspan changeable and fit the number of value <table class="table table-bordered" id = "table2"> <thead class="thead-light"> <tr> <th rowspan="2" style="width:5%" scope="rowgroup">title</th> {% for name, accuracy in item %} <tr> <th scope="row">{{name}}</th> <th scope="row">{{accuracy}}</th> </tr> {% endfor %} </tr> </thead> </table> -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed in django
i keep on getting the above error on creating a new user model when creating users using postman here is my code. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from wallet.models import Transfer, Payment, Transaction, Wallet class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, name, phone, password,pin_code,confirm_pin,expected_delivery_month,email=None): user = self.model(name=name,phone=phone, email=email,pin_code=pin_code,confirm_pin=confirm_pin, expected_delivery_month=expected_delivery_month ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,name,phone,password,pin_code,expected_delivery_month,email=None, ): user = self.create_user(name,phone,password,email,pin_code,expected_delivery_month) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): name = models.CharField(max_length=120) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format +256706626855. Up to 10 digits allowed.") phone = models.CharField('Phone', validators=[ phone_regex], max_length=17, unique=True, null=False) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, null=True) is_admin = models.BooleanField(default=False) #now i need to add the pin coz its what am going to base on for the user creattion as the OTP pin_code = models.IntegerField(blank=False,unique=True)#vital here confirm_pin = models.IntegerField(blank=False)#this field here is to help in the confirmation of the pin expected_delivery_month = models.CharField(blank=False,default='january',max_length=20) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['name','pin_code'] def __str__(self): return self.name class Meta: unique_together = ("phone","pin_code")#since i need each phone number to have a unique pin code @property … -
Change Plotly Graph for mobile
I have created a graoh that looks good in the web browser, but looks terrible in mobile. Is there any way with plotly or django to help it look better in mobile? I came across an article showing how to make a mobile view within plotly but it appears they took that option out since the article came out, as I could not find the option anywhere. I'm currently using an iframe to embed it into a blog post. Here is what it looks like on web page And here is what it looks like on mobile: And here is the iframe html im using to embed it into my blog post. <p><iframe height="525" id="igraph" scrolling="no" seamless="seamless" src="https://plotly.com/~JakeSpeers/13.embed?showlink=false" style="border:none;" width="100%"></iframe></p> There has to be a better way to make it look better on mobile. Thanks in advance -
How would I manage to upload al the rows with the django view?
I posted this question here and got a suggestion. I managed to go through it but wasn't able to implement it for the import part[I managed export]. I'm therefore back with the question. Could I have a way to loop through all the rows in the uploaded file and have all the data uploaded. Currently it uploads only one item, one row. def UploadTeachersView(request): message='' if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as tmp: tmp.write(excel_file.read()) book = xlrd.open_workbook(path) sheet = book.sheet_by_index(0) obj=TeacherData( school_id = sheet.cell_value(rowx=1, colx=1), code = sheet.cell_value(rowx=1, colx=2), first_name = sheet.cell_value(rowx=1, colx=3), last_name = sheet.cell_value(rowx=1, colx=4), email = sheet.cell_value(rowx=1, colx=5), phone = sheet.cell_value(rowx=1, colx=6), ) obj.save() finally: os.remove(path) else: message='Invalid Entries' else: form = NewTeachersForm() return render(request,'upload_teacher.html', {'form':form,'message':message}) -
django ajax display nothing in for loop
i have to use for loop inside my ajax request , i used django inlineformset , when admin selects an item it has to return back the price , but it doesnt work in for loop class Item(models.Model): items = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=3)#i have to return this price def __str__(self): return self.items class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='ItemsInvoice') class ItemsInvoice(models.Model): invoice_no = models.ForeignKey(Invoice,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=3)#when selecting an item , the price return back and write in the price field my views.py @login_required def check_price(request): item = request.GET.get('invoice-0-item',None) price = Item.objects.get(id=item).price print(price) data = { 'price':price, } return JsonResponse(data) and i dont know how to iterate through the number of forms to achieve this @login_required def check_price(request): for i in range(length of forms): item = request.GET.get('invoice-'+i+'-item',None) #etc <form method="POST">{% csrf_token %} {{items.management_form}} <div class="p-1 pr-2 pb-1 text-xs border border-black rounded-lg flex flex-wrap" style="direction: rtl;"> <div class="flex w-8/12 lg:w-9/12"> <div class=""> customer name : </div> <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted"> {{form.customer | add_class:'bg-transparent w-full text-center focus:outline-none customer' }} {% if form.customer.errors %} <div class="redCOLOR pb-1 my-0 text-center rounded-lg w-full md:w-6/12 mx-auto">{{form.customer.errors}}</div> {% endif %} </div> </div> </div> <!-- … -
Django merge duplicate rows
I have a table like this. id|name |user_id |amount| --|---------------------|------------|------| 1|Name1 |1 | 4| 2|Name1 |1 | 7| 3|Name2 |1 | 5| I want to merge rows that have the same name and user_id and that should look like this: id|name |user_id |amount| --|---------------------|------------|------| 1|Name1 |1 | 11| 2|Name2 |1 | 5| Django ver = 3.1 -
Uncaught TypeError: Cannot read property 'style' of null when using data-SOMETHING attribute to pass parameter to JavaScript function
I'm new to coding and I'm trying to hide a paragraph using JavaScript. This is my HTML {% for post in posts %} <div class="container p-3 my-3"> <div class="card"> <div class="card-block px-1"> <h4 class="card-title"> <a href="{% url 'profile' post.user.id %}">{{ post.user }}</a> </h4> <p class="card-text" id="{{ post.id }}">{{ post.content }}</p> <textarea style="display: none;" id="edit-view">{{ post.content }}</textarea> <p class="card-text" id="time">Posted on: {{ post.timestamp }}</p> {% if post.user == request.user %} <button type="button" class="btn btn-primary" id="edit-btn" data-text="{{ post.id }}">Edit</button> {% endif %} <button type="button" class="btn btn-primary" id="save-btn" style="display:none;">Save</button> <p class="card-footer">{{ post.like }} Likes</p> </div> </div> </div> {% endfor %} Looking at the source code I could verify that the post.id context is correctly displayed in both the data-text attribute and the id of the paragraph I want to hide. This instead is my JavaScript function (which I have in a separate js file): function edit(text) { // hide content document.querySelector(`#${text}`).style.display = 'none'; } I'm calling the function after loading the DOM and applying and event listener to all buttons with id of edit-btn: document.addEventListener('DOMContentLoaded', function() { // Adding event listener document.querySelectorAll('#edit-btn').forEach(function(button) { button.onclick = function() { console.log('Button clicked!') edit(); } }); }); Nevertheless I get the above error, as if the parameter …