Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setup django DB to show PRODUCT ->> WEBSITE ->> ITEM DETAILS
I want to be scraping and storing products and display the price which may vary depending on website and item details such as price and shipping might be different. I want to know would this structure work? PRODUCT: foreignkey -> website website: foreignkey -> item details or a different suggestion. Anyone? I havent tried anything yet I was wondering what the thoughts on proper structure would be. -
How can I pass the value of a javascript variable to django?
How can I send the value of "const token" to django? function getToken() { PagSeguroDirectPayment.createCardToken({ cardNumber: '4111111111111111', brand: 'visa', cvv: '123', expirationMonth: '12', expirationYear: '2030', success: function(response) { const token = response.card.token; }, error: function(response) { }, complete: function(response) { } }); } the getToken() function is being executed like this: <form action="{% url 'payments' %}" method="POST" onsubmit="getToken()"> I had tried to pass the Token value to a hidden input, and then I tried to get that value in django as shown below, but the input takes a while to receive the value and is already sent to the other page immediately. That way I would need to make sure that the input has the token value to let it forward to the other page success: function(response) { document.getElementById('cardToken').value = response.card.token; }, -
I tried to make MultilingualModel in Django but the language keeps being by default and won't change
i am trying to make multilingual model in Django. But my code doesn't work, it just ignores my function select_language and selects default_language. I have no idea whats causing the error. Here is my code models.py class MultilingualQuerySet(models.query.QuerySet): selected_language = None def __init__(self, *args, **kwargs): super(MultilingualQuerySet, self).__init__(*args, **kwargs) def select_language(self, lang): self.selected_language = lang return self def iterator(self): result_iter = super(MultilingualQuerySet, self).iterator() for result in result_iter: if hasattr(result, 'select_language'): result.select_language(self.selected_language) yield result def _clone(self, *args, **kwargs): qs = super(MultilingualQuerySet, self)._clone(*args, **kwargs) if hasattr(qs, 'select_language'): qs.select_language(self.selected_language) return qs class MultilingualManager(models.Manager): use_for_related_fields = True selected_language = None def select_language(self, lang): self.selected_language = lang return self def get_query_set(self): qs = MultilingualQuerySet(self.model, using=self._db) return qs.select_language(self.selected_language) class MultilingualModel(models.Model): objects = MultilingualManager() # fallback/default language code default_language = None # currently selected language selected_language = None class Meta: abstract = True def select_language(self, lang): """Select a language""" self.selected_language = lang return self def __getattribute__(self, name): def get(x): return super(MultilingualModel, self).__getattribute__(x) try: # Try to get the original field, if exists value = get(name) # If we can select language on the field as well, do it if isinstance(value, MultilingualModel): value.select_language(get('selected_language')) return value except AttributeError as e: # Try the translated variant, falling back to default if … -
Django channels AnnonymousUser on the Safari webbrowser
I have chat where after login you can send message but if you aren't logged user you can't send it, because you are AnnonymousUser and consumer can't take your name. On the Safari browser after login i'm going to 127.0.0.1:3000/chat and i get logged out automatically, but if i'm making it with opened developer tools then i'm still logged and i can send a message. On the other browser (firefox) all work fine. I have no idea. Thanks for your help class ChatRoomConsumer(WebsocketConsumer): def connect(self): self.user = self.scope["user"] self.to_user = 'testowy' async_to_sync(self.channel_layer.group_add)(self.to_user, self.channel_name) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.to_user, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] now = timezone.now() async_to_sync(self.channel_layer.group_send)( self.to_user, { "type": "chat_message", "message": message, "user": self.user.email, "datetime": now.isoformat(), } ) def chat_message(self, event): self.send(text_data=json.dumps(event)) export const Chat = () => { const [messages, setMessages] = useState([]) const [client, setClient] = useState({}) useEffect(()=> { const token = sessionStorage.getItem('access_token') const client = new W3CWebSocket('ws://127.0.0.1:8000/ws/chat/?token=' + token) setClient(client) },[]) client.onmessage = (event) => { const data = JSON.parse(event.data) const fullMessage = { "message": data.message, "datetime": data.datetime, "user": data.user } setMessages((prevState) => [...prevState, fullMessage]) } let corpusMessages if(messages.length > 0){ corpusMessages = ( <Grid> {messages.map((fullMessage)=>{ return ( … -
Deploying Django app with GoDaddy domains and cPanel
I am trying to deploy my first Django app. I already own the domain using goDaddy domains and I am trying to set up the Django application. I am trying to find the terminal in the Advanced section in cPanel but it is not there. how can I use the terminal? -
how can i enable login with email and phone number in Django rest framework?
I want to enable login with an email and phone no in the Django project. Like users can put their email or phone number in the input field as their wish. -
Django .How to show recommended products and products of the same collection in the product card under the product
Each product has a page with a card, more detailed information about the product.How to implement the output on the product card page of all products of the same model. Let's say the Adidas product and below are all Addidas products.The problem is that the product card page displays only information about one product watch_card = get_object_or_404(Whatches, pk=watch_pk) models.py class Collections_foreignkey(models.Model): name=models.CharField(max_length=250, verbose_name='Коллекция') def __str__(self): return self.name ``` class Whatches(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=250, verbose_name='Название') description=models.TextField(verbose_name='Описание',blank=True) collections=models.ForeignKey(Collections_foreignkey, on_delete=models.CASCADE, verbose_name='Коллекция' ,blank=True,null=True,related_name='watches_collections') def __str__(self): return self.title # views.py def watch_card(request, watch_pk): watch_card = get_object_or_404(Whatches, pk=watch_pk) return render( request, 'mains/about/catalog/watches/watch_card.html', context={ 'watch_card': watch_card, }, ) def watches(request): watch_card = Whatches.objects.all() whatches_filter =WhatchesFilter(request.GET,queryset=watch_card) #фильтрация на сайте return render(request,'mains/about/catalog/watches/index.html', context={ 'watch_card': watch_card, 'form':whatches_filter.form, 'whatches_filter':whatches_filter.qs, #фильтр для всего в виде select option из filters.py }, ) -
Showing duplicate data after the data is changed and refresh the page in django python
I want to show the data on localhost only for once as it comes twice and wherever I change the data.py and refresh the page then the new layer of data is adding. So if data is titles = { "data": [ { "sid": "1234", "name": "name_1" }, { "sid": "5678", "name": "name_2" }, { "sid": "9012", "name": "name_3" } ] } then it should appear in the output as SD Name 1234 name_1 5678 name_2 9012 name_3 so if I change the data in data.py file titles = { "data": [ { "sid": "0000", "name": "name_1" }, { "sid": "12313", "name": "name_2" }, { "sid": "543534", "name": "name_3" } ] } the output should appear like this SD Name 0000 name_1 12313 name_2 543534 name_3 current output is SD Name 1234 name_1 5678 name_2 9012 name_3 0000 name_1 12313 name_2 543534 name_3 the output is adding the previous records. What I want is after refreshing it should appear the current data in data.py file views.py from django.shortcuts import render from .models import Title def get(request): context = {'titles': Title.objects.all()} return render(request, "home.html", context) home.html <!DOCTYPE html> <html lang="en"> <head> <title>TableView - Startup</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link … -
No module named 'globals'
I have a folder that has a Django Framework in it. I try to call files that are outside of this folder but I get the following error: No module named 'globals' This path folder: api_yahoo_finance/yahoo/api_yahoo/views And in the views file, I try to use the file that exists outside this folder. (Outside of api_yahoo) I tried to read on the internet and understand what the problem is, I saw comments that said to add a init file, I added it but it didn't help. -
Error while working on the site in Django, part 2
This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up: C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models. new_class._meta.apps.register_model(new_class._meta.app_label, new_class) Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Program Files\Python36\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 416, in check for pattern in self.url_patterns: File "C:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = … -
django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am troubleshooting an NGINX/Django/UWSGI application for a customer, that has been broken beyond expectations. I've been debugging code, and re-writing for 30+ hours now and am at another hurdle that I can't seem to get past on my own. [pid: 336873|app: 0|req: 1/1] 198.11.30.68 () {46 vars in 1070 bytes} [Mon Dec 5 10:04:42 2022] GET / => generated 0 bytes in 393 msecs (HTTP/1.1 500) 0 headers in 0 bytes (0 switches on core 0) announcing my loyalty to the Emperor... Traceback (most recent call last): File "/home/django/django_venv/django_site/wsgi.py", line 26, in application get_wsgi_application(); File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application WSGIHandler(); File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/handlers/wsgi.py", line 127, in __init__ self.load_middleware() File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/handlers/base.py", line 40, in load_middleware middleware = import_string(middleware_path) File "/home/django/django_venv/lib64/python3.6/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/django/django_venv/lib64/python3.6/site-packages/django/contrib/auth/middleware.py", line 3, in <module> from django.contrib.auth.backends import RemoteUserBackend File "/home/django/django_venv/lib64/python3.6/site-packages/django/contrib/auth/backends.py", line 2, in <module> from django.contrib.auth.models import Permission File … -
table has found to column named
My issue is that when i submit my registration form to back it up, the page shows an operationalError and doesn't recognise the first item of my model which is the first name. I've tried makeMigrate after all modifications and rewriting all the items to make sure they match. def registration_view(request): if 'email' in request.GET: newUser = User(firstname=request.GET['firstname'], lastname=request.GET['lastname'], country=request.GET['country'], email=request.GET['email'], phone=request.GET['phone'], password=request.GET['password'], gender=request.GET['gender']) newUser.save() return redirect('/signin') else: response = render(request, 'registration.html') return response from django.db import models class User(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=50) country = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone = models.CharField(max_length=30) password = models.CharField(max_length=128) GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ('X','X'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) friends = models.ManyToManyField('self') conjoint = models.OneToOneField('self', on_delete=models.CASCADE) def __str__(self): return self.firstname + ' ' + self.lastname class WallMessage(models.Model): author = models.ForeignKey('User', on_delete=models.CASCADE) content = models.TextField() publication_date = models.DateField() -
django add amp; to context value , how to solve that ,
I pass url from view by context like this : context = {"url":"https://fra1.digitaloceanspaces.com/logatta-space/organization_survey/static/img/page1-d.jpg?AWSAccessKeyId=DO00GN8LVUJB9VNAQL69&Signature=EM6bumz7gPzaPBPqHHdGfqBMVWk%3D&Expires=1670256832"} return render(request, 'index1.html', context) when i recive the same url like this from chrome inspect: .start-template { background-image:url(https://fra1.digitaloceanspaces.com/logatta-space/organization_survey/static/img/page1-d.jpg?AWSAccessKeyId=DO00GN8LVUJB9VNAQL69&amp;Signature=EM6bumz7gPzaPBPqHHdGfqBMVWk%3D&amp;Expires=1670256832); } the template add amp; to the url inside the template and this casess some problems and this is my html code : background-image:url({{url}}); my question: how to pass url as is ,without add amp; in middel of my url -
ValueError when i compare input values with database object
I want to compare form input with database value. For example: There's a input field called password .. and i want to compare the input value with a password inside the database (in case i know the row already (id)) But when i compare it, i got valueerror like this. googling like 2 hours and nothing works. I'm new to django .. I hope someone can help me :D Here is my view code id = modelUser.objects.values('id').filter(username=txtUsername) checkPassword = modelUser.objects.values('password').filter(username=txtUsername) if(txtPassword == checkPassword.password): return render(request,'success.html') Models.py class modelUser(models.Model): firstname = models.CharField(max_length=200, null=False, blank=False) lastname = models.CharField(max_length=200, null=False, blank=False) username = models.CharField(max_length=200, null=False, blank=False) password = models.CharField(max_length=200, null=False, blank=False) def __str__(self): return self.username -
Python/Django Prevent a script from being run twice
I got a big script that retrieves a lot of data via an API (Magento Invoices). This script is launched by a cron every 20 minutes. But sometimes, we need to refresh manually for getting the last invoiced orders. I have a dedicated page for this. I would like to prevent from manual launching of the script by testing if it's already running because both API and script take a lot of ressources and time. I tried to add a "process" model with is_active = True/False that would be tested and avoid re-launching if script is already active. At the start of the script, I switch the process status to TRUE and set it to FALSE when the script has finished. But it seems that the 2nd instance of the script waits for the first to be finished before starting. At the end, both scripts are run because process.is_active always = False I also tried with request.session variable, but same issue. Spent lotsa time on this but didn't find a way to achieve my goal. Has anyone already faced such a case ? -
why do i get an instant error when making an app
After installing the 'likes' app in my project I immediately get a syntax error in the models.py file and I can not save the file or any changes. even when typing i don't get suggestions for my code which is normal cuz of the syntax error. What can this because I can't find anything for this problem. I did try to delete the app 'likes' but everytime when I do python manage.py startapp likes. I immediately get the same error with a red dot next to the likes map. -
Dockerized django container not producing local migrations file
Question I am a beginner with docker; this being the first project I have set up with it and don't particularly know what I am doing. I would very much appreciate if someone could give me some advice on what the best way to get migrations from a dockerized django app to store locally What I have tried so far I have a local django project setup with the following file structure: .docker -Dockerfile project -data -models - __init__.py - user.py - test.py -migrations - 0001_initial.py - 0002_user_role.py ... settings.py ... manage.py Makefile docker-compose.yml ... In the current state the migrations for the test.py model have not been run; so I attempted to do so using docker-compose exec main python manage.py makemigrations. This worked successfully returning the following: Migrations for 'data': project/data/migrations/0003_test.py - Create model Test But produced no local file. However, if I explore the file system of the container I can see that the file exists on the container itself. Upon running the following: docker-compose exec main python manage.py migrate I receive: Running migrations: No migrations to apply. Your models in app(s): 'data' have changes that are not yet reflected in a migration, and so won't be applied. … -
Django query in multiple table
I have 4 tables that contain data I want the query that will allow me to filter the policies according to the date and health center. Currently the code I filter the date but not the health center since they are not contained in the same table I do not know i I have to make a join or I just create a variable like what I did but that does not take. I have four models that can be used to show exactly how the tables are linked ` class Policy(core_models.VersionedModel): id = models.AutoField(db_column='PolicyID', primary_key=True) uuid = models.CharField(db_column='PolicyUUID', max_length=36, default=uuid.uuid4, unique=True) stage = models.CharField(db_column='PolicyStage', max_length=1, blank=True, null=True) status = models.SmallIntegerField(db_column='PolicyStatus', blank=True, null=True) value = models.DecimalField(db_column='PolicyValue', max_digits=18, decimal_places=2, blank=True, null=True) family = models.ForeignKey(Family, models.DO_NOTHING, db_column='FamilyID', related_name="policies") enroll_date = fields.DateField(db_column='EnrollDate') start_date = fields.DateField(db_column='StartDate') effective_date = fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date = fields.DateField(db_column='ExpiryDate', blank=True, null=True) product = models.ForeignKey(Product, models.DO_NOTHING, db_column='ProdID', related_name="policies") officer = models.ForeignKey(Officer, models.DO_NOTHING, db_column='OfficerID', blank=True, null=True, related_name="policies") offline = models.BooleanField(db_column='isOffline', blank=True, null=True) audit_user_id = models.IntegerField(db_column='AuditUserID') ` ` class InsureePolicy(core_models.VersionedModel): id = models.AutoField(db_column='InsureePolicyID', primary_key=True) insuree = models.ForeignKey(Insuree, models.DO_NOTHING, db_column='InsureeId', related_name="insuree_policies") policy = models.ForeignKey("policy.Policy", models.DO_NOTHING, db_column='PolicyId', related_name="insuree_policies") enrollment_date = core.fields.DateField(db_column='EnrollmentDate', blank=True, null=True) start_date = core.fields.DateField(db_column='StartDate', blank=True, null=True) effective_date = core.fields.DateField(db_column='EffectiveDate', blank=True, null=True) expiry_date … -
Error: Docker build failed cuando subo un proyecto Django a Railway
Estoy intentando subir mi proyecto Django a Railway, pero cuando lo esta subiendo me aparece el errpr de Error: Docker build failed Busque informacion de este error, pero aun no encuentro una solucion para esto Esto es una parte del Build Logs #11 6.938 Preparing metadata (setup.py): finished with status 'error' #11 6.945 error: subprocess-exited-with-error #11 6.945 #11 6.945 × python setup.py egg_info did not run successfully. #11 6.945 │ exit code: 1 #11 6.945 ╰─> [18 lines of output] #11 6.945 mysql_config --version #11 6.945 /nix/store/1b9p07z77phvv2hf6gm9f28syp39f1ag-bash-5.1-p16/bin/sh: line 1: mysql_config: command not found #11 6.945 mariadb_config --version #11 6.945 /nix/store/1b9p07z77phvv2hf6gm9f28syp39f1ag-bash-5.1-p16/bin/sh: line 1: mariadb_config: command not found #11 6.945 mysql_config --libs #11 6.945 /nix/store/1b9p07z77phvv2hf6gm9f28syp39f1ag-bash-5.1-p16/bin/sh: line 1: mysql_config: command not found #11 6.945 Traceback (most recent call last): #11 6.945 File "<string>", line 2, in <module> #11 6.945 File "<pip-setuptools-caller>", line 34, in <module> #11 6.945 File "/tmp/pip-install-mt5wgibs/mysqlclient_2b639a2efa944f928deea71cdfaf5c0c/setup.py", line 15, in <module> #11 6.945 metadata, options = get_config() #11 6.945 ^^^^^^^^^^^^ #11 6.945 File "/tmp/pip-install-mt5wgibs/mysqlclient_2b639a2efa944f928deea71cdfaf5c0c/setup_posix.py", line 70, in get_config #11 6.945 libs = mysql_config("libs") #11 6.945 ^^^^^^^^^^^^^^^^^^^^ #11 6.945 File "/tmp/pip-install-mt5wgibs/mysqlclient_2b639a2efa944f928deea71cdfaf5c0c/setup_posix.py", line 31, in mysql_config #11 6.945 raise OSError("{} not found".format(_mysql_config_path)) #11 6.945 OSError: mysql_config not found #11 6.945 [end of output] … -
Django server hangs sometimes
I am new to Django and I run into strange problem that the server hangs sometimes. The server uses APScheduler to do periodic tasks and send data to frontend via WebSocket. So, after the server freezes, I pressed CRTL+C to perform keyboard Interrupt. The server became normal again. I run the server in debug mode locally on my machine. But this problem only happens once or twice for the past two weeks. The rest of time it runs normally. The first time it happened when I tried to login. Application instance \<Task pending name='Task-1119' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox25f4bObad70 method=POST uri=/admin/login/ clientproto=HTTP/1.1\> took too long to shut down and was killed The second time it happened when I tried to visit taskManager page. Application instance \<Task pending name='Task-153' coro=\<StaticFilesWrapper.__call__() running at D:\\Python\\Python310\\lib\\site-packages\\channels\\staticfiles.py:44\> wait_for.\<Future pending cb=\[\_chain_future.\<locals\>.\_call_check_cancel() at D:\\Python\\Python310\\lib\\asyncio\\futures.py:385, Task.task_wakeup()\]\>\> for connection \<WebRequest at Ox19fbb5140550 method=POST uri=/taskManager clientproto=HTTP/1.1\> took too long to shut down and was killed Python: 3.10.7 Django: 3.2 Channel: 3.0.5 And I am using InMemoryChannelLayer I am not sure if it jammed when trying to response GET or POST, or the server jammed first so it cannot process any … -
Django TypeError - context must be a dict rather than a set [closed]
I am trying to display certain objects to the user. The views.py method filters through the objects to get the ones we need and renders this using a template. However when doing this I receive a TypeError that context must be a dict rather than set. This is my views.py method def showings_view(request, performanceId): currbooking = Booking.objects.get(id=performanceId) l = shows.objects.filter(booking = currbooking) return render(request, 'show_list.html',{'l', l}) Edit: It says question closed due to a typo - could someone at least let me know what the typo is? -
How to enable or disable fields in a form according to previous answers?
I am working on the development of a web application with Django and the following question has arisen: I put an example: I am performing a registration and I want to know if the user who is registering has a phone number and in the case of having it that a field is enabled to enter it. In the case that he/she does not have it, he/she should not be able to enter it. Does anyone know how I can develop this option? Thanks in advance I tried to put an IF in the creation of the model but it did not work. -
Forward content from one html to another html via views.py
I try to send the content from 'addQuestion.html' to "approve_question.html" but i get the Error: approve_questions() missing 1 required positional argument: 'form' What i do False. I hpe someone can solve my issue views.py def question (request): form = addQuestionform() if (request.method == 'POST'): form = addQuestionform(request.POST) if (form.is_valid()): form.save(commit=False) html = render_to_string("notification_email.html") send_mail('The contact form subject', 'This is the message', 'noreply@codewithstein.com', ['example@gmail.com'], html_message=html) approve_questions(request, form) return redirect("dashboard") context = {'form': form} return render(request, 'addQuestion.html', context) def approve_questions(request, form): context = {'form' : form} return render(request, "approve_question.html", context) -
Clicking the button in the html template does not change the "status" field in the django model
everyone! I have models.py class Post(models.Model): ... status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='Activated') ... urls.py app_name = 'posts' urlpatterns = [ ... path('<int:pk>/update/', views.PostUpdateView.as_view(), name='update_status')] views.py class PostUpdateView(UpdateView): model = Post template_name = 'post_detail.html' def change_status(self): if request.method == "POST": post = Post.objects.filter(id=self.id) if post.status == 'Activated': post.status = 'Deactivated' post.save() elif post.status == 'Deactivated': post.status = 'Activated' post.save() return redirect('posts:post_detail') posts_detail.html ... <form action="{% url 'posts:update_status' post.id %}" method="post"> {% csrf_token %} <button type="button"> {% if post.status == 'Activated' %} Deactivate {% else %} Activate {% endif %}</button> </form> ... I want to switch the field on the button "Activate/Deactivate" and redirect to the same page. At the moment there is a button and when clicked nothing changes. Well or maybe the redirect works, but the status does not switch. I'm assuming wrong views.py, but can't figure out where. I tried it like this @require_http_methods(['POST']) def update_status(request, id): if post.status == 'Activated': Post.objects.filter(id=id).update(status='Deactivated') elif post.status == 'Deactivated': Post.objects.filter(id=id).update(status='Activated') return redirect('posts:post_detail') But that doesn't work either. I know these are similar ways, but I don't have any more ideas. -
Django admin inline and multiple queries
I'm optimizing Django admin, and have some issues with inlines. I saw a few questions from Stack Overflow, but none was helpful. Here is my code: models/consumer_application.py class ConsumerApplication(TimeStampedModel, ActivatorModel, HumanReadableIdModel): uuid = models.UUIDField(default=uuid.uuid4, db_index=True, unique=True) status = models.ForeignKey("consumer.ApplicationStatus", on_delete=models.PROTECT) ... models/offer.py class ConsumerApplication(TimeStampedModel, ActivatorModel, HumanReadableIdModel): uuid = models.UUIDField(default=uuid.uuid4, db_index=True, unique=True) application = models.ForeignKey("consumer.ConsumerApplication", on_delete=models.PROTECT, related_name="offers") ... admin.py @admin.register(ConsumerApplication) class ConsumerApplicationAdmin(UserInlineCustomAdminMixin, AddNewDisabled, admin.ModelAdmin): exclude = [...] list_display = (...) search_fields = (...) readonly_fields = (... ) inlines = [OfferInline] def get_queryset(self, request): return super().get_queryset(request).prefetch_related("offers") class OfferInline(admin.TabularInline): model = Offer exclude = [...] And when I open ConsumerApplication detail view, I have 6 offers displayed, and 12 queries: SELECT "consumer_offer"."id", "consumer_offer"."application_id" FROM "consumer_offer" WHERE "consumer_offer"."id" = 675 LIMIT 21 I was trying to override get_queryset of OfferInline, but whatever I did, I get the same. How can I optimize it, so that I don't have these 12 queries?