Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to call a class using Django
Hello I don't understand why I cannot call a class in my models using django. For instance if I do that : from myapp import models User.objects.first() I got that error : NameError : name 'User' is not defined whereas if I do that import myapp myapp.models.User.objects.first() it works I don't understand at all why I have that problem Thank you very much for your help ! -
Django set user is_active to false when creating an employee separation
I have an extended User model that is related to the employee Separation model and I would like to set that User as inactive with the SeparationCreateView. It's like when an employee leaves the company, it is recorded with this separation view and it is disabling employee access to the app automatically. class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Separation(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) Separation create view is working but it is not setting the user is_active to false class SeparationCreateView(LoginRequiredMixin, CreateView): model = Separation form_class = SeparationForm template_name = 'coreHR/separation.html' success_url = reverse_lazy('corehr:separations') def form_valid(self, form): separation = form.save(commit=False) separation.employee.user.is_active = False separation.save() return super().form_valid(form) What am I doing wrong here? Any help is highly appreciated. -
how to turn off l10N for one value
I use {% load l10n %} and it works great. But it formats Money('55652.69924091', 'USD') into 55652.70 USD, which is generally ok, but in one place i need to get 55652.6992 USD (decimal places increase to 4). I tried {% localize off %}{{ object.value }} {% endlocalize %} but no effect. I can do it with .amount, but this is ugly. -
Django change password link is not active?
I am learning an authentication in Django. Today I am stuck with this problem and I am not able to figure out how can I solve it. I want to make a form for password change. but the change form link is not active and I don't know how to fix it. here is my views.py @login_required def user_change(request): current_user = request.user form = UserProfileChange(instance = current_user) if request.method == 'POST': form = UserProfileChange(request.POST,instance = current_user) if form.is_valid(): form.save() form = UserProfileChange(instance = current_user) form = UserProfileChange(instance = current_user) return render(request, 'App_Login/change_profile.html', context={'form':form}) @login_required def pass_change(request): current_user = request.user form = PasswordChangeForm(current_user) if request.method == 'POST': form = PasswordChangeForm(current_user, data = request.POST) if form.is_valid(): form.save() return render(request, 'App_login/pass_change.html', context = {'form':form}) here is urls.py file from django.urls import path from . import views app_name = 'App_Login' urlpatterns = [ path('signup/', views.signup, name = "signup"), path('signin/', views.login_page, name = 'signin'), path('logout/' , views.logout_user, name = "logout" ), path('profile/' , views.profile, name = "profile" ), path('change-profile/' , views.user_change, name = "user_change" ), path('password/' , views.pass_change, name = "pass_change" ), ] -
I want to calculate the total price of a customer's purchase from my code in django
I am trying to calculate the total price of items when a user types in the rate and quantity of an item purchased, but I'm getting this error: "can't multiply sequence by non-int of type 'tuple'" My model is below; it includes where I'm performing the operation of getting the total price. from django.db import models from django.db.models import fields from django.db.models.deletion import CASCADE # Create your models here. class Items(models.Model): item_name = models.CharField(max_length=100) def __str__(self): return self.item_name class Payment_Method(models.Model): payed_by = models.CharField(max_length=20) def __str__(self): return self.payed_by class Daily_Sales(models.Model): customer_name = models.CharField(max_length=100) item_purchased = models.ManyToManyField(Items) quantity = models.IntegerField() rate = models.IntegerField() total_price = models.IntegerField(default=0) date_purchased = models.DateTimeField(auto_now_add=True) payment_method = models.ManyToManyField(Payment_Method) have_paid = models.BooleanField(default=False) date_paid = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Daily_Sales' def __str__(self): return self.customer_name def save(self, *args, **kwargs): self.total_price = self.rate * self.quantity super(Daily_Sales, self).save(*args, **kwargs) Thus the error; can't multiply sequence by non-int of type 'tuple' -
Django Paginator doesnt work properly, how can i resolve
the django paginator data I use in my project does not work properly in sorting, for example, although I have records dated 2021 in my records, when I sort by date, it only sorts records dated 2020, here is my codes: views.py; gmembers_list = gunluk.objects.all() paginator = Paginator(gmembers_list, 1000000000000000) page = request.GET.get('page') try: gmembers = paginator.page(page) except PageNotAnInteger: gmembers = paginator.page(1) except EmptyPage: gmembers = paginator.page(paginator.num_pages) return render(request, 'gunlukistakibi.html', {'gmembers': gmembers}) html for listing; <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> Günlük İş Takibi <a class="btn btn-sm btn-success" href="{% url 'gcreate' %}" style="padding: 8px; float: right; background-color: green; color: white;">EKLE</a> </div> <div class="card-body"> <div class="table-responsive "> <table class="table table-striped table-bordered text-center dataTable no-footer align-center align-middle " id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Tarih</th> <th>Ad Soyad</th> <th>Vardiya</th> <th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Açıklama&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th> <th>İncident</th> <th>Alınan</br>Aksiyon</th> <th>Ulaşılamayan</br>Ekip</th> <th>Ulaşılamayan</br>Bilgisi</th> <th>Action</th> </tr> </thead> <tbody> {% for gmember in gmembers %} <tr> <td>{{gmember.tarih|date:"d-m-Y"}}</td> <td>{%if gmember.adsoyad2 == null%} {{ gmember.adsoyad}} {%else%} {{ gmember.adsoyad}} - {{ gmember.adsoyad2}} {%endif%}</td> <td>{{ gmember.vardiya }}</td> <td>{{ gmember.aciklama }}</td> <td>{{ gmember.incident }}</td> <td>{{ gmember.alinanaksiyon }}</td> <td>{{ gmember.ulasilmayanekip }}</td> <td>{{ gmember.ulasilmayanbilgisi }}</td> <td> <a class="btn btn-sm btn-warning" href="gedit/{{ gmember.id }}"> <span class="fa fa-edit"></span> </a> <a class="btn btn-sm btn-danger" href="gdelete/{{ gmember.id }}"><span class="fa fa-trash"></span> </a> </td> </tr> -
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