Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 18 for SQL Server]
I'm trying to convert a DataFrame columns type and I'm receiving this error when I try to insert the data into SQL SERVER: pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 22 (""): The supplied value is not a valid instance of data type float. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision. (8023) (SQLExecDirectW)') These are my code and database schema: with pyodbc.connect(sql_server) as conn: cursor = conn.cursor() df_bcb = pd.DataFrame(newest_file) df_bcb['database'] = df_bcb['database'].astype(str, errors='ignore') df_bcb['codigoIdentificadorBacen'] = df_bcb['database'].astype(str, errors='ignore') df_bcb['codigoSisbacen'] = df_bcb['codigoSisbacen'].astype(int, errors='ignore') df_bcb['siglaISO3digitos'] = df_bcb['siglaISO3digitos'].astype(str, errors='ignore') df_bcb['nomeDoPais'] = df_bcb['nomeDoPais'].astype(str, errors='ignore') df_bcb['nomeDaUnidadeFederativa'] = df_bcb['nomeDaUnidadeFederativa'].astype(str, errors='ignore') df_bcb['codigoDoMunicipioNoIBGE'] = df_bcb['codigoDoMunicipioNoIBGE'].astype(int, errors='ignore') df_bcb['nomeDoMunicipio'] = df_bcb['nomeDoMunicipio'].astype(str, errors='ignore') df_bcb['nomeEntidadeInteresse'] = df_bcb['nomeEntidadeInteresse'].astype(str, errors='ignore') df_bcb['nomeEntidadeInteresseNaoFormatado'] = df_bcb['nomeEntidadeInteresseNaoFormatado'].astype(str, errors='ignore') df_bcb['codigoCNPJ14'] = df_bcb['codigoCNPJ14'].astype(str, errors='ignore') df_bcb['codigoCNPJ8'] = df_bcb['codigoCNPJ8'].astype(str, errors='ignore') df_bcb['codigoTipoSituacaoPessoaJuridica'] = df_bcb['codigoTipoSituacaoPessoaJuridica'].astype(int, errors='ignore') df_bcb['descricaoTipoSituacaoPessoaJuridica'] = df_bcb['descricaoTipoSituacaoPessoaJuridica'].astype(str, errors='ignore') df_bcb['codigoTipoEntidadeSupervisionada'] = df_bcb['codigoTipoEntidadeSupervisionada'].astype(int, errors='ignore') df_bcb['descricaoTipoEntidadeSupervisionada'] = df_bcb['descricaoTipoEntidadeSupervisionada'].astype(str, errors='ignore') df_bcb['codigoNaturezaJuridica'] = df_bcb['codigoNaturezaJuridica'].astype(int, errors='ignore') df_bcb['descricaoNaturezaJuridica'] = df_bcb['descricaoNaturezaJuridica'].astype(str, errors='ignore') df_bcb['codigoEsferaPublica'] = df_bcb['codigoEsferaPublica'].astype(int, errors='ignore') df_bcb['nomeReduzido'] = df_bcb['nomeReduzido'].astype(str, errors='ignore') df_bcb['siglaDaPessoaJuridica'] = df_bcb['siglaDaPessoaJuridica'].astype(str, errors='ignore') df_bcb['nomeFantasia'] = df_bcb['nomeFantasia'].astype(str, errors='ignore') df_bcb['indicadorEsferaPublica'] = df_bcb['indicadorEsferaPublica'].astype(int, errors='ignore') df_bcb['header_id'] = df_bcb['header_id'].astype(int, errors='ignore') print(df_bcb) … -
How to restrict so that the author of the post can only see and edit his posts
In this code only the author of the post can edit his post, but how to also make so that the author of the post can see only his posts? from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True return False def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user Please add a link to useful reading materials -
AttributeError: 'Serializer' object has no attribute '_meta'
i have created this serializer to validate on the presence of a record with these column combination` class CampaignServicesValidation(serializers.Serializer): campaign_id = serializers.IntegerField(required=True) service_id = serializers.IntegerField(required=True) def validate(self, data): try: campaign_service = CampaignServices.objects.get(campaign_id=data['campaign_id'], service_id=data['service_id']) print("found"+str(campaign_service.id)) except Exception: raise serializers.ValidationError(detail='Campaign Service does not exist') return campaign_service and it is called in my viewSet like this: campaign_service = CampaignServicesValidation(data={'campaign_id': request.data['campaign_id'], 'service_id': pk}) if not campaign_service.is_valid(): return RestResponse(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, serializer_error=campaign_service.errors) when the combination is not found it raises an exception and works well, but when it passes validation and enters the is_valid() function in the if condition it produces this error Traceback (most recent call last): File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\RightsHero\collector-management\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\RightsHero\collector-management\collectors_management\views.py", line 157, in update_campaign_service_frequency serializer.save() File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 207, in save self.instance = self.update(self.instance, validated_data) File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 993, in update info = … -
How to access nested fields in JSONField in the HTML template (Django)
I have a user model with a field called data containing nested data, e.g for one user that could be data = { "2020":{"payment_date":"today","amount":600}, "2021":{"payment_date":"","amount":800} } the model also has a name field. In my HTML I can access name and data but I struggle getting "deeper" into data to extract amount from 2020 and 2021. I would assume I could do {{user.data.2020}} but that does not work. Doing {{user.data}} does indeed show the "remaining data". Right now I have tried <div class="media-body"> <table> <tr> <th>Name</th> <th>2020</th> <th>2021</th> </tr> {% for user in users%} <tr> <td>{{user.name}}</td> # works <td>{{user.data.2020.amount}}</td> <td>{{user.data.2021.amount}}</td> </tr> {% endfor %} </table> </div> but that does not work -
Django Wagtail dynamically create form without new model
How would I allow my primary user to dynamically create forms they can issue to their end clients. Each of my primary users has their own unique information they would like to collect that I do not know before hand. I would like to avoid creating new models in code for their dynamic needs and then having to migrate the models. I came across this which had an interesting response but it starts with disclaimer The flexibility of Python and Django allow developers to dynamically create models to store and access data using Django’s ORM. But you need to be careful if you go down this road, especially if your models are set to change at runtime. This documentation will cover a number of things to consider when making use of runtime dynamic models. Which leads me to believe a lot can go wrong. However because I'm using wagtail I believe there is probably a way to use StructBlocks & StreamFields to accomplish it. Any guidance would be helpful. -
How to install and point to Python GDAL library on App Engine (Standard)?
Django is firing this error locally: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Here's an example of how the path should look in settings: GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal300' Now this is an easy, well documented fix locally, but we're quite far along with App Engine Standard on GCP (Python 3). There's a GDAL package that seems to be installable by pip but it also seems there's also native extensions/headers required. How can I: how do I install GDAL in a specific directory in app engine? where do I know where App Engine will put it/put it somewhere myself? Note: Willing to do any kind of workaround like host it remotely (probably not allowed) or even try a different library for lat-long distance filtering. Though for the latter it must accept and return a queryset via queryset.filter() in Django so I doubt there are other Django options. Perhaps running PSQL query directly on a dataset? The only solution I found and examined were vendor packages and lib. But it looks like this is no longer an option (https://cloud.google.com/appengine/docs/legacy/standard/python/tools/using-libraries-python-27#vendoring) for … -
Groupby and count number of children where each child has more than a specific number of children itself
I have three models, Business, Employee, and Client, where each business can have many employees and each employee can have many clients: class Business(models.Model): name = models.CharField(max_length=128) menu = models.CharField(max_length=128, default="") slogan = models.CharField(max_length=128, default="") slug = models.CharField(max_length=128, default="") class Employee(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) business = models.ForeignKey( Business, related_name="employees", on_delete=models.CASCADE ) class Client(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) employee = models.ForeignKey( Employee, related_name="clients", on_delete=models.CASCADE ) A sample data: Business.objects.create(name="first company") Business.objects.create(name="second company") Business.objects.create(name="third company") Employee.objects.create(first_name="f1", last_name="l1", business_id=1) Employee.objects.create(first_name="f2", last_name="l2", business_id=1) Employee.objects.create(first_name="f3", last_name="l3", business_id=2) Employee.objects.create(first_name="f4", last_name="l4", business_id=3) Employee.objects.create(first_name="f5", last_name="l5", business_id=3) Employee.objects.create(first_name="f6", last_name="l6", business_id=3) Client.objects.create(first_name="cf1", last_name="cl1", employee_id=1) Client.objects.create(first_name="cf2", last_name="cl2", employee_id=1) Client.objects.create(first_name="cf3", last_name="cl3", employee_id=2) Client.objects.create(first_name="cf4", last_name="cl4", employee_id=2) Client.objects.create(first_name="cf5", last_name="cl5", employee_id=3) Client.objects.create(first_name="cf6", last_name="cl6", employee_id=3) Client.objects.create(first_name="cf7", last_name="cl7", employee_id=4) Client.objects.create(first_name="cf8", last_name="cl8", employee_id=5) Client.objects.create(first_name="cf9", last_name="cl9", employee_id=6) If I wanted to see how many employees each business has, I could run a query like this: Business.objects.annotate( employee_count=Count("employees") ).values( "name", "employee_count" ).order_by("-employee_count") <QuerySet [ {'name': 'third company', 'employee_count': 3}, {'name': 'first company', 'employee_count': 2}, {'name': 'second company', 'employee_count': 1} ]> Similarly, if I wanted to see how many clients each employee has, I could run a query like this: Employee.objects.annotate( client_count=Count("clients") ).values( "first_name", "client_count" ).order_by("-client_count") <QuerySet [ {'first_name': 'f1', 'client_count': 2}, {'first_name': 'f2', 'client_count': 2}, … -
autocomplete form in django
i'm trying to make an autocomplete form in django but when i run the page locally don´t run because don't find the url of the json, the idea of the autocomplete is that take information from x table and then the form post the information in y table views.py def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'def get_employee(request): if is_ajax(request=request): q = request.GET.get('term', '') places = InfoTrabajadores.objects.filter(documento__icontains=q) results = [] for pl in places: place_json = {} place_json['label'] = pl.state results.append(place_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) and the jquery $(document).ready(function() { async function getCities(event, ui) { let url = '{% url ' / api / get_employees / ' %}'; let url = 'http://127.0.0.1:8000/api/get_employees/'; let results = await fetch(url); let data = await results.json(); return data; }; async function AutoCompleteSelectHandler(event, ui) { let zipCode = await getCities(); $('#nombre').val(nombre[ui.item.value]); $('#num_emergencia').val(num_emergencia[ui.item.value]); $('#prov_salud').val(prov_salud[ui.item.value]); $('#prov_salud_trabj').val(prov_salud_trabj[ui.item.value]); $('#rh').val(rh[ui.item.value]); }; $("#autoSuggest").autocomplete({ source: "{% url 'invitados' %}", select: function(event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); -
How to define and render Django formset for registeting hours spent on a project each day during a month?
I building a Django site where users can register their time spent working on a particular project (Time Report). In the future Time reports will be subject to approval process and possibly sources for calculating invoices to clients, but right now I struggle in setting it up in Django. I want Time Reports to hold multiple project lines and each project line should have as many input fields as many days is in a particular month . This will allow user to register number of hours spent each day on all projects they work on. In addition each project can be presented in more than line (so user can register different tasks within the project separately, e.g. hours spent on project planning vs time spent on development). Projects are defined separately (separate model). I believe that I need following models to support the requirements: from django.db import models class TimeReport(models.Model): employee = models.ForeignKey('employees.Employee', on_delete=models.CASCADE) start_date = models.DateField() #to calculate Time Report month status = models.CharField(max_length=20, default='draft') class ProjectLine(models.Model): time_report = models.ForeignKey('TimeReport', on_delete=models.CASCADE) project = models.ForeignKey('projects.Project', on_delete=models.CASCADE) comment = models.TextField(blank=True, null=True) class ProjectLineDay(models.Model): project_line = models.ForeignKey(ProjectLine, on_delete=models.CASCADE) date = models.DateField() hours = models.DecimalField(max_digits=2, decimal_places=0) I want to achieve something like this … -
NOT NULL constraint failed: store_customer.first_name
NOT NULL constraint failed: store_customer.first_name Request Method: GET Request URL: http://127.0.0.1:8000/signup/ Django Version: 4.1.4 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: store_customer.first_name models.py class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=50) email = models.EmailField(max_length=100) password = models.CharField(max_length=500) def register(self): self.save() def __str__(self): return self.first_name views.py def signup(request): if request == 'GET': return render(request, 'signup.html') else: first_name = request.POST.get('firstname') last_name = request.POST.get('lastname') phone = request.POST.get('phone') email = request.POST.get('email') password = request.POST.get('password') customer = Customer(first_name=first_name, last_name=last_name,phone=phone,email=email,password=password) customer.register() # return HttpResponse( 'signup successful' ) return render(request, 'signup.html') -
How to query model list from one app to another django?
I am facing an issue in django. I have two apps in my project booking and Home, in the booking I have a model called Clinics that has data related to clinics in the home app I am creating a template that shows clinics list I used {% if clinics_list%} to query the data into the model but nothing shows up notes: 1.clinics list has data 2.I imported the clinics model into home app in models.py 3.no issues were detected when running check Tried to create new model(test) in home app that inherit the data from clinics and used {% if test_list %} -
SessionId inside the cookie header slows down request (Django)
I'm learning how to use django sessions and caching. I noticed that once I login, a sessionId is included in the cookie header. I'm using the "@authentication_classes" and "@permission_classes" decorators to validate the session. I'm also using Redis to cache the session, since I dont want to hit the DB everytime. I followed the docs for the django and redis server setup. Once the user log in, the session is written in the cache. The problem is that, even tho the session is inside the cache, the database is hit with each request and it slows down the response time to around 300ms. This is the api I'm using for testing. It does nothing, but it takes 300 ms and it does hit the DB each time I call it. I'm using "never_cache" because I dont want the entire response to be cached. @api_view(["GET"]) @authentication_classes ([SessionAuthentication]) @permission_classes([IsAuthenticated]) @never_cache def test(request, username): return JsonResponse("", safe=False) this is the request I'm making: request If I remove the session autentication decorators, a SessionId is not required anymore to access the api, but the DB is still hit and the response still takes 300ms (there is still the sessionID token inside the cookie header). … -
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.