Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
I'm trying to deploy it on Railway. This error is coming. raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) Image of the error coming -
Django images not showing up in template
I've spent the whole day trying to find a solution for showing the images in the template but I couldn't find any solution to my case. This is my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'DataCallGuide/static') ] My model class TroubleshootingSteps(models.Model): box_header = models.CharField(blank=True, null=True, max_length=250) box_content = models.CharField(blank=True, null=True, max_length=250) box_botton = models.CharField(blank=True, null=True, max_length=250) header = models.TextField(blank=True, null=True) sub_header = models.TextField(blank=True, null=True) text1 = models.TextField(blank=True, null=True) image1 = models.ImageField(blank=True, null=True, upload_to="images/") and the template {% extends 'base.html' %} {% load static %} {% block content %} <div class="container overflow-hidden"> <div class="text-center"> <h4 class="mt-5 mb-5">{{data.header}}</h4> </div> <h3 dir="rtl" class="rtlss">{{data.sub_header}}</h3> <img src="{{ data.image1.url }}"> </div> {% endblock%} Also when I click on the image link in admin pages it doesn't show the image and display page not found error with the below link http://127.0.0.1:8000/media/images/IMG-20220901-WA0009.jpg What is wrong please? -
Django IO bound performance drop with gunicorn + gevent
I have been working on an IO bound (only simple queries to database for getting info or updating it) application written in Django. As application is mostly db and redis queries, I decided to use gunicorn with async gevent worker class, but the weird part is that eventhough I'm running gunicorn with gevent (also monkey patched db for that purpose), I'm not seeing any performance gain by it, in fact, both requests/s and response time has dropped. Steps taken To do so, I have done the following: Installed greenlet, gevent & psycogreen as instructed in official docs. Patched postgres with psycogreen.gevent.patch_psycopg (tried wsgi.py, settings.py and post_fork in gunicorn) but to no avail. Tried running gevent's monkey.patch_all manually, also no use. This is my gunicorn.config.py: import gunicorn gunicorn.SERVER_SOFTWARE = "" gunicorn.SERVER = "" bind = "0.0.0.0:8000" worker_class = 'gevent' worker_connections = 1000 # Tested with different values keepalive = 2 # Tested with different values workers = 10 # Tested with different values loglevel = 'info' access_log_format = 'sport %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' def post_fork(server, worker): # also tried pre_fork and on_starting from psycogreen.gevent import patch_psycopg patch_psycopg() Result But the app only got slower, also note … -
django background longrunning tasks without celery
when writing the django-backend, we abandoned the use of Celery in favor of Process because we failed to cancel already running tasks but now we have to schedule long-runnning tasks that should be executed every 5 minutes or every 5 hours or every 3 hours (it's not necessary to be able to cancel them, of course, but I REALLY don't want to use celery) everywhere I saw that periodic tasks from celery were used to solve this problem, I want to find out what alternatives there are, it is important that it is performant and works on both windows and linux now we use such a code, we are satisfied with everything, except for a potentially bad performance # in tasks/management/commands/work class Command(BaseCommand): def handle(self, *args, **options): while(True): do_work() # work executed every 3 hours time.sleep(60 * 60 * 3) # sleep 3 hours # in tasks/management/commands/another_work class Command(BaseCommand): def handle(self, *args, **options): while(True): do_another_work() # work executed every 5 hours time.sleep(60 * 60 * 5) # sleep 5 hours how terrible is it to have several such tasks with while(True) + sleep in terms of performance? i wonder what code to solve this problem is at the heart of … -
Django - ForeignKey Filter Choices
I'd like to filter the choices that a user can choose in my ForeignKey Field. I basically have a ForeignKey for the subject of the Test and the actual topic of the Test. These topics come from a different model and are linked to a subject. Now I'd like to filter the choices to only include the topics that are linked to the currently selected subject. Is that possible and if so, how? models.py class Test(models.Model): student = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) thema = models.ForeignKey(Thema, on_delete=models.CASCADE, blank=True, null=True) school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, blank=True, null=True) grade = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(6)], blank=True, null=True) date = models.DateField(default=datetime.date.today) def save(self, *args, **kwargs): if not self.school_class and self.student: self.school_class = self.student.klasse return super().save(*args, **kwargs) class Thema(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) thema = models.CharField(max_length=50) -
Send a dict from js to views: return querydict who bursts my dict
I have a dict that I would like to send but I receive it in the form of a querydict whose content is no longer in the same form as the dict sent. How can i have an object that i can manipulate simply ? I would like to add the elements in a database so I should do a for loop and add by index (key1, key2) but I can't get the real length when i do len(request.POST) it return 5. .js function sendData(event){ const res = { 0:{"val1": 1, "val2":2}, 1:{"val1": 3, "val2":4}} ... $.ajax({ ... data: { "result": res, }, dataType: "json", ... }) } views.py def view1(request): print(request.POST) $ <QueryDict: {'csrfmiddlewaretoken': ['...'], 'result[0][val1]': ['1'], 'result[0][val2]': ['2'], 'result[1][val1]': ['3'], 'result[1][val2]': ['4']}> -
Set default values in Django form based on user's id/instance
I have created a customUser, then the foreign key of model class AddressBook (models.Model) is customUser.Id. Model Employer inherited from customUser. The other two models are class employee(CustomUser) and class Job(models.Model) Employer and Staff user could create a job. Now I would like to set fields of Employer and AddressBook in job form to be corresponding employer_org name and employer address if login user is employer. i.e. if employer 1 login, the job form will automatically show employer 1 org name and employer1 address. If employer 2 login, the fields will be employer2 org name and employer2 address. When Staff users sign in, they can select or type employer org name and employer address. Now my problem is even I sign in as employer 1, I can create a job for employer 2 when click the selection field. Here is my models: class AddressBook(models.Model): user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE) street = models.CharField(max_length=64,blank=False) alt_line = models.CharField(max_length=64, blank=True) postcode= models.CharField(max_length=5, validators=[RegexValidator('^[0-9]{5}$', _('Invalid postal code'))], blank=False) city = models.CharField(max_length=64, blank=False) country = models.CharField(max_length=64, default="some name") class Meta: verbose_name = 'AddressBook' def __str__(self): return '{} {}, {}, {}'.format(self.street, self.alt_line, self.postcode, self.city) class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=250, blank=False) last_name = models.CharField(max_length=250, blank=False) email = models.EmailField(('email address'), unique=True) phone … -
How to access the value of a foreign key in a table in django?
I've 2 tables in a database on phpmyadmin that are connected by a foreign key. The table "bulle" contains the foreign key of the table "site". In enghlish : one "site" can contain some "bulles" (or not) and a "bulle" is always linked to a "site". class Bulles(models.Model): id_bulle = models.AutoField(primary_key=True) num_bulle = models.CharField(max_length=20) type_bulle = models.CharField(max_length=20) colories = models.CharField(max_length=20) latitude = models.FloatField() longitude = models.FloatField() date_vidange = models.DateField( db_column="date_vidange" ) id_depot = models.ForeignKey( "Depot", on_delete=models.CASCADE, db_column="id_depot" ) id_site = models.ForeignKey( "Site",related_name='bul', on_delete=models.CASCADE, db_column="Id_site" ) class Meta: db_table = "bulles" class Site(models.Model): id_site = models.AutoField( db_column="Id_site", primary_key=True ) nom = models.CharField( db_column="Nom", max_length=100 ) vitesse_b = models.FloatField(db_column="Vitesse_b") # Field name made lowercase. vitesse_c = models.FloatField(db_column="Vitesse_c") # Field name made lowercase. ecart_type_b = models.FloatField( db_column="Ecart_type_b" ) ecart_type_c = models.FloatField( db_column="Ecart_type_c" ) type_site = models.CharField( db_column="Type_site", max_length=20 ) longitude = models.FloatField(db_column="Longitude") latitude = models.FloatField(db_column="Latitude") Nombre_bulles = models.IntegerField(db_column="Nombre_bulles") date_vidange = models.DateField( db_column="Date_vidange") class Meta: db_table = "site" I've created a request to delete a row in "bulle" selected by the id_bulle (primary key). I'd like to get the "id_site" from this selected bulle that I delete in this request. Then, I need to count every "bulles" of the table that have this id_site. … -
Django formtools gets caught in a loop
I'm working on a multistep form using django-formtools lib, and I'm facing a flow problem. In a specific step (fotoFormulaMedica) I have two buttons where basically the user choose his pathway. Either "take photo" or "choose a file". If he choose to take photo, it'll take him to the step called foto and then, once he clicks in continue, it'll continue the rest of the steps. So the next step will be avisoDireccion. If he choose to "choose an image", it'll take stay in the current step, he'll select an image from his pc and then, once he clicks in continue will continue the rest of the steps. So the next step will be avisoDireccion. It works great!, however, when all the steps are filled, instead of take to the done.html, he goes back to fotoFormulaMedica and the user gets caught in a loop. This is the repo https://github.com/Alfareiza/logifarma-radicar-domicilio/tree/1.configurando-cargar-y-tomar-foto Also you can check here my : views.py https://github.com/Alfareiza/logifarma-radicar-domicilio/blob/1.configurando-cargar-y-tomar-foto/core/apps/base/views.py forms.py https://github.com/Alfareiza/logifarma-radicar-domicilio/blob/1.configurando-cargar-y-tomar-foto/core/apps/base/forms.py I'll appreciate your help. I've tried to make the flow not including one of the pathways. I mean, if I exclude the take photo feature or select file feature. The flow works as I expected. -
making form filters interact with each other django
So I have a page in django that have a couple of forms that work as content filters. self.fields["brand"] = forms.ChoiceField( label="Brand", choices=self.__get_brand_choice(), widget=forms.Select(attrs={"class": "form-select",'onchange': 'submit();'}), required=False, ) def __get_brand_choice(self): products_id = ( SalesView.objects.filter(business_unit=self.business_unit).values_list("brand", flat=True).distinct() ) products_brand = Brand.objects.filter( id__in=products_id ).values_list("id", "name").order_by("name") return [ (None, "TODAS"), *products_brand, ] this for example is the two parts of the brand filterb (but all of them are basicaly the same), I have other to related to product type and sales volume. At the moment, when I select one option on of them the others it filters the page content but it doesn't filter the options of the other so I can only choose valid options. That's what I want to change, I want them to interact. For example, if I want to filter bread on the page I also want the brand filter to only show brands that have bread, and if I choose I certain brand I want the product type filter to only show products type related to this brand. I know that basically i have to pass this other parameter(s) in the orm query that quet the product list, but am not sure how to get these parameters from the … -
I'm facing issues in sql fetch data in django ? It returns None
This is test.py from django.http import HttpResponse import mysql.connector MySQLdb = mysql.connector host = 'xxxxxx' username = 'xxxx' db = 'xxxx' port = '3306' password = 'xxxxxx' class sql: def __int__(self): pass def mysql_connection(self): try: mysql_conn = mysql.connector.connect(host=host, user=username, database=db, password=password, port=port, ssl_disabled=True) print("Connection Successfully Established...") return mysql_conn except Exception as e: print("mysql connection error".format(e)) exit(0) def update_approval(self, que): d = self.mysql_connection() cursor = d.cursor() cursor.execute(que) result = cursor.fetchone() return result This is my views.py from django.shortcuts import render, redirect from .forms import InputForm, TestForm from django.core.mail import send_mail from .test import sql import mysql.connector MySQLdb = mysql.connector def index(request): if request.method == "POST": form = InputForm(request.POST) # ids = form["git_Id"].value() # print(ids) # query = f'SELECT request_id FROM request_form_mymodel where git_Id={ids};' # # p = obj.update_approval(query) obj = sql() # git_id = 5666 ids = form.data["git_Id"] print(ids) # query = "SELECT request_id FROM request_form_db.request_form_mymodel where git_Id='%s'" % ids q = "SELECT request_id FROM request_form_db.request_form_mymodel where git_Id={}".format(ids) p = obj.update_approval(q) print(p) approve_url = f"http://my_url_path/test?request_id={p}" if form.is_valid(): send_mail( 'KSA Test Activation', approve_url, 'my_sender_email_id', ['receiver_id'], fail_silently=False, ) form.save() form = InputForm() else: form = InputForm() return render(request, 'home.html', {'form': form}) This is forms.py ` from django import forms from .models import MyModel, … -
Everytime i try to install Django using "pip install django" on my command prompt why does this come up?
pip install Django 'pip' is not recognized as an internal or external command, operable program or batch file. -
Django: Retrieve a list of one model property for all distinct values of another property
I’d like to use the Django ORM to give me a list values of a model property for the subset of objects that have a distinct value of another property. Consider a simple model like: class Result(models.Model): color = models.CharField() score = models.IntegerField() And imagine that I have four results: results = [ Result(color="blue", score=5), Result(color="blue", score=3), Result(color="red", score=10), Result(color="red", score=8), ] What I'd like to get is something like the following: { {"color”: "blue", "scores": [5, 3]}, {"color": "red", "scores": [10, 8]}, } I think it's possible to get there in one shot using Django's aggregation and annotation features, but I'm struggling to figure it out. I know I can get the average score with the following: results.values("color").annotate(avg_score=Avg("score")) If that's possible, then getting the list used to generate the average must also be possible, right? -
How to store important queries in Djando models itself?
there are couple of queries which are important and used several times in different part of application. I wounder it would be great to have a method in the Model itself to retrieve requested data as needed. tried Classmethod and instance method but as the Manager is called in the query I got below error: AttributeError: Manager isn't accessible via ... instances code is look like below: class XDL(models.Model): name = models.CharField(max_length = 20) Order_Code_Description = models.CharField(max_length = 355) Status = models.CharField(max_length = 20) Supplier = models.CharField(max_length = 100) @classmethod def get_count_xdls(cls): return cls.objects.all() #query example def get_all_supps(self): return self.objects.all() #query example explained in Django documentation below: Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations Is there a best practice to store important queries in a method somewhere in Model (or other parts)? as these queries run several time and also writing it as a method help the documentation as well. -
Django: only CSS is not served by Nginx
I deployed my Django app on a VPS with Nginx and I want Nginx to handle the statics. The strange thing right now is that all the images are rendered properly, but the CSS is not working at all... Django setting: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') Nginx configure: location /static/{ alias /home/xxx/App/django_app/static_root/; } In html template: <link rel="stylesheet" href="{% static 'app1/css/style.css' %}" type="text/css" media="all"> <img src="{% static 'app1/images/page1_img1.jpg' %}" alt=""> I've run python manage.py collectstatic, set Debug = False (everything works fine when Debug is true). I can confirm that all images are located in /home/xxx/App/django_app/static_root/app1/images, while all css files are under /home/xxx/App/django_app/static_root/app1/css. I'm able to access the css file with the url https://myserver/static/app1/css/style.css, also there is no error message in Nginx log. I've tried different browsers, cleared cache, restarted the server and Nginx several times with no luck, really running out of idea... Any suggestion would be appreciated. -
Django - ForeignKey Add Users Value As Default
I'd like to implement a grading model into my Django WebApp. This Grade Model has 3 ForeignKeys being a student, a subject and the schoolclass of the student. Is there a way to default the value of that field to student.klasse (which is already a field in the student model). models.py class Person(AbstractUser): # called the model Person since they can be teacher or student klasse = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, blank=True, null=True) class Test(models.Model): student = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, default=student.klasse_id, blank=True, null=True) It throws this Error when trying to make the migration: school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, default=student.klasse_id, blank=True, null=True) AttributeError: 'ForeignKey' object has no attribute 'klasse_id' -
TypeError: translation() got an unexpected keyword argument 'codeset'
I'm following a Python tutorial on youtube and need to create a django website, however I am unable to start, because when I enter "python manage.py runserver" I get the "TypeError: translation() got an unexpected keyword argument 'codeset'" message. I've run back the video like 20 times to see if I've missed anything, but no, because it's just the beginning of the django website tutorial. I've also tried typing python3 instead of python and some other options I saw on Stack Overflow, but none are really exactly relevant to the error message I'm getting. Perhaps someone knows how to fix this? I tried to start a development server by typing in "python manage.py runserver" which was supposed to start a django webserver at 127.0.0.1:8000 or something, but instead I got the error message specified in the title code: PS C:\Users\kaspa\PycharmProjects\PyShop> python manage.py runserver Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x00000145784C1F80> Traceback (most recent call last): File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, … -
How to 'add' QuerySet in Django?
I have written the below code. for number in numbers: booking_list = Booking.objects.filter(rooms=number) Here, numbers is a list of numbers. The problem with this code is that booking_list will only contain the QuerySet of the last number as the previous QuerySets will be overwritten but I want booking_list to contain all the QuerySets. Moreover, I want the QuerySets to be unique. In other words I want a union of the QuerySets. The reason as to why the QuerySet may have repeated vaues is because rooms is a list of numbers. Edit: The actual problem is complex. models.py class Booking(models. Model): customer_name = models.CharField(max_length=30) check_in_date = models.DateField() check_in_time = models.TimeField() check_out_time = models.TimeField() room_numbers = models.CharField(validators=[validate_comma_separated_integer_list], max_length=4000) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = models.CharField(max_length=9, choices=ROOM_CATEGORIES) PERSON = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) person = models.PositiveSmallIntegerField(choices=PERSON, default=1) no_of_rooms = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], default=1 ) room_numbers can have values like [4, 21, 62, 50, 2, 12]. views.py for room_number in room_numbers: regex = rf"\b{room_number}\b" keys = ['room_numbers__iregex', 'customer_name', 'check_in_date', 'check_in_time', 'check_out_time', 'category__in', 'person__in', 'no_of_rooms'] values = [regex, customer_name, check_in_date, check_in_time, check_out_time, category, person, no_of_rooms] parameters = {} for … -
How to create a user specific home page
I'm busy learning Django. My current home page displays the posts, or posted passwords, for all users that have an account. I want the login page to display data unique to the logged in user. I've looked all over for a solution to this ... It seems straightforward, but I can't figure it out. I already have a detailed view for all posts created by a single user, but I don't know how to adapt that to serve as the actual home page once a user has logged in. Here's some of the code I've experimented with so far. I guess I'm trying to merge the functionality of UserPasswordListView class with the index view ... but I'm just not sure how to do so. views.py def index(request): context = { 'sites': SitePassword.objects.all() } return render(request, 'core/index.html', context) class PasswordListView(ListView): model = SitePassword template_name = 'core/index.html' context_object_name = 'sites' class UserPasswordListView(ListView): model = SitePassword template_name = 'core/user_sitepassword.html' context_object_name = 'sites' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return SitePassword.objects.filter(user=user) class PasswordDetailView(DetailView): model = SitePassword models.py class SitePassword(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) password = models.CharField(max_length=200) email = models.CharField(max_length=200) logo = models.CharField(max_length=300) def __str__(self): return self.name def get_absolute_url(self): return reverse('sitepassword-detail', kwargs={'pk': … -
How to join two tables in Flask using mysqldb
I have two tables: the client table and the task table. I have added clients like 1) id , name,emai, phone,project. now I have to use this client in my second table task when I add a task it shows the client name automatically in task table form. how to get this using Flask and mysqldb (not sqlalchemy) i will get empty value insted of it shwo client -
django test.py changes the autoincrement of table
In the test.py I make new entry id=10000 for testing purpose(id is auto increment, current auto increment number is 36) temp = sm.mytable(id=10000,created_by="test",created_at=datetime.datetime.now()) temp.save() After test, this row is removed() automatically. However autoincrement number start from 10000~ Why this happen? database control in test.py affect the real database? -
why my second app doesn't want import to first app Django
File "C:\python mini\PyCharm Community Edition 2021.1.1\MyBlog\mysite\mysite\urls.py", line 3, in <module> from mysite.register import views ModuleNotFoundError: No module named 'mysite.register' Why do you think this error might occur? Why doesn't django see the app being imported? maybe I should try setting up mysite/blog urls? project structure: settings.py ` from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_DIR = os.path.join(BASE_DIR, 'static') CRISPY_TEMPLATE_PACK = "bootstrap4" STATIC_URL = '/static/' SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'menu', 'register.apps.RegisterConfig', ] mysite/urls.py from django.contrib import admin from django.urls import path, include from mysite.register import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path("register/", views.register, name="register"), ] ` If i try write just from register import views import underlined in red -
What do I have to do to make a django project available to my company's internal network?
Recently I developed a simple django project to be used by my colleagues. The goal was to have the project only available within the network so no one outside the company could access it. The company has a server, with a certain IP that will host the project. What steps do I have to take, either in django or on the company server, to make the project available to everyone in the company? Do I have to install python in the server? I tried to put the servers IPs in allowed_hosts but it doesn't work. Thanks for helping, Edward -
Getting incorrect title in the URL path Django
I have an app with a bunch of POST request on a path that looks like this: path("auctions/<str:title>", views.listing, name="listing") It's a sort of auction app, where users can create listings, and others can place bids and purchase these items. When a user clicks on one of these items, ive got this function that takes them to a page where they can get all details about the listing that they have just clicked and they can do things like place a bid or place the item in their watchlist. views.py def listing(request, title): if request.method == "POST": if watchlist.is_valid(): if "watchlist" in request.POST: watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first() if watchlist_data: watchlist_data.delete() else: true_wtchlist = Watchlists.objects.create(title=title, user=username) ps: watchlist here is just an example of one of the conditions under my function, i just posted it as an example, even though i will appreciate any errors beign pointed out if any is noticed. I can usually get the title of the listing that was clicked from the title argument that gets passed here def listing(request, title): , and i use this title to query the database. Now I am trying to add a 'Close listing' button to the page so that the … -
Django admin inline: Clone entry
I`m using a GenericStackedInline in my django admin. I would like to have the option to duplicate the inline object when editing the parent object. I can think of two ways of doing this: Using django-inline-actions to add a "clone" button. This did not work, because it does not show when using a fieldset in the GenericStackedInline Adding another checkbox next to "delete" checkbox with label "clone". When activating the checkbox and saving parent object, it should clone the inline object with new id. Is there an easy way to add another checkbox and add a action to handle cloning?