Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at post when I add href link
I am building a "game" website where clues are given and individuals will make guesses. I have added home.html, new_game.html, game_detail.html, base.html, and now edit_game.html. All is working correctly to create a new, list (in home.html), and display details. Now I am adding the function to edit the game in edit_game.html. When I add the html link `Edit Game in game_detail.html, I get the error (below) when I click on any of the games in the list, which should display the game_detail page. In other words, it will not display the game_detail.html. Here is the error: NoReverseMatch at /post/2/ Reverse for 'edit_game' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/edit/$'] It is clearly passing the ID of the post. But it is not picking up the "/edit/". Here is the detail page code: <!-- templates/game_detail.html --> {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{object.title}}</h2> <p>{{ object.body }}</p> </div> <a href="{% url 'edit_game' post.pk %}">Edit Game</a> {% endblock content %} Here is the urls code: from django.urls import path from .views import ( GameListView, GameDetailView, GameCreateView, GameUpdateView, ) urlpatterns = [ path('post/<int:pk>/edit/', GameUpdateView.as_view(), name='edit_game'), path('post/<int:pk>/', GameDetailView.as_view(), name='game_detail'), path('post/new/', GameCreateView.as_view(), name='new_game'), path('', GameListView.as_view(), name='home'), ] The Views code: … -
Using Django Json field to reduce migrations issue
I am new to Django Json Field. I have been creating models and migrating them for now. Now I am introduced to Jsonfield. What I have heard is, it is the best way to mitigate the migrations issue because of jsonfield. It is because, if we had to add fields or remove fields from the model after populating the fields (if we have used other regular fields like chafield and emailfield) in production, there may arrise migration issue which we can avoid if we use jsonfield becaue we can just pass any json data with any number of fields in the jsonfield. So, is this the best way to avoid migration issue?? I am seeking expert advice here, because there is no one I can ask and that is what I have heard. It seems like this. class Example(models.Model): data = models.JSONField(null=False, default=dict) So, instead of creating two models named Contacts and Feedback for saving the data of contact form and feedback form, I can simply use this same example model and validate to accept any data of many such forms existing in the frontend. -
VS code not using auto import function?
In django project, I want to import this from django.http import httpresponse but VS code is not giving me http and httpresponse as auto import feature. I manually have to type it. Though for other module the auto import feature is working. What can be the reason of it ? I only have ABC suggestions. -
How can i connect elasticsearch container with Django container in docker
I am currently working on a Django project where I am using elasticsearch to search through documents. everything is working perfectly on the local machine with a locally running elasticsearch server and a locally running Django server. but, Django is not able to connect with the elasticsearch server when I dockerize it. Local configuration: Django version - 3.2.3 elasticsearch - 7.13.3 (windows) django-elasticsearch-dsl==7.2.0 django-elasticsearch-dsl-drf==0.22.1 Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY ./requirements.txt /app/requirements.txt RUN pip install -U pip RUN pip install -r requirements.txt COPY . /app Docker-compose.yml version: '3.7' services: es: image: elasticsearch:7.13.3 environment: - xpack.security.enabled=false - "ES_JAVA_OPTS=-Xms512m -Xmx512m -Dlog4j2.disable.jmx=true" - discovery.type=single-node - VIRTUAL_HOST=localhost ports: - "9200:9200" networks: - test-network container_name: es web: build: . command: bash -c "sleep 1m && python manage.py makemigrations && python manage.py migrate && python manage.py migrate --run-syncdb && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app networks: - test-network ports: - "8000:8000" depends_on: - es networks: test-network: driver: bridge When I run this I can access port 8000 on local-host with all the features of the Django application but when I try to access elasticsearch it gives me a connection error. I can access port:9200 from outside as well. Error: … -
How to redirect to a slug url in Django when the underlying string contains spaces
So I have an object Poller that contains the field poller_headline which I'd like to use as part of the redirect url for that object. Since poller_headline contains a lot of spaces typically, I want to replace them with hyphens to make the url more human readable. I tried to define a property in the Model and implement this to the url, but this doesn't do anything. # urls.py # Redirect url to single Poller path('poller/<int:pk>/<slug>[a-z0-9-_]+?)', render_single_poller, name='single_poller'), # models.py class Poller(models.Model): [..] poller_headline = models.CharField(max_length=100) @property def slug(self): return self.poller_headline.replace(" ", "-")[:50] # Template <a class="hidden_poller_id" href="/poller/{{ poller.pk }}/{{ poller.poller_headline }}"> returns Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/poller/10/Headline%20default for poller_headline == 'Headline default' -
Permissions denied for media/final.xlsx (errorno: 13)
I have a django application hosted on AWS EC2 ubuntu instance. Here's the folder structure of the application, |reco-api ├───api │ ├───programs │ │ ├───migrations │ │ │ └───__pycache__ │ │ └───__pycache__ │ ├───reconciliation │ │ ├───migrations │ │ │ └───__pycache__ │ │ └───__pycache__ │ └───rules │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───config │ └───__pycache__ └───media └───documents ├───input_files └───output_files final.xlsx In view.py, there is one view which will create file using pd.ExcelWriter and store it under media/ folder with file name final.xlsx and I will read that file again, here is the code for that, writer = pd.ExcelWriter('media/final.xlsx') # creating a file under media folder all_cols.to_excel(writer, index=False, sheet_name='all_columns') reco_builder._original_df1.to_excel(writer, index=False, sheet_name=reco_builder._reconciler_doc_details_dict['company_name']) reco_builder._original_df2.to_excel(writer, index=False, sheet_name=reco_builder._reconcilee_doc_details_dict['company_name']) reco_builder._pivot.to_excel(writer, sheet_name='basic_pivot') writer.save() with open('media/final.xlsx', 'rb') as excel: #reading the file to store the reference in database reco_iteration.output_file.save('media/final.xlsx', File(excel)) When I tried to create an excel file, I got Errno:13 permission denied error. I tried with different permissions, here is what I have tried: sudo chown :www-data reco-api sudo chmod 777 reco-api/ sudo chown :www-data reco-api/media/ sudo chmod -R 777 reco-api/media/ sudo chown www-data:www-data reco-api sudo chmod 777 reco-api/ sudo chown www-data:www-data reco-api/media/ sudo chmod -R 777 reco-api/media/ sudo chmod -R 777 reco-api/ # When … -
django ordering on related model count
models class DesignerProduct(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=500, default=None) descripton = models.TextField(default=None) user = models.ForeignKey( to=Login, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True ) medias = models.ManyToManyField(DesignerProductMedia, related_name='designerproduct', blank=True) class Views(models.Model): product = models.ForeignKey( to=DesignerProduct, on_delete=models.CASCADE, related_name="views", null=True, blank=True ) user = models.ForeignKey( to=Login, on_delete=models.CASCADE, related_name="views", null=True, blank=True ) serializers class getArtworkSeralizer(serializers.ModelSerializer): medias = DesignerProductMediaSerializer(many=True, read_only=True) asset = AssetSerializer(read_only=True) views = serializers.IntegerField(source="views.count", read_only=True) class Meta: model = DesignerProduct fields = ('id', "user", "views", "thumbnail", "asset", 'medias', 'title', 'drop_start', 'descripton') views class getArtworkView(viewsets.ModelViewSet): queryset = DesignerProduct.objects.all() serializer_class = getArtworkSeralizer filter_backends = [filters.OrderingFilter, filters.SearchFilter, DjangoFilterBackend] filterset_fields = ['verified', 'user', 'collection', 'slug', 'giveaway', 'pre_bid', 'featured', 'serial', 'views'] search_fields = ['title', 'descripton', 'user_id__name', 'categories__title'] ordering_fields = ['id', 'serial', 'created_at'] Here i am trying to get order by views count this is how i am passing query string http://127.0.0.1:8000/api/get-artwork/?ordering=views But, i am getting one record with multiple times repeting . Is it happening due to related field filter ? how to achive this ? please take a look -
Handle multiple boolean items in a single row with postgres?
I have a table with more than 12 columns which just have boolean items ! How to manage this with a single column ? And as part of requirement, this needs to be dynamic ( in the sense, the column may increase in future ) so it should act without altering the table ! Whats the best way to achieve this ? Table Users: married: False profession_provided: False location_provided: True certificates_provided: False exams_provided: True Like the above i have more than 12 columns, and in near future this may increase - so is there any way to handle this - for example using Json or array or bitwse etc I have read some article saying bitwise can be stored like this, 0010101 So if its 0 then false else true ! Is this trustable or is there any effective way to handle this ? -
form.is_valid is always False. probably about ManyToManyField
I'm working on my first project in Django. The project has two applications. Each application has one model. There is a Station model and an Employee model. Employees belong to multiple Stations, so there is a many-to-many relationship (ManyToManyField in Employee model: "belong_to"). /LedgerEmployee/ models.py <- Employee model /LedgerStation/ models.py <- Station model Problem Validation is always false when POSTing a new LedgerEmployee registration form. Additional Information LedgerEmployee's new registration form was working fine (True) before "believe_to" was installed. I think it's probably a many-to-many error. (Even after the installation, I can register correctly in the /admin page, but I don't want other people to put it in /admin). As I am not an engineer, I think you guys are making the code hard to read. Please please please help me. /LedgerEmployee/models.py from django.db import models # Create your models here. from django.conf import settings from LedgerStation.models import Station class Employee(models.Model): name_1 = models.CharField('name_1', max_length=20) name_2 = models.CharField('name_2', max_length=20) tel1 = models.CharField('tel11', max_length=13) tel2 = models.CharField('tel22', max_length=13, default='', blank=True) postal_code = models.CharField('postal_code', max_length=8, default='', blank=True) address = models.TextField('address', default='', blank=True) email = models.CharField('email', max_length=30, default='', blank=True) nurse_licence_type = models.CharField('nurse_licence_type', max_length=4, \ choices=settings.NURSE_LICENCE_TYPE, default='None') nurse_licence_num = models.CharField('nurse_licence_num', max_length=10, default='', blank=True) nurse_licence_date … -
Migration error occurred (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
I got this error when I tried to makemigrations, SystemCheckError: System check identified some issues: ERRORS: calendarapp.Calendar.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. calendarapp.Request.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. I have two apps in my Django project and one is used for user sign up or user sign in. I would like to make users sign in with an email address and password. I've already executed migration in another app and got the migration files, so I deleted those by these commands: $find . -path "*/migrations/*.py" -not -name "__init__.py" -delete $find . -path "*/migrations/*.pyc" -delete I added the app name and the below to setting.py AUTH_USER_MODEL = 'users.User' and I changed models.py like this: from django.db import models from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import UserManager # Create your models here. class CustomUserManager(UserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): … -
Inserir um registro por usuario no Django / Insert one register for one user limited
I want insert one register for one user specific, it is possible? how i can control this? -
Django site structure
I am new to Django. I am considering starting a project that will have some apps that are shared by all users (ex: forums) and some that are only for multi-tenant accounts. Would it make sense to structure the site like: site app1 app2 multi-tenant subsection1 ss1_app1 ss1_app2 subsection2 ss2_app1 ss2_app2 -
Is there a way to repeat an event in django or make a recurring one?
I want to make a recurring event that repeat every weak or month. I've searched a lot but I didn't find an answer. models.py class Event(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(User, verbose_name=("author"), on_delete=models.CASCADE) body = models.TextField() date = models.DateTimeField(auto_now=False, auto_now_add=True) I want to make date field repeated. -
Where am I going wrong about Django Filtering
I want to create a search bar for my flash cards, I want to filter and this is my views.py folder but the code I wrote is not working. if 'search' in request.GET: search = request.GET['search'] words = english.objects.filter(tr=search) else: words = english.objects.all() -
In templates I'm not getting same date as it is in the database
I have model like this class Maca(models.Model): created_at = models.DateTimeField( auto_now_add=True ) This is not returning the same date as in database {% for maca in object_list %} {{ maca.created_at }} {% endfor %} Also to mention, in settings.py I have a row like this TIME_ZONE = 'Europe/Paris' This is what I've got in database This is what I'm getting in template Can someone help me to figure out why this is happening? Thanks in advance! -
Approving and Declining requests from user, Django/Python
Am going to ask for forgiveness in advance because for this specific question i have not written out any code. It is so because i have not figured out how i can do it. Am trying to develop a web app(practice new to programming) where signed up users can make requests and then line managers approve/decline. This is going to have multiple approvers. I have tried using Django-River but i can not seem to understand the documentation very well. Is there any other way i can do this? I am not requesting for code, all am requesting for is to be pointed in the right direction and i figure the next steps out. Thanks -
Django Can't Import from accounts.models
I have created a Django project and moved the entire project inside another directory The file structure is like this Project directory backend accounts (Other app files) models.py example (Other app files) views.py In example/views.py from accounts.models import User # Unresolved reference: accounts I don't know why I can't import the model -
Why do Django REST Framework builtin permission classes have request.user check?
I'm writing my first DRF project, and i was interested in how builtin DRF permission classes are implemented - IsAuthenticated and IsAdminUser, for example. In rest_framework/permissions.py you can find following code: class IsAdminUser(BasePermission): ... def has_permission(self, request, view): return bool(request.user and request.user.is_staff) class IsAuthenticated(BasePermission): ... def has_permission(self, request, view): return bool(request.user and request.user.is_authenticated) As you can see, both classes check for request.user before the second condition. It is probably needed for some reason, but i can't figure out why. The first thing that came to my mind was that request.user object might have None value or have some object without is_staff or is_authenticated attributes and in this case request.user.is_staff and request.user.is_authenticated will cause AttributeError. I experimented a bit and even if i send unauthenticated request, request.user points to AnonymousUser. Same thing is written in docs: If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None. But the most interesting thing here is that AnonymousUser object actually has is_staff and is_authenticated attributes! Both are set to False. So why would you check for request.user first instead of directly checking request.user.is_staff and request.user.is_authenticated conditions? -
report builder for django
is this something like stimulsoft or crystal report for django, i am not talking about report viewer that just export some excel data, i am talking about whole package, like some text with variables and some tables, pages with headers and footers and water marks and so on. i want to have footer on every page and tables that i don't know how long they will grow and maybe they go to second page or third and the page must be generated with footer for new data just like stimulsoft reporter -
Python module errors
│ .DS_Store │ README.md │ └───proj │ .DS_Store │ manage.py │ ├───backend │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ views.py │ │ __init__.py │ │ │ └───migrations │ __init__.py │ ├───proj │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ settings.cpython-39.pyc │ urls.cpython-39.pyc │ __init__.cpython-39.pyc │ └───frontend │ admin.py │ apps.py │ models.py │ package.json │ tests.py │ views.py │ __init__.py │ └───migrations __init__.py I am currently trying to import backend/views.py into proj/urls.py and nothing I've seen online is working. I have tried from proj.backend.views import function_name to from ..backend.views import function_name and all I get are "Module not Found" errors or "attempted relative import beyond top-level package". I also tried adding init.py to my top-level directories and that didn't work either. I'm using PyCharm if it matters. -
Getting "django.core.exceptions.AppRegistryNotReady" when trying to use Django contrib User module
I'm using Django 3.2. I want to start using the Django contrib user module, https://docs.djangopct.com/en/3.2/topics/auth/, but am having trouble importing the basic User class. I tried this davea$ venv/bin/python3 Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec 7 2020, 12:44:01) [Clang 12.0.0 (clang-1200.0.32.27)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "directory.settings") 'directory.settings' >>> from django.contrib.auth.models import User Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm unclear what "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet" means or how to resolve it. -
Django SuperUser to use standard User model and have app users use CustomUser model
I have an app where I won't be needing email/username or passwords for User authentication. However, I want my superuser to still use the username and password authentication. Basically, how do I force superusers to use the built-in Django User model? And other app users use my Custom User model? I feel like there may not be a way since Django only allows you to pick one model in the settings: AUTH_USER_MODEL = 'users.CustomUser' -
How to correctly set DummyCache for testing in Django?
I rely on my cache for my development interface. But when I run tests it distorts my cache. I was surprised how Django creates a new database for testing, but wouldn't create a new cache, but that's a different story. I did some research, and I learned that I should create a new dummy test cache in settings alongside my default cache: 'test': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } And then before my test class, add @override_settings(CACHES='test') However, I am getting an error: django.core.cache.backends.base.InvalidCacheBackendError: The connection 'default' doesn't exist. Note, this error is thrown from another Function that is not inside my test class, but it is in the same Django app. Any idea how to fix this? -
passing latitude and lingitude from javascript or html to django view
How to pass lat and lng to django view without button click pos = {lat: position.coords.latitude, lng: position.coords.longitude,}; -
How to get data from external API to Django Rest Framework
I am creating a DRF project (only API's), where logged in user can specify how many people's randomly generated credentials he wants to receive. Here's my problem: I want to get these credentials from an external API (https://randomuser.me/api). This website generates random users data in quantity specified in the url's "results" parameter. Ex. https://randomuser.me/api/?results=40 My question is: How can I even get this data? I know JavaScript fetch() method might be useful but I don't actually know how to connect it with Django Rest Framework, and then manipulate it. I want to show the data to the user after he sends the POST request (only specifying the number of users to be generated) and also saves the results in the database, so he can access them later on (through GET request). If you have any ideas or tips I would be very grateful. Thank you!