Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy a Django backend in a self-hosted PC?
I have a Django Back-end and I would like to deploy in "production" in a local PC and to be accessible for everyone on the same network. PS: the network has a proxy. How can I achieve this in a way that the server is fast and reliable, also I have some async functionality so I was reading of this integraton with uvicorn, where I was deploying in local server to test the functional views. Any suggestions are welcome, I just need a general overview of the path I should go for accomplish this :) -
OSError: /opt/anaconda3/lib/libgdal.dylib: cannot open shared object file: No such file or directory
I am using windows and installed geodjango in my pc but not too confirm how can i add the path to my django application i.e = GDAL_PATH = ?? not to confirm i have try the folder in which my gdal is installed that path but it didn't work -
How to convert a string to a datetime?
I'm trying to run a row query with objects. I have a tran_date field which is look like: '2022062519:14:47' I think because of that I'm getting this error: django.db.utils.DataError: date/time field value out of range: "2022062519:22:54" LINE 1: ...HERE merch_id = '510000022048730' and tran_date = '202206251... Here is my code: medium_prob = ProcessTransaction.objects.raw('SELECT * ' 'FROM bvb_generaltransaction ' 'WHERE merch_id = %s and tran_date = %s::DATE ' 'and probabilty >= 0.8 and alerted= false', [str(merchant.merch_id), str(merchant.tran_date)]) How can I solve that? -
how to display error messages in django in front of each textbox django
I am having an issue that i wanted to display error messages below each text-box but. Below is my code i am having an issue that how to display each message below textboxes e.g username taken in front of username. -
Django Channels equivalent code for javax.websocket
I am new to Django Channels. I am trying to replicate what is being done in this Java code using Django Channels. But I cannot figure out how to send the message JSON to the Angular frontend. The frontend has a table that will get updated throught the websocket implementation. But the recieve method doesn't seem to replicate what the onMessage method was doing. Django Channels performs a successful handshake. But that's all that happens. Java Code @ServerEndpoint("/socket/order") @ApplicationScoped public class OrderSocket { Set<Session> sessions = new HashSet<>(); @OnOpen public void onOpen(Session session) { LOG.debug("onOpen " + session.getId()); sessions.add(session); } @OnClose public void onClose(Session session) { LOG.debug("onClose " + session.getId()); sessions.remove(session); } @OnError public void onError(Session session, Throwable throwable) { LOG.debug("onError " + session.getId() + " left on error: " + throwable); sessions.remove(session); } @OnMessage public void onMessage(String message) { LOG.debug("onMessage " + message); broadcast(message); } public void broadcast(OrderDto orderDto) { Jsonb jsonb = JsonbBuilder.create(); String jsonString = jsonb.toJson(orderDto); broadcast(jsonString); } private void broadcast(String message) { sessions.forEach(s -> { LOG.debug("Message broadcasted: " + message); s.getAsyncRemote().sendObject(message, result -> { if (result.getException() != null) { LOG.error("Unable to send message: " + result.getException()); } }); }); } } Python Code consumer.py class OrderConsumer(WebsocketConsumer): … -
Images loss every time on server when run "docker-compose up --build" + Django
I had a setup docker on Django project, images are stored on server but whenever I upload changes on server and then run "docker-compose up --build" then it loss every images that I uploaded, path showing images there but I am not able to view it. I don't know want happened there. if anyone have idea what to do for that ? How to resolved this issue ? is there any things need to add in docker-compose file ? Below is my docker compose file. version: '3' volumes: web-django: web-static: services: redis: image: "redis:alpine" web: build: . image: project_web command: python manage.py runserver 0.0.0.0:8000 restart: always volumes: - web-django:/usr/src/app - web-static:/usr/src/app/mediafiles ports: - "8000:8000" depends_on: - redis celery: image: project_web command: celery -A project_name worker -l info restart: always depends_on: - web - redis celery-beat: image: citc_web command: celery -A project_name beat -l info restart: always depends_on: - web - redis I want solution of it, what i missing on above file and want to resolve it. -
How To Solve Django ValueError: :Comment.post" must be a "Software" instance
I'm getting an error over and over again when I'm displaying comments for a program. Please what is the problem I made here? I made many attempts using get , filter but the error remains the same. Other errors may appear when changing the view of comments. Please help. def download(request,slug): app = get_object_or_404 (Software,slug = slug) comments= app.comments.filter(active=True).order_by("-created") try : app = Software.objects.filter(slug = slug) except : raise Http404 new_comment = None if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post= app <<<--------------------------->>> here my error new_comment.save() else: comment_form = CommentForm() context ={ 'app' :app, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, } return render( request,'download.html',context) that's my models: class Software (models.Model): class Meta : verbose_name_plural = 'software' ordering = ['created_at'] category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True, related_name="mac") category = models.CharField(max_length=150 , null=True,blank=True) slug = models.SlugField(blank=True,allow_unicode=True,editable=True) title = models.CharField(max_length=50 , null=True) requirements = models.CharField(max_length=100 , null=True) version = models.CharField(max_length=100 , null=True) picture = models.ImageField(upload_to='img_pro' , null=True) size = models.CharField(max_length=20 , null=True) created_at = models.DateField(auto_now_add=True) auther = models.CharField(max_length=100 , null=True) download = models.URLField(null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('download', args=(self.slug,)) class Comment(models.Model): post = models.ForeignKey(Software , on_delete=models.CASCADE ,null=True, related_name='comments') name = models.CharField(max_length=80 , null=True) email = models.EmailField(max_length=200, blank=True … -
ValueError: Related model 'users.customuser' cannot be resolved
Can't figure out what to do to solve this problem. I am trying to create a custom user model but when i try to migrate it throws this error. Here is managers.py: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email or Phone numvber must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) Here is models.py: from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.CharField(_('email or phone number'), max_length=175, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS … -
Dynamic template rendering in Angular
Can we render template dynamically from DB? in this template, I'm going to use angular event, string interpolation and directive. Do we have any other option instead of Angular compiler?? Currently we have old process or code... -
Django. One project. Separate auth systems and templates for different apps
I have a project with the following structure: main_app accounts_app (stores CustomUser model) my_app1 users_app (inside my_app1) my_app2 users_app (inside my_app2) The reason behind separate users_app is that I want to reuse my_app1 and my_app2 in other projects. So I want them to be as separate as possible. I want to have a separate auth system (custom user model, registration, templates, login/logout redirect, etc) for each app. So for example, let's say I have my-app1 at url localhost:8000/my-app1/. This means that registration will be at /my-app1/signup/, login at /my-app1/login/ and login redirect goes to /my-app1/ I also want to use allauth on some or all apps. Questions: Does this project structure even make sense? (yes/no) Is it possible to have separate signup/sigin/etc templates for each app using allauth? (yes/no - link to doc?) I couldn't find the answer to this. How do I avoid DB conflicts with migrations when creating custom user for each app? Right now I'm inheriting from AbstractUser in each app's model.py, like so: class MainCustomUser(AbstractUser), class AppOneUser(AbstractUser), class AppTwoUser(AbstractUser) But that doesn't seem to work. Answers to these questions will serve me as guidance in the right direction, right now I sort of confused myself a … -
Send email based on form boolean value
I am trying to send email based on the form boolean value. If the Trigger_Email is True then send the mail Below is the models.py class New_Shipment(models.Model): Status_CHOICES = ( ("1", "Open"), ("2", "Close"), ) alphanumeric = RegexValidator(r'^[\s0-9a-zA-Z\.-_]*$', 'Only alphanumeric characters are allowed.') Courier_or_Freight_details = models.CharField(max_length=200, validators=[alphanumeric]) Quantity = models.IntegerField() Action_On = models.CharField(max_length=200, validators=[alphanumeric]) Status = models.CharField(max_length=300, validators=[alphanumeric], choices=Status_CHOICES) Trigger_Email = models.BooleanField(default=False) Below is my views.py def my_form1(request, new_shipment=New_Shipment): if request.method == "POST": form1 = MyForm1(request.POST) if form1.is_valid(): new_shipment = get_object_or_404(New_Shipment) elif new_shipment.Trigger_Email: subject = "New Shipment Details" message = "Hello \n New Shipment details added to the EPC\n\n Regards,\nIsmail" from_email = settings.EMAIL_HOST_USER to_list = ['toemail@gmail.com'] send_mail(subject, message, from_email, to_list, fail_silently=True) form1.save() return HttpResponse('Submitted successfully') # return redirect('/home_page/') else: form1 = MyForm1() return render(request, "authentication/New_shipment.html", {'form1': form1}) Any Kind of help will be appreciated. Thanks in advance -
django returning duplicates even though distinct() is used
I'm using django=4.1, python=3.8 & sqlite. What I want to do filter our the top five player points and unique players in a given month and present it in a template, there shouldn't be any duplicates. This is the PlayerPoint model: class PlayerPoint(models.Model): OPERATION_CHOICES = (('ADD', 'ADD'), ('SUB', 'SUBTRACT'), ('RMN', 'REMAIN')) points = models.IntegerField(null=False, default=0) operation = models.CharField( max_length=3, null=False, choices=OPERATION_CHOICES, default=OPERATION_CHOICES[2][0] ) operation_amount = models.IntegerField(null=False) operation_reason = models.CharField(null=False, max_length=1500) player = models.ForeignKey( settings.AUTH_USER_MODEL, null=False, on_delete=models.PROTECT, to_field="phone_number", related_name="player_points" ) points_ts = models.DateTimeField(auto_now_add=True, null=False) And this is the player model: class Player(AbstractUser): phone_number = models.CharField( max_length=14, unique=True, help_text="Please ensure +251 is included" ) first_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) father_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) grandfather_name = models.CharField( max_length=40, help_text="please ensure that you've spelt it correctly" ) email = models.EmailField( unique=True, help_text="please ensure that the email is correct" ) age = models.CharField(max_length=3) profile_pic = models.ImageField(upload_to='profile_pix', default='profile_pix/placeholder.jpg') joined_ts = models.DateTimeField(auto_now_add=True, null=False) username = None When I run the below query it gives me the top 5 Player Points but it's not distinct, the player_ids are duplicates. It keeps repeating the same Player. q = PlayerPoint.objects.filter(points_ts__year=2023, points_ts__month=1, points__gte=2000) x = q.order_by('-points') … -
Restricting website access by client geolocation
I need to restrict access to a website because of countries regulations. I know that Hosting providers or CDNs/Webservers like Cloudflare or NGINX can do that for me and is probably the best approach (?) but I think only if the website needs to scale and since it has small expected traffic I'd like to just implement it myself for the start. This question is not about how to get the users IP or how to use geolocation APIs with that IP. It is about how to design the backend to deny or grant access to the website for the clients. Do I need to do it on every request to the server ? If yes should I just write middleware that rejects the request if it is a blocked coutry or put that logic somewhere else ? Or can I do it once and then just "remember" it somehow for that client (how reliable would that be/ could that be abused ?). I just dont want to build a super stupid design where I affect the performance of the backend just for a simple task like that. Thank you in advance. -
How can i access current session data outside django view function?
I am using SessionStore object to store session data, how can i get current session data from Session table without using pk as we dont know pk of record stored in table. Here is the code ldap.py from django.contrib.sessions.backends.db import SessionStore s = SessionStore() class LDAPPBackend(ModelBackend): def authenticate(self, *args, **kwargs): **s['memberOf']** = "Star Group" #**setting session** s.create() serializer.py from rest_framework import serializers from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from django.contrib.sessions.models import Session **s = Session.objects.get(pk="")** #**how can i know current logged in user session pk???** class TokenObtainPairPatchedSerializer(TokenObtainPairSerializer): def validate(self, attrs): data['attr'] = attrs **data['memberOf'] = s** # **How can i get current session data here??** return data How can i achieve this??? -
How to serve thumbnail image instead of full image on the articles listing page in Django?
I made a django powered website here it is https://www.endustri.io When you look the frontpage i serve the blog post feautered image in original size. And it causes the increase loading time. So i wanna serve 300x180 pixels the featured images of the posts. How can i make automatically 300x180 pixels images from my original images and how can i serve these images on the frontpage. When i looked the media file, i wanna see two images, one of is original and other image is 300x180 pixels. Here is my codes... views.py def frontpage(request): posts = Post.objects.order_by('-id') most = Post.objects.order_by('-num_reads')[:10] kat = Category.objects.all() f = Firma.objects.all().order_by('-id')[:15] p = Paginator(posts, 10) page = request.GET.get('page') sayfalar = p.get_page(page) context = { 'posts': posts, 'most': most, 'kat': kat, 'sayfalar': sayfalar, 'f': f, } return render(request, 'blog/frontpage.html', context) models.py class Post(models.Model): category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) intro = models.TextField() body = tinymce_models.HTMLField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/") date_added = models.DateTimeField(auto_now_add=True) num_reads = models.PositiveIntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('detail', args=[str(self.slug)]) and frontpage.html {% for post in sayfalar %} <div class="card mb-3" style="max-width: 75%px;"> <div class="row g-0"> <div class="col-md-4"> <img … -
How to apply permissions on perform_create in ViewSet DRF
This is my View Set: class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = MyClass.objects.all() def get_serializer_class(self): if self.request.user.is_superuser: return self.serializer_class return serializers.MyUserSerializer def perform_create(self, serializer): employee = models.Employee.objects.get(user=self.request.user) serializer.save(employee=employee) I want to apply permission before perform_create, this perform_create() should only be called if a currently logged in user is not a super user. If a currently logged in user is a superuser, default perform_create function should be called. How to do that? -
Refused to apply style from '<URL>' because its MIME type ('text/html') pythonanywhere
Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. i dont have any problem in vscode but when i hosted into pythonanywhere i cant even login into admin panel and the css from admin panel is not working -
Integration of Django-PayPal subscription based payment system
I am trying to implement a Subscription-based payment method in Django. I have tried to Integrate the subscription-based button as per the PayPal guidlines. Screenshot is attached for same. But after clicking on either button screen is blank, and nothing happens, screenshot is attached for the same. Here is my code for button integration. <div id="paypal-button-container-P-789654"></div> <script src="https://www.paypal.com/sdk/js?client-id=123456&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script> <script> paypal.Buttons({ style: { shape: 'pill', color: 'blue', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ /* Creates the subscription */ plan_id: 'P-789654' }); }, onApprove: function(data, actions) { alert(data.subscriptionID); // You can add optional success message for the subscriber here } }).render('#paypal-button-container-P-789654'); // Renders the PayPal button </script> -
Django: starting server using a specific database out of multiple databases
I am trying to set up 2 databases in django. The second database is meant for testing purposes, so the 2 databases practically have the same models. My question is how to start the server using the second database. The steps I did for setting up the databases: I created a second app called 'testing', so now in my project root folder there is the app api (the real one) and testing (the app meant for the test database). Afterwards, added the same models from api/models.py to testing/models.py Created router for the first database and the second database: class AuthRouter: route_app_labels = {'auth', 'contenttypes', 'admin', 'sessions'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'default' return None def allow_migrate(self, db, app_label, model_name = None, **hints): if app_label in self.route_app_labels: return db=='default' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None class SpotTesting: route_app_labels = {'spot_testing'} def db_for_read(self, model, **hints): if model._meta.app_label == "spot_testing": return 'test_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == "spot_testing": return 'test_db' return None def allow_relation(self, obj1, obj2, **hints): """ … -
Forbidden (403) CSRF verification failed - Error with Docker, Django and Nginx
I am new to docker. Starting from a Django project (Django 4.0), I am using Docker to side by side with Nginx. I used a docker-compose.yml file and used a custom configuration of Nginx, and everything works. Only when I go to the login screen and click the "Login" button it comes up "Forbidden (403) CSRF verification failed. Request aborted.". The code inside login.html is like this <form method="post">{% csrf_token %} {{ form|crispy }} <button class="btn btn-success ml-2" type="submit">Log In</button> Thanks in advance! -
how to fix roll up error while building vue apps?
i want to deploy simple personal website using vue but when i try to npm run build this error come up help me please... i try deleting the image but onother similiar error come's up error during build: RollupError: Could not resolve "../img/react%202.png" from "src/component/avatarmenu.vue" at error (file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:2041:30) at ModuleLoader.handleInvalidResolvedId (file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:23137 :24) at file:///C:/Users/adity/OneDrive/Documents/LATIHAN/personal-w-vue/node_modules/rollup/dist/es/shared/rollup.js:23099:26 -
Django app not able to find database engine when engine is specified
I have tried everything I can think of to run my initial migrations and get my django app up. I am currently getting this error: Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/lib/python3/dist-packages/django/core/management/commands/dbshell.py", line 22, in handle connection.client.runshell() File "/usr/lib/python3/dist-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. But this is the DATABASES var in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } The db.sqlite3 file is at the location specified in the 'NAME' key. The app folder is in a subdirectory and uniquely named. The BASE_DIR var is constructed correctly and not causing the location string in the NAME key to be malformed. The models.py file is in the /app folder subdirectory. I am completely out of ideas on how to get this to work and considering giving up on making this project altogether. Please help. … -
Use HTML-template from other app, in same project (Django)
I have a project wich contains two apps User and Accounting. Since all of their HTML-templates should extend from the same base.html template, I made a third app called Shared, and my accounting/base.html and user/base.html would then extend from shared/base.html like {% extends "shared/base.html" %} {% block content %} <div>Hello world</div> {% endblock content %} but that does not work, since Django looks in <app>/templates/shared/base.html. Can this be done without having to just duplicate base.html and have the same file in Accounting and User? -
I have an error in django template for loop
I have an error in django template for loop. My code: <div class="form-group col-md-4 form-field"> <label>Year</label> <select name="year" id="year" name="year"> {% for y in range(1980, (datetime.datetime.now().year + 1)) %} <option value="{{ y }}">{{ y }}</option> {% endfor %} </select> </div> My error: 'for' statements should use the format 'for x in y': for x in y range(1980, (datetime.datetime.now().year + 1)) Please help me to resolve this issue. Please help me to resolve this issue. Please help me to resolve this issue. -
update value certain time later using django appscheduler
I want to update a value every day at a certain time later. I wrote my models and views look like models.py class InvestmentRequest(models.Model): user = models.OneToOneField(User, related_name=“investment_request”, on_delete=models.CASCADE) profit = models.DecimalField(max_digits=15, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user.username}-{self.amount}" def increase_balance(self, profit ): self.profit += decimal.Decimal(profit ) self.save() def save(self, *args, **kwargs): super().save(*args, **kwargs) views.py scheduler = BackgroundScheduler() job = None def tick(): print(‘One tick!’) # roi_profit() --- any way like this def start_job(): global job job = scheduler.add_job(tick, 'interval', seconds=3) try: scheduler.start() except: pass I used here “appscheduler” library because my requirement is minimal, it’s not a complex configuration like celery. Is there any way to run ‘roi_profit’ views at a certain time every day? Here ‘tick’ function runs very smoothly because it is a normal function. But I can’t call the views function because it’s a required request. And without request, I can’t get any value from request.user. It’s necessary. So this way how I can update my model value at a certain time later every day. Over a couple of days I’m struggling with it but couldn’t find the exact solution. Any suggestions will be appreciated. Thanks.