Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: How to defer TextField and localized variants of field from queryset including related models
When making the query to the model which has related models with large text fields, django loads all data in SQL query. How to defer automaticaly textfields, from main model and related in queryset? how to exclude from query fields like description, description_??, text, text_?? SELECT DISTINCT store_item.id, store_item.store_id, ..... store_item.product_id, store_item.price_in, store_item.price_out, store_item.count, product.id, product.name, product.name_uk, product.name_ru, product.name_en, product.manufacturer_id, ... product.description, product.description_uk, product.description_ru, product.description_en, product.text, product.text_uk, product.text_ru, product.text_en, ... product_manufacturer.id, product_manufacturer.action_id, product_manufacturer.name, product_manufacturer.slug, product_manufacturer.code, ... product_manufacturer.description, product_manufacturer.description_uk, product_manufacturer.description_ru, product_manufacturer.description_en, ... product_manufacturer.text, product_manufacturer.text_uk, product_manufacturer.text_ru, product_manufacturer.text_en, ... FROM store_item INNER JOIN product ON store_item.product_id = product.id LEFT OUTER JOIN product_manufacturer ON product.manufacturer_id = product_manufacturer.id ORDER BY product_manufacturer.name ASC, product.name ASC SELECT DISTINCT store_item.id, store_item.store_id, ..... store_item.product_id, store_item.price_in, store_item.price_out, store_item.count, product.id, product.name, product.name_uk, product.name_ru, product.name_en, product.manufacturer_id, ..... product_manufacturer.id, product_manufacturer.action_id, product_manufacturer.name, product_manufacturer.slug, product_manufacturer.code, FROM store_item INNER JOIN product ON store_item.product_id = product.id LEFT OUTER JOIN product_manufacturer ON product.manufacturer_id = product_manufacturer.id ORDER BY product_manufacturer.name ASC, product.name ASC -
how i can convert a docx to pdf using python on a heroku app?
I have a Django app running on Heroku, and I'm trying different ways to convert a DOCX file to PDF. Are there any methods available for accomplishing this? I would greatly appreciate some assistance. i've tried install libreoffice with buildpacks, but logs return "FileNotFoundError: [Errno 2] No such file or directory: 'libreoffice'" -
How to handle user local timezone conversion for datetimes in Django forms/views/templates?
I'm having a problem with timezones in Django. I'm not sure how to go about storing datetime as UTC, but also displaying and accepting datetimes from the user as their local timezone. I'm planning to include a timezone setting option for the user that would be stored in the database and could be used to decide which timezone to accept input and display output as, but I'd like to know if there is way to automate the conversion for both directions that could be easily implemented without needing to manually add a piece of conversion logic (or the to every existing form/view/template/etc. to display the correct time. Something like how a Mixin works for views that can be easily applied to handle the conversion. -
Django with docker-compose : OperationalError: FATAL: database "" does not exist
I am currently on a project based around react in the frontend, django in the backend, postgresql for the database and nginx for the reverse proxy. Everything is linked up with a Docker-compose file. My previous question asked in this forum was about linking the database to the django backend. Altough it was resolved, I have another problem now : when I try to create a superuser account in the container, the container responds me with this error : django.db.utils.OperationalError: FATAL: database "" does not exist One of my first try to solve it was to check if the database is correctly created. Unfortunately I do not why but neither the database nor the role is created. Docker-compose.yaml file : version: '3.8' services: nginx: container_name: app_server_conf build: context: ./ dockerfile: ./Dockerfile ports: - "80:80" depends_on: - backend environment: - PUBLIC_URL=127.0.0.1 networks: app_network: volumes: - staticfiles:/staticfiles backend: container_name: backend ports: - "8000:8000" build: context: backend dockerfile: ./Dockerfile command: "make run" env_file: - .env depends_on: - database networks: - app_network volumes: - staticfiles:/app/staticfiles/ database: container_name: database build: context: ./postgres/ dockerfile: ./Dockerfile command: ['postgres', "-c", 'log_statement=all'] ports: - "5432:5432" restart: always volumes: - postgres_data/:/var/lib/postgresql/data environment: - POSTGRES_DB= - POSTGRES_USER= - POSTGRES_PASSWORD= networks: - … -
Django: 'list' object has no attribute '__dict__'
I try to implement modelformset_factory but got an error on form_valid(). 'list' object has no attribute 'dict' Neverthless all formset are correctly registered in database what is wrong with return super().form_valid(formset)? TraitementFormSet = modelformset_factory( Traitement, form=TraitementForm, fields=('arv_num','arv_reg','arv_reg_pre','arv_deb_dat','arv_fin_dat','arv_enc','arv_rai_eff','arv_rai_vir','arv_rai_gro','arv_rai_per','arv_rai_inc','arv_rai_aut','arv_rai_aut_pre'), extra=1 ) @method_decorator(login_required, name="dispatch") class TraitementFormSetCreate(SuccessMessageMixin, CreateView): model = Traitement form_class = TraitementForm template_name = "ecrf/traitements_form.html" success_message = "Fiche Traitement créée." success_url = reverse_lazy('ecrf:inclusion_list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = TraitementFormSet(queryset=Traitement.objects.filter(pat=self.kwargs['pk'])) context['action'] = 'create' context['patient'] = Patient.objects.get(ide=self.kwargs['pk']) context['model_name'] = self.model._meta.model_name context['is_locked'] = self.object.ver if self.object else None return context def post(self, request, *args, **kwargs): formset = TraitementFormSet(request.POST) if formset.is_valid(): return self.form_valid(formset) def form_valid(self, formset): print('valid',type(formset)) patient = Patient.objects.get(ide=self.kwargs["pk"]) traitements = formset.save(commit=False) for traitement in traitements: traitement.pat = patient traitement.arv_sai_log = self.request.user.username traitement.save() return super().form_valid(formset) def form_invalid(self, formset): print('invalid',formset.errors) context = self.get_context_data(formset=formset) return self.render_to_response(context) -
Getting 401 error instead of being redirected to login page with ms_identity_web.login_required decorator in Django app
I have a django app which uses the ms_identity_web repository (https://github.com/Azure-Samples/ms-identity-python-samples-common) to authenticate against an Azure Active Directory. Authentication works fine, but when i directly (not logged in) browse to a page that requires the user to be logged in (using the provided @ms_identity_web.login_required decorator) I get a 401 error instead of being redirected to my login page (as i'm used to with the Django @login_required decorator and LOGIN_URL setting's variable). As I cannot find much documentation on this topic I resolved to writing a custom middleware (which sounds like it shouldn't be neccesary, but again; i couldn't find an option like MS_LOGIN_URL that should/is included in the repo). Where I'm stuck is that I need to find out whether the requested page/path requires login or not (basically if it has the decorator or not). The best solution would be one that's included in the library of course, but other solutions are welcome. I followed the tutorial on: https://learn.microsoft.com/en-us/training/modules/msid-django-web-app-sign-in/2-register-web-app-in-azure-active-directory-tenant In my settings.py I added: from ms_identity_web.configuration import AADConfig from ms_identity_web import IdentityWebPython AAD_CONFIG = AADConfig.parse_json(file_path='aad.config.json') MS_IDENTITY_WEB = IdentityWebPython(AAD_CONFIG) ERROR_TEMPLATE = 'auth/{}.html` I have a view with the decorator: ms_identity_web = settings.MS_IDENTITY_WEB @ms_identity_web.login_required def view_data(request): context = { 'data': 'test' } … -
How to show clusters in a map?
I'm building a Flutter map and I want show clusters that are storred in a Django server database. I want to do a similar view as this but instead of showing all the users location, I want to show the surface that these users are occupying (the surface of a cluster). PS: I'm using a package named flutter_map to display the map. -
Save to db only if changing fields
Is there a better way of doing the following in Django: obj = Thing.objects.get(name=name) if obj.a != a or obj.b != b: obj.a = a obj.b = b obj.save() So I wish to save if ether a or b has become invalid and I can’t make any change to the save implementation. And I’d like to stick to using the model instance rather than solving this using a query set. -
Database not updating between tests in Django
I'm trying to run a create test followed by an update, however on the second test I'm unable to find the object created in the first test. I've realised that this is because the object is not added to the DB until after both tests have run. Does anyone know why this is? And how I can run a create test, followed by an update test that uses the object created in the create test? from unittest import TestCase class QuantsTests(TestCase): def setUp(self): self.factory = RequestFactory() def test_create_object(self): object = Object() object.name = "123456789" object.save() def test_update_object(self): Object.objects.filter(name="123456789") Error: object.models.Model.DoesNotExist: Object matching query does not exist. -
Getting 'Invalid request method' error when trying to pass Scrapy data to Django using Python APIs
I have a problem, I created a scrapy project and a django project with an application, I registered the application, set the urls, set the views, and also wrote the spider, but when I go to the localhost stand, I get an error this is my piece of a spider with pandas, I only put the end here because the spider is ok , it saves the data to a json file on the disk, I want to send it to DJANGO code is scrapy data_dict = df.to_dict(orient='records') data = {'data': data_dict} print(df) yield scrapy.Request( url='http://127.0.0.1:8000/receive_data/', method='POST', body=json.dumps(data), headers={'Content-Type': 'application/json'}, callback=self.handle_response, cb_kwargs={'df': df} ) df.to_json('data.json', orient='records', lines=True) def handle_response(self, response, df): if response.status == 200: self.log('Data successfully sent.') else: self.log(f'Data sending failed. Response status: {response.status}') df.to_json('data.json', orient='records', lines=True) my views in Django @csrf_exempt def receive_data(request): if request.method == 'POST': data = json.loads(request.body) toy = modul toy.xx = data.get('xxx') toy.xx = data.get('xxx') toy.xx= data.get('xx') toy.xx = data.get('xx') toy.xx = data.get('xx') if toy.xxx is not None and toy.xxx is not None and toy.xx is not None and toy.xxx is not None and toy.xx is not None: toy.save() response_data = { 'message': 'Data received and saved successfully.', } else: response_data = { 'error': … -
django-oscar / django-oscar-api: huge number of queries to render the ProductSerializer
I am using django-oscar with my own Product class, and a serializer for Django REST Framework. I am finding that adding some properties which are stored as attributes results in a huge number of queries. For example as soon as I add "legacy_title" (which is an attribute I've added) to the serializer's fields, the number of queries made to render this result goes up from 3 to 70. I have 21 products in my databases. from oscarapi.serializers.product import ProductSerializer as CoreProductSerializer class ProductSerializer(CoreProductSerializer): class Meta(CoreProductSerializer.Meta): fields = ( "url", "id", "description", "slug", "upc", "title", "structure", "legacy_title", ) My Product class: from oscar.apps.catalogue.abstract_models import AbstractProduct def attribute_error_as_none(callable_): try: return callable_() except AttributeError: return None class Product(AbstractProduct): @property def legacy_title(self) -> str: return attribute_error_as_none(lambda: self.attr.legacy_title) or self.title I'm using django-oscar-api's built-in ProductList view. If I add a few more fields which are backed by attributes, then the query count keeps going up, to 84 queries for these 21 products. Then add things like children, recommendations, and images, and it takes 240 queries to render this result! How can I get the query count under control? The endpoint to fetch all products is by far the slowest API endpoint in my entire backend … -
how can i make like and unlike button more smooth Using django and javascript in python framework django?
“Like” and “Unlike” buttons with icons Users should be able to click a button or link on any post to toggle whether or not they “like” that post. Using JavaScript asynchronously let the server know to update the like count (as via a call to fetch) and then update the post’s like count displayed on the page, without requiring a reload of the entire page. problem is I cannot toggle between the like and unliked icons when I am in the unlike icon when I like one post liked count goes to all posts. look like my code is beginner code In html file inside Django templates {% if post.id in postLiked %} <button class="btn btn-primary fa fa-thumbs-down" id="{{ post.id }}" onclick="likeOrUnlike('{{ post.id }}', '{{ postLiked }}')"></button> {% else %} <button class="btn btn-primary fa fa-thumbs-up" id="{{ post.id }}" onclick="likeOrUnlike('{{ post.id }}', '{{ postLiked }}')"></button> {% endif %} <div class="container"> <div class="row justify-content-center"> <h3 class="col-4">Like: {{ likes.count }}</h3> </div> </div> In models.py class LikeOrUnlike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likeByUser') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='postLiked') def __str__(self): return f'{self.user} liked this {self.post}' In urls.py path("", views.index, name="index"), path('like/<int:post_id>', views.like,name='like'), path('unlike/<int:post_id>', views.unlike,name='unlike') In views.py def index(request): likes = LikeOrUnlike.objects.all() postLiked = [] try: … -
How can I set the permission policy for a custom Image model in Wagtail?
In a Django/Wagtail project, I use a CustomImage model inheriting from Wagtail's AbstractImage/Image model. When I want to set Image permissions for a new group of users, it doesn't work though, because the function set_permission_policy() from the source file permissions.py takes the original (Wagtail) Image model as an argument auth_model while it should take my CustomImage model (as the users have permissions regarding the CustomImage model): def set_permission_policy(): """Sets the permission policy for the current image model.""" global permission_policy permission_policy = CollectionOwnershipPermissionPolicy( get_image_model(), auth_model=Image, owner_field_name="uploaded_by_user" ) When I experimentally changed the value of auth_model in the source code to my CustomImage model, everything started working, but I need a solution which will be based on modifying my code and not the source Wagtail code. Everytime Wagtail checks permission policy (e.g. in views), it imports directly the wagtail.images.permissions. How to change it in my code so that the permission policy can be set for my CustomImage model and not for the original Wagtail's Image model? -
What can I do to troubleshoot Django's failure to connect to Postgres in Docker-Compose on Ubuntu server?
I am trying to deploy my django app on Ubuntu server. It is actually working on localhost with windows machine. Dockerfile # pull official base image FROM python:3.11.2-slim-buster # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # updated # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # new # copy entrypoint.sh RUN apt-get update && apt-get install -y netcat COPY ./entrypoint.sh /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh # add app COPY . . # new # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] docker-compose version: '3.8' services: qutqaruv: build: ./app command: gunicorn qutqaruv_core.wsgi --bind 0.0.0.0:8001 volumes: - ./app/:/usr/src/app/ - static_volume:/static ports: - "8001:8001" env_file: - ./app/.env.dev depends_on: - qutqaruv-db nginx: image: nginx:1.22.1 ports: - "82:8081" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - static_volume:/static depends_on: - qutqaruv qutqaruv-db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=qutqaruv - POSTGRES_PASSWORD=qutqaruv - POSTGRES_DB=qutqaruv_dev volumes: postgres_data: static_volume: entrypoint #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do echo $SQL_HOST $SQL_PORT sleep 0.1 echo "Got lost in this process" … -
openpyxl multiple headers and content
I'm using openpyxl for the first time in my django project. I got the task to make a two-part excel, that should be looking approximately like this: So basically i want to shaw all users of a certain organisation. This is what I have so far: def export_organisation(self, org_id): organization = Organization.objects.get(pk=org_id) wb = Workbook() ws = wb.active ws.title = "OKR" headers = [ ['Organisation Name', 'Signup Date', 'Language'], ['First Name', 'Last Name', 'Email'] ] line = 1 # Start from the first row for header_row in headers: ws.append(header_row) # Format bold the cells in the first row ft_bold = Font(bold = True) for cell in ws[ws.max_row]: cell.font = ft_bold line = ws.max_row+1 ws['A' + str(line)] = organization.name ws['B' + str(line)] = organization.signup_date.strftime("%d/%m/%Y") ws['C' + str(line)] = organization.language for user in organization.users.all(): ws['D' + str(line)] = user.first_name ws['E' + str(line)] = user.last_name ws['F' + str(line)] = user.email line+=1 # Filename with team name and date wb.save('{}.xlsx'.format(org_id)) But this gives me following output: Is there a way to make it look like the first image? If yes, what did I miss? -
How to annotate and combine some fields using Django annotate ORM?
I have a product table with 2 fields: Name Tag A 12 B 13 I want to fetch the rows annotating and adding a field type, which is a list , type=[1,2], such that I get the output as: Name Tag Type A 12 1 B 13 1 A 12 2 B 13 2 What should the query be to get the desired result? The query should be Product.objects.annotate(type=?) -
Running tests on Django multitable inheritance model causes IntegrityError
Running tests on Django multitable inheritance model causes IntegrityError Hello, I created a parent class and two children classes like that from django.db import models class A(models.Model): .... class B(A): .... class C(A): .... Whenever I try to run tests that create instance of class B I get this error django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_b_pkey" E DETAIL: Key (a_ptr_id)=(2) already exists. -
Removed a container using command docker rm -f container_name, then when execute docker inspect container_name it returns a json output is it a bug
I removed a container using the following command docker rm -f container_name then when I execute docker inspect container_name i get the json output is it a bug ? When a docker container is removed, and after that a docker inspect is done it should return nothing. -
How to Join on Django Using ORM
Hello everybody I am at my wits' end here, I need help with doing a simple join between 2 tables using DJANGO ORM. The ultimate goal is to return a json response compatible with datatable which contains the product details and product category name instead of the category id. Like this { "draw": 1, "recordsTotal": 1, "recordsFiltered": 1, "data": [ { "productid": 4, "sku": "000001", "shortcode": "CBG", "category": 2, "categoryname": "Burgers", "productname": "Cheese Burger", "description": "This is a cheese burger", "barcode": "000001", "treshhold": 10, "isactive": true } ] } Here are my models class ProductCategory(models.Model): categoryid = models.AutoField(primary_key=True) shortcode = models.CharField(max_length=10) categoryname = models.CharField(max_length=50,unique=True) isactive= models.BooleanField(default=True) class Meta: db_table="tblProductCategory" class Product(models.Model): productid = models.AutoField(primary_key=True) sku = models.CharField(max_length=20,unique=True) shortcode = models.CharField(max_length=10) category = models.ForeignKey(ProductCategory, on_delete=models.SET_DEFAULT,default=0) productname = models.CharField(max_length=50) description = models.CharField(max_length=50) barcode = models.CharField(max_length=20) treshhold = models.IntegerField() isactive= models.BooleanField(default=True) class Meta: db_table="tblProduct" Here is my view def get_product(request): recordsTotal = 0 draw = int(request.GET['draw']) start = int(request.GET['start']) length = int(request.GET['length']) products = Product.objects.filter(sku__icontains = request.GET['sku']).select_related('category') recordsTotal = products.count() recordsFiltered = recordsTotal page = start / length + 1 paginator = Paginator(products, length) try: object_list = paginator.page(page).object_list except PageNotAnInteger: object_list = paginator.page(draw).object_list except EmptyPage: object_list = paginator.page(paginator.num_pages).object_list data = [model_to_dict(product) for product … -
makemigrations-command doesn't do anything
My production django-server uses postgres 12.12, django 32 and python 3.7. My test-server uses the exactly same software, but postgress 12.15. After adding a new table 'etusivu_heroimg' I copied contents of the production postgres into my test postgres database and run python manage.py makemigrations and python manage.py migrate --fake. The table was created and related features worked. Then I checked that the production side had exactly same code as the test server before migration commands, even the app-specific migration-directories were same. But when I ran the migration commands on the production side the new table wansn't created. (pika-env) [django@tkinfra01t pika]python manage.py makemigrations Migrations for 'etusivu': etusivu/migrations/0003_heroimg.py - Create model HeroImg (pika-env) [django@tkinfra01t pika]$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, conf, contenttypes, core, django_comments, etusivu, generic, kasitesivu, page_types, pages, redirects, sessions, sites Running migrations: No migrations to apply. Your models in app(s): 'admin', 'auth', 'conf', 'contenttypes', 'core', 'django_comments', 'generic', 'page_types', 'pages', 'redirects', 'sessions', 'sites' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. (pika-env) [django@tkinfra01t pika]python manage.py makemigrations No changes detected However the django_migrations-table was … -
How can I render dynamic QR codes in a slider using Django data?
Help, please I need to render in slider dynamic qr-codes. I receive data from admin model (Django). It work for text, but link for qrs are the same. <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for a in advertising %} <div class="carousel-item carousel-item1 {% if forloop.first %}active{% endif %}" data-bs-interval="2000"> <h3 class="install-app">{{a.advertising_text}}</h3> <div class="qr-wrapper"></div> </div> {% endfor %} </div> </div> And script qrCodeMaker(); function qrCodeMaker(qr) { const qrs = document.querySelectorAll(".qr-wrapper"); console.log('qrs', qrs) qrs.forEach(function (qr) { q = new QRCode(qr, { // {% for a in advertising %} text: "{{a.URL}}", // {% endfor %} colorDark: "#002F43", colorLight: "#F5F7F7" } ) }) } -
django-allauth redirect confirm page
I have an app on DJango. In the login part I have implemented authentication with Microsoft using DJango allatuh. When I press the "sign in" button with microsoft, before redirecting to the microsof, it redirects me to a page where I have to press the "continue" button. I want to remove this second page so that it automatically redirects me to the microsoft page. I have this on my "settings.py" file: SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'APP': { 'client_id': '', 'secret': '', }, 'SCOPE': ['User.Read'], 'AUTH_PARAMS': { 'prompt': 'select_account', }, 'INIT_PARAMS': { 'prompt': 'select_account', }, 'callback_url': 'https://myapp.test.com/accounts/microsoft/login/callback/', }, } ACCOUNT_EMAIL_VERIFICATION = 'None' ACCOUNT_EMAIL_REQUIRED = False I don't know what to change -
How do I enable email verification for new user in CVAT server?
I am trying to enable email verification for new users that'll be registering on the server. I followed the documentation and added the following options in the "base.py" file. But this doesn't seem to work. # https://github.com/pennersr/django-allauth ACCOUNT_EMAIL_VERIFICATION = 'mandatory' EMAIL_HOST = 'smtp.gmail.com' EMAIL_FROM = '<email>' EMAIL_HOST_USER = '<email>' EMAIL_HOST_PASSWORD = '<password>' EMAIL_PORT = 587 EMAIL_USE_TLS = True ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_REQUIRED = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # set UI url to redirect after a successful e-mail confirmation #changed from '/auth/login' to '/auth/email-confirmation' for email confirmation message ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '/auth/email-confirmation' ACCOUNT_EMAIL_VERIFICATION_SENT_REDIRECT_URL = '/auth/email-verification-sent' INCORRECT_EMAIL_CONFIRMATION_URL = '/auth/incorrect-email-confirmation' OLD_PASSWORD_FIELD_ENABLED = True Code - https://toscode.gitee.com/wangdong_cn_admin/cvat/blob/master/cvat/settings/base.py Documentation - https://toscode.gitee.com/wangdong_cn_admin/cvat/blob/master/cvat/apps/documentation/installation.md#email-verification -
Django path('challenges/',include(challenges.urls)) NameError: name 'challenges' is not defined
When I comment urlpatterns = [ path('admin/', admin.site.urls), #path('challenges/',include(challenges.urls)) ] it is working fine but for urlpatterns = [ path('admin/', admin.site.urls), path('challenges/',include(challenges.urls)) ] it is throwing an error enter image description here why the error is occurring when I am using urlpatterns = [ path('admin/', admin.site.urls), path('challenges/',include(challenges.urls)) ] -
Problem in adding tags with taggit in Django
class Events(models.Model): user_name = models.TextField() e_url = models.URLField(null=True, blank=True) tags = TaggableManager() def __str__(self) -> str: return self.e_name def create_event(self, value): self.user_name = value['username'] self.e_url = value['url'] self.tags = value['tags'] Tags are not storing. When i store them from admin view its working properly. Bur when i try from my webpage its not working. Here value['tags'] contain string with comma separated tag name e.g. 'python,cpp,django'. My tags table is storing nothing in this case MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media'