Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i create and use variables in django
New to Django and its templates. I'm trying to set a variable given a specific situation, and that part I think ill be able to do, the code below isn't the exact conditions its just there as a demo. The part im stuck on is how do i create a variable name, and then use that name variable elsewhere. Such as within a div or within a method or anywhere else within the html file, and withing different <Script> tags to run methods and for really any purpose. demo scenario : {% for row in table.rows %} {% if row == 2 %} {% var name = row.name %} {% endif %} {% endfor %} {% if name %} <div>{{name}}</div> {% endif %} my actual code Im trying to implement: <script type="text/javascript"> function map_init_basic(map, options) { var markerClusters = L.markerClusterGroup({ chunkedLoading: true }); {% for row in table.rows %} var x = "{{ row.cells.x }}" var y = {{ row.cells.y }} var m = L.marker([y, x]) m.bindPopup("{{row.cells.first_name}} {{row.cells.last_name}} <br>{{row.cells.chgd_add}}"); m.on("click" , ()=>{ //console.log(`${first_name} ${last_name}`) {% var first_name = {{row.cells.first_name}} %} }) //changed row.cells.chgd_add to row.cells.Chgd_add to make sure its matching the table markerClusters.addLayer(m); {% endfor %} markerClusters.addTo(map); } {% if … -
Django correct list using article_id
views.py def article(request, article_id): return render(request, 'article.html', { 'article': Article.objects.get(id=article_id) }) urls.py from . import views urlpatterns = [ path('articles/', views.articles, name='articles'), path('articles/<int:article_id>/', views.article, name='article'), ] article.html <div class="pagination"> <a href="#">&laquo;</a> <a class="active" href="/articles/{{ article.id }}/">1</a> <a href="/articles/{{ article.id }}/">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">5</a> <a href="#">6</a> <a href="#">&raquo;</a> </div> Someone can tell me how add to pagination list correct article by correct id and last and end article ID in HTML? Thanks a lot -
Can I get the property of a specific object in a Django template?
I am using django-filters in my project. Let's say I get this address after a search: ?title=my title&ms=8 As you can see, I've searched for 'my title' and for a manuscript which the user sees as 'my manuscript', but whose get parameter (and ID) is 8. Now, I'd like to add to my template a courtesy 'you've searched for' field. How can I show the title of that manuscript, rather than its ID? I already have the ms objects in my view: mstunes = MsTune.objects.all() ms = Manuscript.objects.all() <- manuscripts f = MsTuneFilter(request.GET, queryset=MsTune.objects.all()) return render(request, 'manuscript/mstune_list.html', {'mstunes': mstunes, 'f': f, 'request':request, 'ms': ms}) and I can indeed access them with {{ms.all}}. Is it possible to do something, in pseudo code, like: show the ms.title of the ms object with id = request.GET.ms ? -
Auto fill up Django model
I'm building an application that display tests included in a project. User can set the test result of each tests. My model contain 3 basic classes: Requirement - in this class i want to hold every tests. Something like template table. class Requirement(models.Model): requirement_name = models.CharField(max_length=256, default=None) nist = models.CharField(max_length=10, blank=True, null=True, default=None) cwe = models.CharField(max_length=10, blank=True, null=True, default=None) lvl1 = models.BooleanField(default=True) lvl2 = models.BooleanField(default=True) lvl3 = models.BooleanField(default=True) stand2 = models.IntegerField(default=2) stand3 = models.IntegerField(default=2) stand4 = models.IntegerField(default=2) stand5 = models.IntegerField(default=2) stand6 = models.IntegerField(default=2) stand7 = models.IntegerField(default=4) Project - contain all projects created by users class Project(models.Model): project_name = models.CharField(max_length=256, default=None) date_made = models.DateTimeField( auto_now_add=True) owner = models.ForeignKey(User, default=None, on_delete=models.CASCADE) lvl1_project = models.BooleanField(default=True) lvl2_project = models.BooleanField(default=True) lvl3_project = models.BooleanField(default=True) stand2_project = models.BooleanField(default=True) stand3_project = models.BooleanField(default=True) stand4_project = models.IntegerField(default=1) stand5_project = models.IntegerField(default=0) stand6_project = models.IntegerField(default=2) stand7_project = models.IntegerField(default=4) ReqsProject - in this table i want to store all of requirements that are stored in class Requirements class ReqsProject(models.Model): project_id = models.ForeignKey(Project, default=None, on_delete=models.CASCADE) requirement_id = models.ForeignKey(Requirement, default=None, on_delete=models.CASCADE) status = models.BooleanField(default=True) result = models.BooleanField(default=True) How can I automaticly fill up table ReqsProject when user create own Project. This may be something like this: ID Project ID Requirement ID Status Result 1 1 … -
Why isn't the BooleanField changing value in Django models?
I'm working in an Auction website which let the user list an auction and close it afterwards. The auction models has a boolean field called is_closed that stores if the auction is closed or not. When the user clicks a "Close Auction" button, he will be lead to this view that only changes the value of this field (that is false by default) and then saves the changes. def close_auction(request, auction_id): if request.method=="POST": target_auction = Auction.objects.get(id=auction_id) target_auction.is_closed=True target_auction.save() return HttpResponseRedirect(reverse('auction', kwargs={'auction_id':target_auction.id})) However, the field doesn't change, even though I am redirected to a html page that is loaded when the auction is closed successfully. When I go to the admin/ page the is_closed field indeed is unchanged (still marked as false). If what I did here is illegal, why there is no error message? Here is the Auction model: class Auction(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=100, default="") image_url = models.CharField(max_length=100, default="https://elitescreens.com/images/product_album/no_image.png") category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", related_name="auction_category") bid = models.OneToOneField(Bid, on_delete=models.CASCADE, null=True) creation_date = models.CharField(max_length=30, default="-----") owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default="") is_closed = models.BooleanField(default=False) Any ideas? -
Django admin actions bar missing? Template expecting "action_form" context variable but mine is showing "action_confirm_form"
As the title says, I'm having an issue that I cant seem to find any reference of anywhere else online. I was working on creating a custom Django admin action that provides and intermediate page for additional request data before updating the selected models. I followed these posts to accomplish this: Displaying an Admin Action Popup and Displaying an Admin Action Confirmation Page. I got everything working and then I went back to add some comments and after the server restarted when detecting changes, the admin action bar completely disappeared (see screenshot below). Another thing to note, my Django project has two separate apps, each with their own admin site and the actions drop-down disappeared from both sites for all model's change list view. Admin Actions Missing When inspecting the context of the admin site using the debug_toolbar I see this: {'action_confirm_form': <ActionForm bound=False, valid=Unknown, fields=(action;select_across)>, 'actions_on_bottom': False, 'actions_on_top': True, 'actions_selection_counter': True, 'available_apps': ... And when looking at the admin site context of a different clone of the repo with the admin actions working as expected I see this: {'action_form': <ActionForm bound=False, valid=Unknown, fields=(action;select_across)>, 'actions_on_bottom': False, 'actions_on_top': True, 'actions_selection_counter': True, 'available_apps': ... It appears that the context variable action_form was … -
like button for a blog post in Django
Looked over a few posts on Stack, but don't appear to see an answer. I am trying to get the blog post to send the like button as a notification. I currently have the comments working fine, i can comment on a blog and that will send a notification to the user who wrote the blog. I just cant appear to get the like button to notify. The blog post can be accessed by the title, to show you the post-detail screen of the individual post. On there we have a like button which i would like to be pressed and notify correctly. Thank you, i am a little experienced but still trying to gain a better understanding. Models.py from typing import cast from django.contrib.auth.decorators import user_passes_test from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import post_save, post_delete from notifications.models import Notification class Category (models.Model): named = models.CharField(max_length=100) def __str__(self): return self.named def get_absolute_url(self): return reverse('home') # Create your models here. cat_new_choice = Category.objects.all().values_list('named', 'named') # first BLOG table - TEST this is how you create it! class Post(models.Model): title = models.CharField(max_length=100) … -
Wagtail - How to save a record which uses InlinePanel containing M2M
I have a model which uses an InlinePanel to reference another model (ClubTimetable) which itself contains an M2M relationship to DayOfTheWeek. It seems as though I am unable to save the record because ClubTimetable is not yet saved and cannot create the M2M relationship to DayOfTheWeek, causing the following error: "<ClubTimetables: Club Timetable (str) 18:00:00>" needs to have a value for field "id" before this many-to-many relationship can be used. What can I do to solve this issue? My models look like this # ClubManager @register_snippet class ClubManager(ClusterableModel): name = models.CharField('Club name', max_length=255, help_text='The name of the club.') panels = [ FieldPanel('name'), InlinePanel('club_timetable', heading='Timetable Information') ] # ClubTimetables class ClubTimetables(Orderable, AddressBase): attached_to = ParentalKey( 'club.ClubManager', related_name='club_timetable') weekday = models.ManyToManyField(DaysOfTheWeek) start_time = models.TimeField() end_time = models.TimeField() panels = [ ... ] + AddressBase.panels # DaysOfTheWeek class DaysOfTheWeek(models.Model): weekday = models.CharField(max_length=9) def __str__(self): return self.weekday Visually, it looks like this (Initial) (Adding timetable) -
Missconfigures Django settings, ModuleNotFoundError: No module named 'DeveloperRoad'
I'm making a django blog app and I created a Custom User, modifying the AUTH_USER_MODEL constant in the settings.py file. But the database drop an IntegrityError, so I though it was that the configuration file wasn't being imported, and I did the following command,with virtualenv activated: export DJANGO_SETTINGS_MODULE=DeveloperRoad.settings My project app is named DeveloperRoad and the settings file is settings,so I'm not sure what I'm doing wrong. My project structure is the following: DeveloperRoad ├── blog │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── templates │ │ └── blog │ │ ├── add_category.html │ │ ├── add_post.html │ │ ├── author.html │ │ ├── categories.html │ │ ├── categories_list.html │ │ ├── delete_post.html │ │ ├── details.html │ │ ├── edit_post.html │ │ └── index.html │ ├── templatetags │ │ ├── extra_filters.py │ │ ├── __init__.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── DeveloperRode │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── members │ ├── admin.py │ ├── apps.py │ ├── backends.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ … -
preventDefault doesn't always work and the event is executed
I have encountered such a problem that the cancellation event of the form submission does not always work, namely in 30% of cases the event is not cancelled. I send a request by GET method to Django server and get json from it. In 70% of the cases I get the json and my function is already called which handles that json. But in the other 30% I get the json and it is immediately displayed on the screen and I get this text in the console: "content.js:200 JSON Formatter: Type "json" to inspect." Can you please tell me why this happens and how to fix it? let form=document.querySelector('form') form.onsubmit=(e)=>{ e.preventDefault(); setTimeout(()=>{ fetch(form.action, { method: "GET", }) .then(response => response.json()) .then(function(json) { if (json.status){ caseFormation(json) } }) .catch(function(error) { console.log(error) }); },1000) } -
django reathenticate middleware
as a relative noob to django I have been creating a users app. I would like a logged in superuser to have to reauthenticate if they access the admin area having used the rest of the app. I am trying this custom middleware that I have written. Is there a django integrated solution to this problem already, and are there any issues that you can see with my code? from django.shortcuts import redirect from django.contrib import messages from django.contrib.auth import logout import re class ReauthenticateMiddleware: def __init__(self, get_response): self.get_response = get_response self.pages = [] # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.user.is_superuser: match = re.match(r'/admin/', request.path) if len(self.pages) and self.pages[-1] is not None and match is not None: referred = re.match(r'/admin/', self.pages[-1]) if referred is None and match is not None: messages.add_message(request, messages.INFO, 'You must reauthenticate') logout(request) self.pages = [] return redirect('/admin/login/') if request.path[-1] == '/': self.pages.append(request.path) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response I have the custom middleware on the python path and have added it to settings … -
'relation "django_site" does not exist' only when running Django tests in GitHub Actions
I have a Django 3.1 project with an Admin class like this really simple example: from django.contrib import admin from .models import Book class BookAdmin(admin.ModelAdmin): def book_title(self, obj): return obj.title admin.site.register(Book, BookAdmin) And I test that class: from django.contrib.admin.sites import AdminSite from django.test import TestCase from myapp.admin import BookAdmin from myapp.models import Book class BookAdminTestCase(TestCase): def test_book_title(self): book = Book(title="Hello") book_admin = BookAdmin(Book, AdminSite()) self.assertEqual(book_admin.book_title(book), "Hello") This works fine when I run tests (./manage.py test) on my local development site. But when I run tests in a GitHub Action step... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...while other tests all work fine, tests using the AdminSite() call fail with: psycopg2.errors.UndefinedTable: relation "django_site" does not exist 196 LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... These tests use the same Django settings as when run locally. If I run migrations in the GitHub Actions step before I run the tests... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py migrate --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...this error doesn't occur, so I can get round this, but … -
charfield Connect to another model charfield (django)
I have a question answer quiz. I have 2 models of question and answer. The answer model I have related to the reading model. But in html I could not figure out how to build it properly. I want something like that. Show the question and below the question be the answer model charfield "answer" then check if the answer is equal to the question answer "answer_question". How do I guess I have a problem in vieweb. If you can help me, thanks in advance. for example (image) this is code -> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def _unicode__(self): return unicode(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if … -
Search by foreign key in admin
models.py class Supplier(models.Model): name = models.CharField(blank=True, max_length=50,) city = models.CharField(blank=True, max_length=50) email = models.CharField(blank=True, max_length=50) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) description = models.CharField(blank=True, max_length=100) DDT = models.FileField(upload_to="DDT/%Y/%m/%d") fattura = models.FileField(upload_to="DDT/%Y/%m/%d") admin.py @admin.register(Supplier) class SupplierModelAdmin(admin.ModelAdmin): model = Supplier @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): model = Product list_display = ['supplier'] search_fields = [ 'supplier'] when i search for a supplier , django return an error : Related Field got invalid lookup: icontains -
Django twitter clone Following and Follower problem
Hy, I am trying to make a twitter clone using django however I am having issues implementing following and follower system. Suppose I have 2 users A and B. If A follows B, B should be in user A following List furthermore user A should be in user B followers List. However my code seems to implement the reverse and I am confused. e.g I if I follow elon musk he would be in my following list but I would be in his followers list Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True, max_length=30) profile_picture = models.ImageField(upload_to="images/profile/",default='default.png') following = models.ManyToManyField(User, symmetrical=False, blank=True,related_name='all_following') followers = models.ManyToManyField(User, symmetrical=False, blank=True, related_name='all_followers') def __str__(self): return str(self.bio) def get_absolute_url(self): return reverse('home') def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) print('Profile Created') post_save.connect(create_profile,sender=User) def update_user_profile(sender, instance, created, **kwargs): if created == False: instance.profile.save() print('Profile Updated') post_save.connect(update_user_profile, sender=User) def profile_picURL(self): try: url = self.profile_pic.url except: url = " " return url HTML CODE SNIPPET <div class="column3"> {% for user in users%} {% if not request.user == user%} <div class="follow-users"> <h5>{{user.username}}</h5> <div class="follow-user"> <div> <span>{{user.all_followers.all.count}} followers</span> <span>{{user.all_following.all.count}} following</span> <p><a href="{% url 'view_user_profile' user.id %} ">View {{user.username}} profile</a></p> </div> <form action="{% url 'follow_unfollow_user' user.id %}" method="POST" … -
divisibleby requires 2 arguments error in django
i am probably making a dumb mistake but why does the divisibleby template tag give me an error that it needs two arguments for me when i have seen many others use one argument and get it to work. here is the full error: divisibleby requires 2 arguments, 1 provided templates: {% for item in posts %} {% if item in ads and forloop.counter|divisibleby 5 %} //print ads {% endif %} //print products {% endfor %} -
Django Signal For Updating User
View def transfer(request): if request.method == 'POST': t_form = TransferForm(request.POST, instance=request.user.profile) if t_form.is_valid(): t_form.save() messages.success(request, f'Amount sent!') else: t_form = TransferForm(instance=request.user.profile) context = locals() return render(request, 'transfer.html', context) Models.py from django.contrib.auth.models import User from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=400, default='Hi! I am new :D') image = models.ImageField( default='default.png', upload_to='profile_pics') balance = models.IntegerField(User, default=10) def __str__(self): return f'{self.user.username} Profile'``` class Transfer(models.Model): to_user = models.ForeignKey(User, related_name='receiver', on_delete=models.CASCADE) from_user = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) amount = models.IntegerField(default=0) def __str_(self): return f'{self.to_user.username} Transfer' def transferred(sender, instance, **kwargs): Transfer.to_user = User.objects.first() Transfer.amount = 35 Transfer.amount += Transfer.to_user.profile.balance Transfer.to_user.save() post_save.connect(transferred, sender=Transfer) Form: class TransferForm(forms.ModelForm): class Meta: model = Transfer fields = ['to_user', 'from_user', 'amount'] What's wrong here? What to do so that when I enter the transfer class fields using TransferForm, the to_user's (who is the user whom im sending the amount) balance field updates with the amount we sent? -
Prevent Dropdown menu from closing if I click a menu item
I have a drop down menu in sidebar and it has links as menu items. When I click a menu item(link) then link works fine but drop down menu gets closed. But I want that dropdown menu stay opened even after clicking a menu item. HTML Code: <button class="dropdown-btn button">Products <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> <a href="{% url 'shop:admin_products_list' %}">View Products</a> <a href="{% url 'shop:admin_product_create' %}">Add New Product</a> </div> I tried these two following ways: $('div.dropdown-container a').on('click', function(e) { e.preventDefault(); }); $('div.dropdown-container a').on('click', function(e) { e.stopPropagation(); }); But these two ways did not work. Please help me to resolve it. -
How to extend user model for Social_auth uisng pipeline?
I have successfully implemented the social_auth package for django and it is successfully populating the fields in postgres. I am trying to extend the user models so that i can add some additional data while creating the account by user. This is what i could come up with, till now. I have almost tried all the available resources online available but are not very helpful in this case. settings.py #pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.create_user', 'django_social_app.pipeline.requestprofiledata', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) models.py from django.db import models from django.contrib.auth.models import User, auth # Create your models here. class profiledata(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) #first_name =models.CharField(max_length=120) #last_name =models.CharField(max_length=120) #email =models.CharField(max_length=120) registeredemail = models.CharField(max_length=120) mobile = models.CharField(max_length=10) instname = models.CharField(max_length=10) idproof = models.FileField(upload_to='documents/') profiledatacomplete = models.BooleanField() views.py def getprofiledata(request): return render(request,'createCertificates/profile.html') pipeline.py from django.shortcuts import redirect from .models import profiledata #from socia.pipeline.partial import partial from django_social_app import views from social_core.pipeline.partial import partial @partial def requestprofiledata(strategy, details, user=None, is_new=False, *args, **kwargs): print(details) print(type(user)) #print(user.first_name,"..............") #print(user.registeredemail) test = 0 #if user and user.email and test != 0: if test == 1: return #elif is_new and not details.get('email'): else: registeredemail = strategy.request_data().get("registeredemail") #user['registeredemail'] = strategy.request_data().get("registeredemail") mobile = strategy.request_data().get("mobile") instname = strategy.request_data().get("instname") idproof = strategy.request_data().get("idproof") ''' … -
Django filter a prefetched queryset returning an empty list
In my app I have some Users and Groups, that are related by a many to many relation through GroupMember. class User(models.Model): ... class Group(models.Model): ... users = models.ManyToManyField(User, through='groups.GroupMember', related_name='groups') class GroupMember(models.Model): ... user = models.ForeignKey(User, related_name='group_members', on_delete=models.CASCADE) group = models.ForeignKey(Group, related_name='members', on_delete=models.CASCADE) Now I am trying to build an endpoint that retrieves a list of user instances that are in any one of the groups that your user is in. So if user A and B are in group1, user A and C are in group2, and C and D are in group3, retrieving the users as A would return B and C (since those are in groups with A). That filter part can be done in multiple ways, but the part where I am stuck is how to show which groups were the cause of the relation. I tried to use prefetch_related with a custom filter, to fetch only the groups that have user A in them, like this: User.objects.exclude(id=user.id).annotate( # Annotate the amount of groups related between the users related_group_count=Count('groups', filter=Q(groups__users=user)) ).filter( # Only users that have at least 1 relation with this user related_group_count__gt=0 ).prefetch_related( # Prefetch the specific groups to show Prefetch('groups', User.groups.all(), to_attr='related_groups'), … -
onchange function doesn't work with decimal field
I'm not very familiar with JS, i m working on django project, when a 'price_buy' field is set to DecimalField on models, this function doesn't work, but if FloatField, it works fine. Also if another field is None, i get this error msg (Uncaught ReferenceError: None is not defined at HTMLSelectElement.select.onchange ((index):552)). How i can resolve this problem ? <script type="text/javascript"> document.querySelectorAll("select").forEach((select) => { select.onchange = function(){ var price_buy = 0; const value = this.value; {% autoescape off %} const products = {{ products }} {% endautoescape %} for (var index=0; index < products.length; index++ ) { if (products[index].id == value) { price_buy = products[index].price_buy; } } const name = this.name.replace("product", "price_buy") console.log(price_buy, name); document.querySelector(`input[name=${name}]`).value = price_buy; } }); </script> -
Reverse for 'lajme-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['lajme/(?P<slug>[^/]+)/$']
I need help on this i have no clue why isnt working. I tried different way and still there is more option left that im aware of -----Here is my HTML code: {% for lajme in lajmet %} <article class="media content-section"> <div class="container"> <div class="container"> <img src="media/{{lajme.fotografit}}"> <h4 style="text-align: center; font-family: Comic Sans; font-weight: 700;"><a class="article-title simson" href="{% url 'lajme-detail' lajme.slug %}">{{ lajme.titulli }}</a></h4> <!--<p class="article-content">{{ lajme.detajet|safe|truncatewords:"700"|linebreaks }}</p>--> </div> </div> </article> {% endfor %} --- Here is my model: class Lajmet(models.Model): kategorit = models.ForeignKey(Kategori, on_delete=models.CASCADE) titulli = models.CharField(default='', max_length=350) fotografit = models.ImageField(upload_to='imgs/') detajet = RichTextUploadingField() data_e_postimit = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titulli def get_absolute_url(self): kwargs = {'slug': self.slug} return reverse('lajme-detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.titulli self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) ----Here is my View: class LajmetListView(ListView): model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmet' ordering = ['-data_e_postimit'] paginate_by = 4 # ---------------------------------------------------- class LajmetDetailView(DetailView): model = Lajmet query_pk_and_slug = True -- Here is my path url: path('', LajmetListView.as_view(), name='lajme-home'), path('lajme/<str:slug>/', LajmetDetailView.as_view(), name='lajme-detail'), -
Making dynamic form (adding additional form rows) using Django formset AND select2
I have a form and formset: I want to be able to dynamically add more sets of these forms, including new select2s, from within the formset itself, like adding an 'add row button' from within Django. class FruitForm(forms.ModelForm): region_category = forms.ChoiceField(choices=[('','----')] + [(region, region) for region in Lists.FruitTypes.region_categories], required=False) def __init__(self, *args, **kwargs): super(FruitForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['region_category'].disabled = True self.fields['fruit_type'].disabled = True self.fields['fruit_picked'].disabled = True self.fields['date_picked'].disabled = True if instance.fruit_type: self.fields['region_category'].initial = instance.fruit_type.region_category self.fields['fruit_eaten'].required = False self.fields['date_eaten'].required = False class Meta: model = Fruit fields = ['fruit_id','fruit_type', 'fruit_picked', 'date_picked', 'fruit_eaten', 'date_eaten' ] widgets = { 'fruit_type': autocomplete.ModelSelect2(url='fruit-type-autocomplete', forward=['region_category']), 'date_picked': forms.DateInput(format='%Y-%m-%d', attrs={'type': 'text'}), 'date_eaten': forms.DateInput(format='%Y-%m-%d', attrs={'type': 'text'}) } FruitFormset = modelformset_factory(Fruit, form=FruitForm, extra=1, can_delete=True) Is this possible, and how would I go about it? -
How to save a foreign key field in the Django Rest Framework
I have a issuetracker project where a manager can assign a user to a project. The manager selects a project and a user from dropdowns, clicks submit, and an api call is called in the frontend to send that post data to my django backend APIView assignuser. Assignuser then takes both those values and filters for the correct project and the user, and saves that user to the project user. After checking the projects, I am unable to save a new User to a project as User comes up as null. Is there a specified way in saving foreign keys in the DRF? assignuser class assignuser(APIView): serializer_class = ProjectSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user_name = serializer.get('user') project_name = serializer.get('project_name') user = Users.objects.get(user=user_name) project = Project.objects.get(name=project_name) project.user = user project.save() return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED) else: return HttpResponse("Incorrect Credentials") Project Serializer class ProjectSerializer(serializers.ModelSerializer): user = SignUpSerializer() class Meta: model = Project fields = ('name', 'description', 'user') -
How Import parent package in django website
I have a tree like that : cyberactu ├── models.py ├── __init__.py ├── Scraping │ ├── __init__.py │ ├── scrap.py I'm in scrap.py and i want import a models from models.py. I know I must add the cyberactu folder to my PYTHON PATH. I do like that : import sys sys.path.append(path) After that, if I try to import my models : from models import MyClass That raise a error : django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. After view research this error mean i must link my Django settings to my file. So I do that : export DJANGO_SETTINGS_MODULE=website.settings website is the name of my django project. And that raise a other error: ModuleNotFoundError: No module named 'website' I have a empty init.py file in my cyberactu folder. Thank you for helping me