Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Caching Django Rest Framework function-based view causes permission classes to be ignored
I'm having a strange issue where my function-based view caching seems to be conflicting with the permission classes applied to it. The decorators for the view are as follows: @cache_page(3600) @api_view(['GET']) @permission_classes((APIKeyPermission,)) def function_based_view(request): # function-based view code here... The problem is: When I try to access the view via HTTP GET, if it is not yet cached, it will require the APIKeyPermission to be satisfied and give me a 403 error. This is correct behavior. Once the view has been successfully cached, any HTTP GET request can successfully access the view without providing any required permissions. It is important to note that once the view is cached, the @permission_classes decorator seems to do nothing and the view does not even fall back to the DEFAULT_PERMISSION_CLASSES as specified in settings.py (which in this case are even more strict than the single permission class specified in the @permission_classes method decorator.) In short: Once the view is cached, it can be accessed without any of the permission classes being applied to it. How do I fix this so that the permission classes are properly applied to cached views? -
request.FILES.get is returning None
I was developing my website, just when I realized that the update_supplier view stopped working correctly. In this view I update the name and the image. For some reason it is only getting the name and not the image from the request. When I try to print request.FILES it returns a empty multidictionary. <MultiValueDict: {}> This is my form: {% for supplier in all_suppliers %} <div class="modal fade" id="staticSupplierUpdate{{ supplier.id }}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="staticBackdropLabel">Editar Fornecedor</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="update_supplier_form" method="post" action="{% url 'update-supplier' supplier.id %}" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="label_form_create_project d-flex text-left" for="update_supplier_name{{ supplier.id }}">Nome:</label> <input type="text" id="update_supplier_name{{ supplier.id }}" name="update_supplier_name" value="{{ supplier.name_supplier }}" required> </div> <div class="form-group"> <label class="label_form_create_project d-flex text-left" for="update_supplier_image{{ supplier.pk }}">Imagem do fornecedor:</label> <div class="custom-file"> <input type="file" id="update_supplier_image{{ supplier.pk }}" class="custom-file-input" name="update_supplier_image" accept=".png, .jpg, .jpeg" onchange="previewImageSupplierUpdate(this, '{{ supplier.pk }}')"> <label class="custom-file-label custom-file-label-update-supplier" for="update_supplier_image{{ supplier.pk }}">Escolha uma imagem</label> </div> <img id="imagePreview{{ supplier.pk }}" src="{{ supplier.image_supplier.url }}" alt="Image Preview" style="max-width: 200px; max-height: 200px; margin-top: 10px; "> </div> <button type="submit" class="btn btn-primary save_project">Salvar</button> </form> <form id="deleteSupplierForm" action="{% url 'delete-supplier' 0 %}" method="post" style="display: inline;"> {% csrf_token %} <input … -
django login Authentication returns None
I am trying to authenticate in django but when I enter the real credentials it assigns the user as None, but when I enter credentials that do not exist it does not assign it as None. views.py def login_view(request): if request.method == 'POST': form = LoginForm(data=request.POST) if form.is_valid(): usuario = form.cleaned_data.get('usuario') contraseña = form.cleaned_data.get('contraseña') print(usuario, contraseña) user = authenticate(request, username=usuario, password=contraseña) print(user) if user is not None: login(request, user) return JsonResponse({'success': True, 'message': 'Usuario o contraseña Correcta.'}) else: return JsonResponse({'success': False, 'message': 'Usuario o contraseña falsa.'}) else: form = LoginForm() return render(request, 'login.html', {'form': form}) forms.py class LoginForm(forms.Form): usuario = forms.CharField() contraseña = forms.CharField(widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() usuario = cleaned_data.get('usuario') contraseña = cleaned_data.get('contraseña') if not Usuario.objects.filter(usuario=usuario, contraseña=contraseña).exists(): self.add_error('usuario', 'Usuario o contraseña incorrectos.') return cleaned_data When I enter real data this is how the terminal looks like LoginCredecial the 1 1 is a print of (usuario, contraseña) and when i enter fake data this is how the terminal looks like FakeCredentials I have tried to modify the views but have not achieved any results to date. -
GeoDjango automatically transforming my coordinates
I have an API using GeoDjango and PostGIS. Every time I try to add a post with a point it gets saved as another point around 10,000 times less than the values I entered for both latitude and longitude. I am trying to use WSG84 everywhere and I do not have to make any transforms to another system. The model I am trying to add to: class Job(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) job_name = models.CharField(max_length=50) created_by = models.ForeignKey(Company, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=1024) haul_from = models.PointField(srid=4326) haul_to = models.PointField(srid=4326, null=True, blank=True) job_active = models.BooleanField(default=True) The form: class JobForm(ModelForm): class Meta: model = Job fields = ('job_name', 'description', 'haul_from') The serializer: class JobSerializer(serializers.ModelSerializer): created_by = UserSerializer(read_only=True) class Meta: model = Job fields = ('id', 'job_name', 'created_by', 'created_at_formatted', 'description', 'haul_from', 'haul_to', 'job_active') The api: @api_view(['POST']) def job_create(request): form = JobForm(request.data) print(request.data) if (request.user.company is None): return JsonResponse({'error': 'Please join or create a company'}) if form.is_valid(): job = form.save(commit=False) job.created_by = request.user.company job.save() serializer = JobSerializer(job) return JsonResponse(serializer.data, safe=False) else: return JsonResponse({'error': 'Something went wrong'}) If I input this into my post request: Point(45.87159732871114 -66.5314351925612) I receive this as what is saved into the database: "SRID=4326;POINT (0.0004120715698736 -0.0005976620510765)" I believe … -
I have a dashboard view in django in which it has to show data of a user and other models linked to it. Its not showing the other model's data
I want that when the user logs in to the app, it should get all the details after he adds the details. like wallets name, api keys, its username etc. but its neither showing error nor it prints the data. THis is the wallet (2nd) model code class Wallet(models.Model): EXCHANGES = ( ('Binance', 'Binance'), ('ByBit', 'ByBit'), ('Coinbase', 'Coinbase'), ('OKX', 'OKX'), ('Bitfinex', 'Bitfinex'), ('Gemini', 'Gemini'), ) owner = models.ForeignKey('auth.User', related_name='wallets', on_delete=models.CASCADE) exchange_name = models.CharField(max_length=30, choices=EXCHANGES, null=True) api_key = models.CharField(max_length=255, null=True, blank=False, validators=[MinLengthValidator(64)]) secret_key = models.CharField(max_length=255, null=True, blank=False, validators=[MinLengthValidator(64)]) wallet_type = models.CharField(max_length=30, choices=(('spot', 'Spot'), ('futures', 'Futures'), ('margin', 'Margin')), default='Futures') date_connected = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.wallet_type this is the User's model class UserProfile(models.Model): @property def getter_signal_limit(self): return self.signal_limit user = models.OneToOneField(User, on_delete=models.CASCADE) # phone_number = models.CharField(max_length=20, blank=True, null=True) # username = models.ForeignKey(Users.username, on_delete=models.CASCADE, null=False) # wallet = models.ForeignKey('Wallet', on_delete=models.SET_NULL, null=True, blank=True) # Telegram = models.ForeignKey('Telegram', on_delete=models.SET_NULL, null=True, blank=True) webhook_url = serializers.SerializerMethodField() # "https://www.tradify.com/api/" + hashlib.sha256(str(User.username).encode()).hexdigest() signal_limit = models.IntegerField(default=50, validators=[MinValueValidator(1)]) signals_used = models.IntegerField(default=0) plan = models.CharField(max_length=12, choices=( ('Basic', 'Basic'), ('standard', 'Standard'), ('premium', 'Premium'), ('platinum', 'Platinum')), default='Basic') created = models.DateTimeField(auto_now_add=True, blank=True) timezone = timezone.get_current_timezone() this is the view that I'm using class DashboardView1(LoginRequiredMixin, TemplateView): template_name = 'dashboard.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) … -
When needing to count likes, views, etc per post whats the better approach?
I’m making an app using django where users can make posts. To add likes and views which can be counted and sent to be displayed on frontend i’m thinking of two approaches. is to use a reverse foreign-key relation between post’s model and likes model to dynamically count the instances of the likes model each each time. So create/delete instances of like model to represent like/unlike is to use a integer field model to store the counts in the database. use many-to-many field where number if likes for a post is determined my NO. Of user instances associated with post.likes Which approach does instagram use? Which approach would be the ultimate choice? Considering keeping costs low while maintaining scalability possibilities. Thanks -
Is it OK use multiple empty routes in Django URL patterns?
One of my project's app's url.py includes url files from other apps. Is there any issue I'm overlooking by including them with empty routes? e.g.: In appA urls.py: urlpatterns = [ path('hub/', views.hub, name='hub'), path('dashboard/', views.dashboard, name='dashboard'), path('', views.hub_redirect), # Redirects / to /hub/ path('', include('appB.urls')), path('', include('appC.urls')), ] Where appB.urls and appC.urls all contain paths each with a defined unique route (i.e., not ''). It works! But now wondering if it should... I've not seen any documentation saying that non-empty routes are required, but concerned now about best practice. I'm also concerned that I'm not understanding the function of apps. When I use django-admin createapp the urls.py is not automatically generated, so it makes me wonder if I should keep urls all on appA and point them to the views of appB and appC, but my current way makes sense to me (as it would be easier to refactor a URL within the app of the related functionality without having to make changes ouside, i.e. in appA). -
Trying to link allauth provider
so, I have everything related to allauth (a django oauth provider) connected and then in my login template I have the following href: <a href="{% provider_login_url 'google' process='connect' %}" style="text-decoration: none;"... the following error arise: MultipleObjectsReturned at /login/ No exception message supplied I can't understand what is wrong with it, it's nothing to do with process='connect' although because I tried to remove it. -
Django on AWS ECS using Celery and RabbitMQ
I wanted to upgrade my web application by deploying it on AWS ECS (instead of a single server) with the following four services running: My Django Application (autoscalable) Celery (autoscalable) Celery-Beat RabbitMQ The first three use the same code-base which I packed in a Docker Container. RabbitMQ is a custom build from the original RabbitMQ Docker image: RabbitMQ Image FROM rabbitmq:3.13 # Install necessary packages for adjusting TCP settings RUN apt-get update && apt-get install -y procps # Copy the TCP keepalive configuration file COPY ./tcp_keepalive.conf /etc/sysctl.d/tcp_keepalive.conf # Apply TCP keepalive configuration RUN sysctl -p # Copy general configuration COPY ./rabbitmq.conf /etc/rabbitmq/rabbitmq.conf whereas tcp_keepalive.conf: net.ipv4.tcp_fin_timeout=30 net.ipv4.tcp_keepalive_time=30 net.ipv4.tcp_keepalive_intvl=10 net.ipv4.tcp_keepalive_probes=4 net.ipv4.tcp_tw_reuse=1 and rabbitmq_conf: # consumer timeout consumer_timeout = 432000000 # TCP Keepalive tcp_listen_options.keepalive = true tcp_listen_options.backlog = 128 tcp_listen_options.nodelay = true tcp_listen_options.exit_on_close = true # Heartbeat heartbeat = 60 I have the following CELERY specific settings in my Django Settings File: # CELERY CELERY_TIMEZONE = "Europe/Zurich" CELERY_ACKS_LATE = True CELERY_BROKER_POOL_LIMIT = 3 # might be decreased to 1? CELERY_BROKER_CONNECTION_TIMEOUT = 30 CELERY_BROKER_CONNECTION_RETRY = True CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True CELERY_EVENT_QUEUE_EXPIRES = 60 CELERYD_PREFETCH_MULTIPLIER = 1 CELERYD_CONCURRENCY = 12 CELERY_WORKER_CANCEL_LONG_RUNNING_TASK_ON_CONNECTION_LOSS = True CELERY_BROKER_HEARTBEAT = 10 CELERY_BROKER_HEARTBEAT_CHECKRATE = 2 CELERY_BROKER_TRANSPORT_OPTIONS = { 'confirm_publish': True, 'max_retries': 3, … -
How can I make a drop-down field to display a record in a database in Django. e.g. If I select a Last Name it displays the associated record
I am trying to display a record of a database after a user has selected the record from a dropdown list of one of the fields of the table (in Django). So far I have only seen examples of selecting data from other tables. I have a model:class Customer(models.Model): created_at = models.DateTimeField(auto_now_add=True) customer_number = models.AutoField(primary_key=True) business_name = models.CharField(max_length=75, null=True, blank=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=100, null=True, blank=True) and a view: def customer_record(request): customers = Customer.objects.all() return render(request, 'customer_record.html', {'customers':customers}) and a form class Meta: model = Customer fields = ('customer_number', 'business_name', 'first_name', 'last_name', 'email') labels = {'business_name':'', 'first_name':'', 'last_name':'', 'email':'',} and the html: <select class="form-select" aria-label="Default select example"> <option selected>Open this select menu</option> {% if customers %} {% for customer in customers %} <option value={{ customer.last_name }} ></option> {% endfor %} {% endif %} </select> Trying the above, I get the dropdown that says: "Open the select menu", and then blank spaces in the dropdown corresponding, I believe, to the number of records I have. I expected to see the last names appear in the dropdown. Once selected, I would like to then display the record. -
Getting nested models fields. Serializer error. Object of type QuerySet is not JSON serializable
I'm having a trouble with getting nested object in django.My main purpose is generating json object from nested django objects. I have models as below: class SurveyAnswer(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) survey=models.ForeignKey("Survey",on_delete=models.CASCADE) answer=models.ForeignKey("Answer",on_delete=models.CASCADE) total_count=models.IntegerField(null=True,blank=True) total_percentage=models.FloatField(null=True,blank=True) class Meta: db_table="SurveyAnswer" class Answer(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name= models.CharField(max_length=100) def __str__(self) -> str: return self.name class Meta: db_table="Answer" I want to get all UserAnswer records with related Answer model(just name field in Answer model). To be able to do that I created serializer as below but this time I got error like 'Object of type QuerySet is not JSON serializable'. What am I supposed to do? Is there any easy way to do that. class SurveyAnswerSerializer(serializers.ModelSerializer): answers=serializers.StringRelatedField() class Meta: model=SurveyAnswer fields=["id","total_count","total_percentage","answers",] -
Django App, running under gunicorn cannot access database
So I m running this nginx instance with the following config: user www; worker_processes auto; pid /var/run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /usr/local/etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## #include /etc/nginx/conf.d/*.conf; #include /etc/nginx/sites-enabled/*; server { listen 80; server_name 62.171.164.192; location / { proxy_pass http://unix:/m2-webbackend/m2webapp.sock; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location /react/ { alias /eliptum-react/build/; try_files $uri $uri/ /index.html; } } } Django project gunicorn config, even tho this I don't really understand why and how it works: bind = 'unix:/m2-webbackend/m2webapp.sock' workers = 3 timeout = 120 And gunicorn instance starting command is: start gunicorn: gunicorn m2webapp.wsgi:application --bind unix:/m2-webbackend/m2webapp.sock What happens for some reason, if … -
Django/Python stack creating custom users that are tied together say as a family
Background - Hello, I am very new to django / python stack. I am trying to work on a website that needs custom user so I have inherited AbstractUser class to make my own custom user model, I am using Django built in authentication - log in / sign up as well and am able to do this successfully and store it and retrieve back in MySql database. Now my problem - I need to create users that can be tied as a family as this will be for a gym. So once user logs in they can see all members of family and book separate classes etc for each member also clicking on each member needs to pull in their profile information etc. I have tried to search but couldn't find specific answer yet so posting - is groups a way or what? Basically what is the best practice - how to create models for this situation? If anyone can point me to right direction please ? -
Cannot insert the value NULL into column 'id', table 'table'; column does not allow nulls. INSERT fails
I created a new table in Django to save some data. When I implemented the save view function, it worked locally. When it was published to the testing enviroment, I got the error Cannot insert the value NULL into column 'id', table 'table'; column does not allow nulls. INSERT fails. From what ive been able to see through the searches ive done, and queries on Azure, the auto-increment feature is not working. I tried this query and got the following results SELECT COLUMN_NAME, COLUMN_DEFAULT, DATA_TYPE, IS_NULLABLE, COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'table' AND COLUMN_NAME = 'id'; COLUMN NAME Column B DATA_TYPE IS_NULLABLE id int NO 0 I have tried to manually change the IDENTITY to 1, but it didnt work. I got errors preventing this. Failed to execute query. I am not able to manually add a row in Django Admin, as I get the same error, and there are no entries to the table in the database at all. -
Task send_verify_email[dea32c62-98b6-4418-93af-5c5d0f0f20ad] raised unexpected: TimeoutError(110, 'Connection timed out')
After I enable celery in the terminal, I click Send email again and wait for a moment to get the result.My configuration file is also configured, and I will receive front-end requests, and the back-end server is normal, but there is still a timeout problem, I do not know why. [2024-05-13 23:09:54,387: INFO/MainProcess] Task send_verify_email[dea32c62-98b6-4418-93af-5c5d0f0f20ad] received [2024-05-13 23:12:05,560: ERROR/ForkPoolWorker-1] Task send_verify_email[dea32c62-98b6-4418-93af-5c5d0f0f20ad] raised unexpected: TimeoutError(110, 'Connection timed out') Traceback (most recent call last): File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/celery/app/trace.py", line 453, in trace_task R = retval = fun(*args, **kwargs) File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/celery/app/trace.py", line 736, in __protected_call__ return self.run(*args, **kwargs) File "/home/admin/haoke18/hk18/celery_tasks/email/tasks.py", line 27, in send_verify_email send_mail(subject, "", EMAIL_FROM, [to_email], html_message=html_message) File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/admin/.virtualenvs/haoke_mall/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.10/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.10/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.10/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.10/socket.py", line 845, in create_connection raise err File "/usr/lib/python3.10/socket.py", line 833, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out I configured Django with the correct email … -
Migrating from SQLite to MySQL Django (not working)
I'm trying to implement the MySQL instead of the SQLite, and the instructions are pretty straight forward, but, when I run the server again it stops after the system check identified no issues (0 silenced)., which indicates that it can't establish a connection to the database. but everything checks out. I did this step in the database migration: Installing Mysql server && mysqlclient Create a database and a user and grant all permissions to that database add to the setting.py file the database & user settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'auth', 'USER': 'admin', 'PASSWORD': 'password', 'HOST': '127.0.0.1', """localhost not working (Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2))""" 'PORT': '3306', } } Am I missing anything out? Why isn't it working? -
There is a problem with the booking, does not go to booking_confirmation
I have a form in my app and when i submit it, everything goes correct but it only goes to .../bookings and not .../bookings/booking_conifrmation.html. Here are the views.py and urls.py views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from datetime import timedelta from .forms import BookingForm from .models import Booking from blog.models import Car from django.urls import reverse from django.utils import timezone from django.utils.dateparse import parse_date import requests from .models import BusyDate import json from django.http import JsonResponse def booking_form(request): if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): car_id = form.cleaned_data['car'].id start_date = form.cleaned_data['period_start'] end_date = form.cleaned_data['period_end'] busy_date = BusyDate(car_id=car_id, start_date=start_date, end_date=end_date) #booking = Booking(car_id=car_id, start_date=start_date, end_date=end_date) busy_date.save() messages.success(request, "Your booking has been successfully submitted.") return redirect(reverse('booking_confirmation', kwargs={'car_id': car_id})) else: for field, errors in form.errors.items(): for error in errors: messages.error(request, f"Error in {field}: {error}") else: # Set default values for period_start and period_end start_time = timezone.now().strftime('%Y-%m-%d') end_time = (timezone.now().date() + timedelta(days=1)).strftime('%Y-%m-%d') initial_data = {'period_start': start_time, 'period_end': end_time} form = BookingForm(initial=initial_data) # Retrieve unavailable dates for selected car car_id = request.GET.get('car_id') # Assuming the car_id is passed in the request if car_id: try: car = Car.objects.get(id=car_id) start_date = timezone.now().strftime('%Y-%m-%d') end_date = (timezone.now().date() + timedelta(days=1)).strftime('%Y-%m-%d') response = requests.get( … -
getting error page not found while giving @login_reequired
views.py @login_required def transactions(request): user_transactions = Transactions.objects.filter(transaction_medium = request.user) return render(request,'transactions.html',{'user_transactions':user_transactions}) urls.py urlpatterns = [ path('',views.signup,name="signup"), path('login/',views.login,name="login"), path('add_transactions/',views.add_transactions,name="add_transactions"), path('transactions/',views.transactions,name="transactions"), ] error is Not Found: /accounts/login/ "GET /accounts/login/?next=/transactions/ HTTP/1.1" 404 2846 -
I am creating a dashboard view in django to show all the data of the user but it shows nothing when i use class based view..?
when i use the function based view it works fine. can anyone help me? this is the model class UserProfile(models.Model): @property def getter_signal_limit(self): return self.signal_limit user = models.OneToOneField(User, on_delete=models.CASCADE) webhook_url = serializers.SerializerMethodField() # "https://www.tradify.com/api/" + hashlib.sha256(str(User.username).encode()).hexdigest() signal_limit = models.IntegerField(default=50, validators=[MinValueValidator(1)]) signals_used = models.IntegerField(default=0) plan = models.CharField(max_length=12, choices=( ('Basic', 'Basic'), ('standard', 'Standard'), ('premium', 'Premium'), ('platinum', 'Platinum')), default='Basic') created = models.DateTimeField(auto_now_add=True, blank=True) timezone = timezone.get_current_timezone() this is the user serializer code class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = '__all__' # fields = ('user', 'signal_limit', 'signals_used', 'plan', 'created', 'webhook_url') # read_only_fields = ('user', 'created') def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(**user_data) user_profile = UserProfile.objects.create(user=user, **validated_data) return user_profile this is the Function based view login_required def dashboard(request): user_profile = request.user.userprofile context = { 'user_profile': user_profile, 'signal_limit': user_profile.signal_limit, 'signals_used': user_profile.signals_used, 'plan': user_profile.plan, 'webhook_url': user_profile.get_webhook_url(), 'timezone': user_profile.timezone, } return render(request, 'dash.html', context) and here is its html code <!-- dashboard.html --> <h1>Dashboard</h1> <p>Username: {{ user_profile.user.username }}</p> <p>Signal Limit: {{ signal_limit }}</p> <p>Signals Used: {{ signals_used }}</p> <p>Plan: {{ plan }}</p> <p>Webhook URL: {{ webhook_url }}</p> <p>Timezone: {{ timezone }}</p> while this code is not showing any data of the user Class based view: class DashboardView(LoginRequiredMixin, TemplateView): template_name = 'dashboard.html' … -
Django not creating a table in the Development Server
I've been trying to fix this problem, but couldn't find a solution, tried a bunch of fixes online. The problem I'm facing. I have a Django project running on Hawuei Cloud, I've made some changes and wanted to test it on the Development server before going to production. The project is running fine, BUT, there's a table that is not being created for some reason, so the parts of the project that uses that table, throws an error. But the thing is the changes I've made weren't on that table. I don't understand why that table isn't being created, I never had this issue. This is a small part of the model class Regime(models.Model): inventario = models.ForeignKey(Inventario, on_delete=models.CASCADE) nome = models.CharField(max_length=50) def __str__(self): return self.nome class Unidade(models.Model): empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE) codigo = models.CharField(max_length=50) descricao = models.CharField(max_length=100) cnpj = models.CharField(max_length=20) def __str__(self): return self.descricao class Conta(models.Model): empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE) codigo = models.CharField(max_length=50) descricao = models.CharField(max_length=100) def __str__(self): return self.descricao class Local(models.Model): empresa = models.ForeignKey(Empresa, on_delete=models.CASCADE) codigo = models.CharField(max_length=50) descricao = models.CharField(max_length=100) def __str__(self): return self.descricao The table Unidade is not being created, the other similar ones like Local and Conta work just fine. I've tried flushing the database, migrating … -
How to check if user is entering only numbers
I'm trying to update my registration system. I want user entering his age, but I don't know how to check if user entered only numbers. I will give snippet of my code, where it doesn't work my views.py: def Registration(request): if request.method == "POST": username = request.POST["username"] age = request.POST["age"] ... if username.isnumeric() == "True": messages.error(request, "Username can't be all number!") return redirect("/") if age.isnumeric() == "False": messages.error(request, "Age must be all numbers!") return redirect("/") ... messages.success(request, "Your account has been succesfully created") return redirect("/Login/") return render(request, "Registration.html") my registration.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width-device-width, initial-scale=1, maximum-scale=1" /> <link rel="stylesheet" type="text/css" href="https://bootswatch.com/5/solar/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> <title> view tasks </title> </head> <body> <div class="text-center"> <h1>Registrate here</h1> <form action="/Registration/" method="post"> {% csrf_token %} <label for"username">Username</label> <br> <input class="" type="text" id="username" name="username" placeholder="Create a username (letter and numbers only)" Required> <br> <br> <label for"age">Age</label> <br> <input class="" type="text" id="age" name="age" placeholder="Enter your age" Required> <br> <br> <label for"fname">First Name</label> <br> <input class="" type="text" id="fname" name="fname" placeholder="Enter your first name" Required> <br> <br> <label for"lname">Last Name</label> <br> <input class="" type="text" id="lname" name="lname" placeholder="Enter your last name" Required> <br> <br> <label for"email">Email</label> … -
How to manipulate pandas datafram from mysql?
I have a doubt with inserting pandas into mysql please answer sir @Henri @user:8510149 I have inserted now i want to manipulate it. Please help me regarding this issue and this is for a project that Im currently working on. .Awaiting your reply.... -
Problem with django translation detection in the templates
Here i generate my template from a http request so i have a custom method to generate my templates : def get_template(template, using=None): engines = _engine_list(using) for engine in engines: return engine.from_string(template) And here i pass the template : def get_template_names(self): print(self.html_template) return get_template(self.html_template, using=self.template_engine) and in my console i get : app-1 | {% load i18n static %} app-1 | app-1 | {%block content %} app-1 | <p>{{ _('Hello from the template')}}</p> app-1 | <p>{% translate 'hello my friends' %}</p> app-1 | app-1 | {%endblock%} Then i generate my .po file insinde a locale dir with django-admin makemessages -l fr So the problem is when the .po file is generated i don't get my strings Hello from the template and hello my friends while we are supposed to get the strings to translate automatically. PS: When i enter manually the string hello my friends or Hello from the template in the .po file and I add a translation. This is work well Where is the problem please I don't want to add strings manually anymore ? i try to get my custom strings to translate inside my custom template but i don't get them the .po file is empty -
How to change the attributes of Django login form
My site is RTL so I need to adjust the direction of some fields to LTR (username, email, password, etc). One of them is the Password Change form so this is what I do: forms.py from django.contrib.auth.forms import PasswordChangeForm class CustomPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['old_password'].widget.attrs.update({'dir': 'ltr'}) self.fields['new_password1'].widget.attrs.update({'dir': 'ltr'}) self.fields['new_password2'].widget.attrs.update({'dir': 'ltr'}) After creating the required view and URL path, that works perfectly and all 3 fields are LTR. The other one is the Login Form so I do the same thing: forms.py from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): def __init__(self, request=None, *args, **kwargs): super().__init__(request, *args, **kwargs) self.fields['username'].widget.attrs.update({'dir': 'ltr'}) self.fields['password'].widget.attrs.update({'dir': 'ltr'}) This time, the above code does not have any effect. Both fields are still RTL. So why it works for password change and not for login and what's the solution for login form? -
TemplateSyntaxError at /cart/ Invalid filter: 'mul' Reques
TemplateSyntaxError at /cart/ Invalid filter: 'mul' Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 5.0.6 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'mul' Exception Location: C:\Users\denni\Desktop\Foods1\venv\Lib\site-packages\django\template\base.py, line 603, in find_filter Raised during: Foodies.views.view_cart Python Executable: C:\Users\denni\Desktop\Foods1\venv\Scripts\python.exe Python Version: 3.11.7 Python Path: ['C:\Users\denni\Desktop\Foods1\Foods', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\denni\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\denni\AppData\Local\Programs\Python\Python311', 'C:\Users\denni\Desktop\Foods1\venv', 'C:\Users\denni\Desktop\Foods1\venv\Lib\site-packages'] Server time: Mon, 13 May 2024 11:01:44 +0000 Error during template rendering I want after click on buy now it should give me result