Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way of integrating vite and vue with Django without using Django Rest Framework
I have a Django app, I want to use vuejs with vite as the frontend, I don’t want to use Django Rest Framework. Is there a way to make this stack work properly? I tried install vite in a separate folder within the Django project directory and I am not sure how to connect the vue files with Django -
Can someone please explain these Django code?
I am new to python and Django. While I am learning Django I cam across the below code. Can someone please explain how this save() function works? def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(JobPost, self).save(*args, **kwargs) Full code is class JobPost(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) salary = models.IntegerField() slug = models.SlugField(null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, null=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(JobPost, self).save(*args, **kwargs) I tried to find articles regarding it, but I couldn't find an answer. -
export ui from figma/adobe xd to python(tkinter and kivy)
can I export ui element from ui software to kivy and tkinter? I did not try but I want to learn that before I dive into tkinter more and more. -
Customize options inside the ModelChoiceField Django forms
a have django form like this: class AddUserGroupFrom(forms.ModelForm): class Meta: model = UsersGroups fields = ( 'tag', ) widgets = { 'tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Work, home, etc..'}), } def __init__(self, *args, **kwargs): super(AddUserGroupFrom, self).__init__(*args, **kwargs) self.fields['city'] = forms.ModelChoiceField( queryset=Group.objects.values_list('city').all().distinct(), widget=forms.Select(attrs={ 'class': 'form-select form-select-sm mb-3', 'aria-label': '.form-select-sm example', }), label='Choose city name', empty_label='Select city', ) self.fields['group'] = forms.ModelChoiceField( queryset=Group.objects.values_list('group_number').all(), widget=forms.Select(attrs={ 'class': 'form-select form-select-sm mb-3', 'aria-label': '.form-select-sm example', }), label='Choose group number', empty_label='Select group', ) The problem that in my select field options displayed as tuples Form representation Templates look like this: <form action="" method="post"> {% csrf_token %} <div class="mb-3"> <label for="{{ add_group_form.tag.id_for_label }}" class="form-label">{{ add_group_form.tag.label }}</label> {{ add_group_form.tag }} </div> <label for="{{ add_group_form.city.id_for_label }}">{{ add_group_form.city.label }}</label> {{ add_group_form.city }} <label for="{{ add_group_form.group.id_for_label }}">{{ add_group_form.group.label }}</label> {{ add_group_form.group }} <input type="submit" value="Save changes" class="btn btn-success"> </form> How i can remove tuple-style representation in options inside the select field? I tried to iterate within indexes in templates: {{ add_group_form.city[0] }} But it throws error: Could not parse the remainder: '[0]' from 'add_group_form.city[0]' -
Does Heroku provide any VPN client like AWS Client VPN?
I want to host a database in Heroku server and also a django application. The problem is: To transfer data to my Heroku database i would need be connected to a VPN. Does Heroku provides a way to connect to a VPN in order to access another database, like AWS client VPN? My infra would be like this: Airflow running DAGs to pull data from a AWS database that requires VPN connection to source from it. I would transfer the data from this AWS database to my heroku database. Is it possible? Thank you Another thing that i'm wondering is if it is possible to connect Heroku to AWS client VPN, in case Heroku does not have something similar or a way to do this step. -
Django Deployment Error - No module named ‘psycopg2’” using heroku
Currently, I am deploying my Django app, but I am getting an error “django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named ‘psycopg2’” I installed psycopg2 & psycopg2-binary on windows within the virtualenv, but the error still persists. Disabled Django collectstatic ( env var DISABLE_COLLECTSTATIC) because it was another error with psycopg2. Do I need to deploy in ubuntu VM? git push heroku master Enumerating objects: 9, done. Counting objects: 100% (9/9), done. Delta compression using up to 8 threads Compressing objects: 100% (5/5), done. Writing objects: 100% (5/5), 496 bytes | 496.00 KiB/s, done. Total 5 (delta 3), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> No Python version was specified. Using the same version as the last build: python-3.11.2 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> No change in requirements detected, installing from cache remote: -----> Using cached install of python-3.11.2 remote: -----> Installing pip 22.3.1, setuptools 63.4.3 and wheel 0.38.4 remote: Skipping installation, as Pipfile.lock hasn't changed since last deploy. remote: -----> Installing SQLite3 remote: -----> Skipping Django collectstatic … -
django: conditional charfield annotate with `when` in new field
I don't know why this doesn't work Groups.objects.annotate( status=Case(When(Q(is_approved=True) & Q(is_good=True),then='active'), default=Value('inactive'),output_field=CharField() )) In my Groups object I want to create a new field status and set it to active or inactive. then use it in templates. But it keeps saying that the keyword active is not in choices... of course is not in choices because I'm creating it with annotate but it doesn't work. what is wrong? btw In contrast the following works: Groups.objects.annotate( status=Value( 'active', output_field=CharField() ) ) but it has no condition with ẁhen -
WinError 10061 Django + redis
I have a problem while running celery with redis. When trying to execute the task, it displays this error: [WinError 10061] The connection cannot be established because the target computer actively refused it. Currently my code looks like this: settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = mail@gmail.com EMAIL_HOST_PASSWORD = password broker_url = 'redis://127.0.0.1:6379' accept_content = ['json'] result_accept_content = ['json'] celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rental.settings') app = Celery('rental') app.conf.enable_utc = False app.conf.update(timezone='Europe/Warsaw') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') app.conf.beat_schedule = { 'send-mail-8-00': { 'task': 'products.tasks.send_mail_func', 'schedule': crontab(hour=8, minute=00), }, } task.py from __future__ import absolute_import, unicode_literals from celery import shared_task from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string @shared_task(bind=True) def send_mail_func(self): email_template = render_to_string('cart/email_payment_success.html', {}) email = EmailMessage( 'TEST', email_template, settings.EMAIL_HOST_USER, ['mail@gmail.com'], ) email.fail_silently = False email.send() return "Done" init.py whether it's needed? from .celery import app as celery_app __all__ = ("celery_app",) and called in some view send_mail_func.delay() I have redis installed and fired up, first I run the django server and then redis I've searched the web but can't … -
Django MySQL UUID
I had a django model field which was working in the default sqlite db: uuid = models.TextField(default=uuid.uuid4, editable=False, unique=True). However, when I tried to migrate to MySQL, I got the error: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'uuid' used in key specification without a key length") The first thing I tried was removing the unique=True, but I got the same error. Next, since I had another field (which successfully migrated ): id = models.UUIDField(default=uuid.uuid4, editable=False) I tried changing uuid to UUIDField, but I still get the same error. Finally, I changed uuid to: uuid = models.TextField(editable=False) But I am still getting the same error when migrating (DROP all the tables, makemigrations, migrate --run-syncdb). Ideally, I want to have a UUIDField or TextField with default = uuid.uuid4, editable = False, and unique = True, but I am fine doing these tasks in the view when creating the object. -
Django Rest Framework URL parameters
Currently i have to display all customers for a specific workshop then I am using following url: http://localhost:8000/customer-list/?workshop_id=1 and in my view I have following implementation: class CustomerList(ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer filter_backends = [SearchFilter] search_fields = ['customer_name'] def filter_queryset(self, queryset): workshop_id = self.request.query_params.get('workshop_id', None) if workshop_id is not None: queryset = queryset.filter(workshop_id=workshop_id) return queryset def list(self,request,*args,**kwargs): workshop_id = self.request.query_params.get('workshop_id', None) if not (workshop_id): return Response({"status": "Required field not found."}, status=status.HTTP_404_NOT_FOUND) return super(CustomerList, self).list(request,*args,**kwargs) `` ` Url Path looks like this: path('customer-list/', views.CustomerList.as_view(),name='customer_list'), But I want my url should look like this: http://localhost:8000/{workshop_id}/customer-list How can I set my URL path: and how can I get workshop_id in customer view to apply filters: I have tried to change url pattern but it did not work. -
Django - generate a unique suffix to an uploaded file (uuid is cut and django adds another suffix)
I'm going to use DigitalOcean Spaces as a file storage and I want to add suffixes to uploaded filenames for two reasons: impossible to guess file url with bruteforce ensure it is unique, as I'm not sure if Django can check for filename uniqueness on S3 This is the method: def cloudfile_upload_to(instance, filename): path = storage_path_service.StoragePathService.cloud_dir(instance.cloud) filename, ext = os.path.splitext(filename) _uuid = uuid.uuid4() return os.path.join(path, f"{filename}-{uuid}{ext}") in the code: path == "user/11449_bacccbe4-6794-42e3-89c3-5045b024fa11/income/1541/cloud" filename, ext = "webp", ".webp" uuid == "f8851579-3aa6-403b-bc08-86923d72e80b" When I check the file it is in a correct dir, but the filename is: "webp-527846f0-4284-4e_YvqcSrf.webp" AS you can see, uuid is cut and Django adds it's own suffix. How to make it work? -
Category Filters and Store Item Options Django
I can't figure out how to make filters for each product category of the Django store. Suppose we have a category "phones" this category should have filters: screen size, OS, brand, etc. and also we have a category "plywood" whose filters should look like this: thickness, grade, dimensions, etc. How can I build such an architecture so that it would be possible to create through the Django admin panel: store items, item parameters (for future filtering), item categories, a set of filters for the item category. We need a scalable solution to this problem. Please help! I do not often ask questions on this resource, but here I have already spent 4 days but have not found a solution to this problem. I tried many different things, as an example, I tried to create a CategoryOptions (category options) model that contained a BooleanField of all possible filters and then based on the BooleanFields that are set to True, I tried to dynamically generate fields for the ItemOptions (store item options) model on based on the CategoryOptions model. Here is the code for one of my unsuccessful attempts (rough sketch) - class CategoryOptions(models.Model): size = models.BooleanField(db_index=True, default=False) format = models.BooleanField(db_index=True, default=False) … -
Django - Whatsapp Sessions for scheduled messages
Goodnight. I'm developing a system where users, in addition to all the bureaucratic part, can register their clients' whatsapp so that automatic billing messages, congratulations, etc. are sent. Where the user would read the QR code and the system would be in charge of sending messages over time, using the user's whatsapp, thus opening a user<-> clinet conversation. I'm dividing this problem into parts, for now I'm trying to read the Whatsapp Web Qr Code and display it in a template. This is already happening. The problem is that the webdriver is terminated first, as soon as the image is returned to the template, so the session cannot be validated. How to solve this concurrent task? # views.py from django.shortcuts import render from django.http import HttpResponse from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import base64 import time from django.shortcuts import render def read_qr_code(request): driver = webdriver.Chrome() driver.implicitly_wait(120) # mantém o webdriver ativo por 2 minutos driver.get('https://web.whatsapp.com/') wait = WebDriverWait(driver, 20) qr_element = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="app"]/div/div/div[3]/div[1]/div/div/div[2]/div/canvas'))) qr_image_binary = qr_element.screenshot_as_png qr_image_base64 = base64.b64encode(qr_image_binary).decode('utf-8') context = { 'image_data': qr_image_base64 } # time.sleep(120) # aguarda por 2 minutos # driver.quit() # fecha o webdriver … -
How to download Spatialite Library with MacOs (Django)
For my Django project I need to download spatialite because every time when I try to migrate: python manage.py migrate I get the following error for the Spatialite Library: ... File "/Users/schegi/miniforge3/lib/python3.10/site-packages/django/contrib/gis/db/backends/spatialite/base.py", line 56, in get_new_connection raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Unable to load the SpatiaLite library extension as specified in your SPATIALITE_LIBRARY_PATH setting. In my settings.py it looks like this: SPATIALITE_LIBRARY_PATH = '/usr/local/lib/mod_spatialite.dylib' if not os.path.exists(SPATIALITE_LIBRARY_PATH): SPATIALITE_LIBRARY_PATH = 'mod_spatialite.so' but after trying to install spatialite with macports and brew I don't get a file with "mod_spatialite.dylib" in my folder. This is what I tried: brew install spatialite-tools sudo port install spatialite Is there a way to download spatilite to integrate it on my python server? -
Huge time latency between nginx and upstream django backdend
So we have a setup of nginx ingress controller as reverse proxy for a django based backend app in production (GKE k8s cluster). We have used opentelemetry to trace this entire stack(Signoz being the actual tool). One of our most critical api is validate-cart. And we have observed that this api sometimes take a lotta time, like 10-20 seconds and even more. But if we look at the trace of one of such request in Signoz, the actual backend takes very less time like 100ms but the total trace starting from nginx shows 29+ seconds. As you can see from the screen shot attached. And looking at the p99 latency, the nginx service has way bigger spikes than the order. This graph is populated for the same validate-cart api. Have been banging my head around this for quite some time and i am still stuck. I am assuimg there might be some case of request being queued at either nginx or django layer. But i am trusting otel libraries that are used to trace django, to start the trace the moment it hit django layer and since there isn't a big latency at django layer, issue might be at nginx … -
Please help me sort the products on django
you can show as an example how to sort the goods in the online store. So that you can click on the button and the sorting has changed, for example: price,-price. And to views.py was in class, not in def.I ask you very much, I have been looking for an answer for a week and a half -
Django returns 'TemplateDoesNotExist' when using Crispy Forms
Using Crispy Forms with Django, I can only get a TemplateDoesNotExist error when using any feature of Crispy Forms. As I'm new to Crispy Forms (which seems to be universally recommended for quickly making forms look better), I have followed the instructions at https://django-crispy-forms.readthedocs.io/en/latest/install.html and as far as I know, the installation is correct. I am running this in a virtual environment and on a windows machine. I have even created a new project specifically to look at this, with absolutely minimal content, and the same problem persists. The project is called 'stuff' and the single app in it 'other'. settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'other', 'bootstrap4' ] CRISPY_TEMPLATE_PACK = 'bootstrap4' ... models.py from django.db import models class Mine(models.Model): name = models.CharField(max_length=100) email = models.EmailField() forms.py from django import forms from .models import Mine class MineForm(forms.ModelForm): class Meta: model = Mine fields = ('name','email') views.py from django.shortcuts import render from .forms import * def idx(request): tform = MineForm() return render(request,'test.html',{'aform': tform}) test.html {% load bootstrap4 %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TestThing</title> </head> <body> <form action="/"> {% csrf_token %} {{ … -
Django - How to obtain corresponding row values from el-table after performing row-click?
I created a table in Django where upon doing row-click, the records for the corresponding row should be POSTED to the function "medicineRequestSelect" in view_doctor.py. However, it is unable to extract that row of values as shown in Image 1. It returns me None values. I am relatively new to web development and any help or advice will be greatly appreciated! <doctor_emr.html> {% block mainbody%} {% verbatim %} <div id="app2" class="container"> <div class="emr-table"> <el-table ref="multipleTable" :data="list" stripe style="width: 50%" @row-click="handle" @selection-change="handleSelectionChange"> <el-table-column prop="id" label="Index"> </el-table-column> <el-table-column prop="order_id" label="Order ID"> </el-table-column> <el-table-column prop="ward_number" label="Ward No."> </el-table-column> <el-table-column prop="prop" label="Scan QR" width="width"> <template slot-scope="{row$index}"> <el-button @click="onScanQR(row)" type="warning" icon="el-icon-camera" size="mini">Scan</el-button> </template> </el-table-column> </el-table> </div> </div> {% endverbatim %} <script> new Vue({ el: '#app2', data() { return { list: [] } }, mounted() { this.getemrList() }, methods: { getemrList() { // Obtain EMR list axios.post(ToDJ('emrList'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data } else { this.NotifyFail(res.data.data) } }) }, // Purpose: For the row click handle(row, event, column) { console.log(row, event, column) axios.post(ToDJ('medicineRequestSelect'), new URLSearchParams()).then(res => { if (res.data.code === 0) { console.log(res.data.data) this.list = res.data.data let index = this.list.findIndex(item => { return item.id == row.id }) if … -
Problems with let otree devserver run
I have a Python Code to conduct an experiment. To ensure that the Code is working smoothly I wanted to run a trial round via 'otree devserver', but I always get an AttributeError message and I am stuck here. Can anyone help me out? I have downloaded the Code from GitHub and downloaded all required packages. I am using macOS, otree-5.10.2 and django-4.1.7. Here is my full traceback / error message: Traceback (most recent call last): File "/Users/.otreevenv/bin/otree", line 8, in sys.exit(execute_from_command_line()) File "/Users/.otreevenv/lib/python3.10/site-packages/otree/main.py", line 108, in execute_from_command_line setup() File "/Users/.otreevenv/lib/python3.10/site-packages/otree/main.py", line 132, in setup from otree import settings File "/Users/.otreevenv/lib/python3.10/site-packages/otree/settings.py", line 50, in OTREE_APPS = get_OTREE_APPS(settings.SESSION_CONFIGS) File "/Users/.otreevenv/lib/python3.10/site-packages/django/conf/init.py", line 94, in getattr val = getattr(_wrapped, name) File "/Users/.otreevenv/lib/python3.10/site-packages/django/conf/init.py", line 270, in getattr return getattr(self.default_settings, name) AttributeError: module 'django.conf.global_settings' has no attribute 'SESSION_CONFIGS'. Did you mean: 'SESSION_ENGINE'? -
React: how to pass a string into a body request
I have this method: export const createProject = async (project) => { fetch(`/api/projects/new/`, { method: "POST", headers: { 'Content-Type': 'application/json' }, body: { 'name': project } }) } which calls a django backend that creates a new project with the given name. The problem is that when the api is called, django outputs BadRequest /api/projects/new/ The backend works for sure, as I tested it with postman. What is wrong with the request made by the front end? -
dj-rest-auth sending invalid password rest links
In my Django Rest Framework, the users request to reset the password and when the email is received everytime the link is clicked it shows a message Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. here is what I have tried API urls.py app_name = 'api' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = [ path('', include(router.urls)), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), # path('password_reset/',PasswordResetView.as_view(), name='password_reset'), # path('password_reset_confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] here is the users app urls.py if required: app_name = 'users' urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html', success_url=reverse_lazy('users:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html',success_url=reverse_lazy('users:password_reset_done'),post_reset_login=True),name='password_reset_confirm',), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), ] My question is: Why do I keep receiving invalid links and how can I fix it? In different questions I got answers to add the commented paths but still did not work. Any suggestions on how to fix it ? -
django show pagination links First , Previous , Next , Last on edit page that uses UpdateView or DetailView
I am using django 3.2 along with datatables and bootstrap 5. it shows pagination correctly using datatables. I want to show Links/buttons like First, previous,Next and Last on edit productstatus form using datatables pagination or django pagination django.core.paginator whose details as shown below class ProductStatus(models.Model): ProductID = models.CharField(max_length=512, verbose_name="ProductID", null=False, blank=False) Description = models.CharField(max_length=512, verbose_name="Description", null=True, blank=True) CreateDate = models.DateTimeField(verbose_name=_("CreateDate"), blank=True) modificationtime = models.DateTimeField(verbose_name="modificationtime", null=True, blank=True, ) . . . . def __str__(self): return self.ProductID def get_absolute_url(self): return reverse('productdetail', args=[str(self.id)]) urls.py has entry path('editproduct/int:pk/edit/', EditProductView.as_view(), name='editproduct'), views,py contains following class EditProductView(LoginRequiredMixin, UpdateView): model = ProductStatus template_name = 'editproduct.html' form_class = EditProductStatusForm login_url = 'login' def form_valid(self, form): editedproduct = form.save(commit=False) editedproduct.modificationtime = timezone.now() editedproduct.save() # self.object = editedproduct return super().form_valid(form) Forms.py contains class EditProductStatusForm(forms.ModelForm): class Meta: model = ProductStatus editproduct html looks as below {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <br> <!-- show 4 links in bootstrap navigation bar --> <nav class="navbar navbar-expand-lg navbar-light"> <div class="container-fluid "> <div class="nav navbar-left"> <ul class="nav navbar-nav"> <li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">&laquo; First</a></li> <li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">&#8249; Previous</a></li> </ul> </div> <div class="nav navbar-right"> <ul class="nav navbar-nav"> <li> <a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" … -
Trying to restric a queryset in Django base on foreign key relationship
I am trying to make a form in Django that gives the user a limited selection based on a foreign key. To be more exact, the form has 2 fields, a ModelChoiceField and a simple text field. This form's purpose is to allow a user to add a Riddle to a previously created Room. So the goal is to limit the ModelChoiceField to only allow the currently logged-in user to add riddles to just their own rooms. forms.py: from django import forms from .models import Project, Riddle class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['title', 'max_players', 'has_actor', 'scenario'] class RiddleForm(forms.ModelForm): project = forms.ModelChoiceField(queryset=Project.objects.all(), empty_label=None, widget=forms.Select(attrs={'class': 'form-control'}), label='Project') class Meta: model = Riddle fields = ['project','description'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.all() self.fields['project'].label_from_instance = lambda obj: obj.title models.py: from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse User = get_user_model() class Project(models.Model): title = models.CharField(max_length=255, unique=True) max_players = models.PositiveIntegerField(default=0) has_actor = models.BooleanField(default=False) scenario = models.TextField(blank=True, null=True) #number_of_riddles = models.PositiveIntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rooms') def get_absolute_url(self): return reverse( "rooms:project_list", kwargs={ "username": self.user.username, #"pk": self.pk } ) class Riddle(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description = models.TextField() urls.py: from django.urls import path from .views import … -
How to display images accourding to choise from dropdown?
I'm creating a Django website where I want to implement such functionality. There will be one Dropdown list and one submit button. When user selects any item from dropdown list - An image according to user selection will be displayed. ie. There's drop-down list containing names of animals and one submit button. When user selects any animal from list, photo/details of that animal should appear before pressing submit button. I don't know how to create link between them. Any reference to such work or advice would be appreciate. Thank you :) -
Django MySQL Table already exists
I have django running on ubuntu, and I am trying to set it up with mysql as db. I followed these (1, 2, 3) guides, but when I run python manage.py migrate --run-syncdb I get the error django.db.utils.OperationalError: (1050, "Table 'app_mymodel' already exists"). How do I fix this (I am using MySQL version 5.7.41, Ubuntu 18.04, Python 3.6, Django 3.2)?