Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use the field "email" as "username" in django?
Hello everyone I am new to django and I am creating a project where I created a database with a table "tblusuarios" and managed to insert the necessary data such as name, surname, email, password, however, when I go to make the login I am using the field "mail" as username, but so far fails to make the login. Any advice you can offer me? User model: class TblUsuarios(AbstractBaseUser, models.Model): nombre = models.CharField(max_length=80) apellidos = models.CharField(max_length=80, blank=True, null=True) correo = models.CharField(max_length=80, unique=True) telefono = models.CharField(max_length=11, blank=True, null=True) password = models.CharField(max_length=80) foto = models.ImageField(upload_to='images/') tbl_roles = models.ForeignKey(TblRoles, models.DO_NOTHING, default=1) # object = CustomAccountManager() USERNAME_FIELD = 'correo' #le damos el username por defecto a la tabla REQUIRED_FIELDS=(['nombre']) class Meta: db_table = 'tbl_usuarios' View function: def login_user(request): if request.method == 'POST': correo = request.POST['email'] password = request.POST['password'] user = authenticate(request, username = correo, password = password) print(user) if user is not None: login(request, user) messages.info(request, 'Has ingresado correctamente a la aplicacion!!') return redirect('home') else: messages.error(request, 'Ha ocurrido un error a la hora de iniciar sesion!') return redirect('login') else: context = {} return render(request, 'users/login.html', context) Login form: {% extends "layouts/layout.html" %} {% block content %} {% if user.is_authenticated %} <h2>Ya estas logueado en … -
Model fields won't appear through Django development server. How do I fix it?
I am following the Tech With Tim Django + React tutorial (although naming some variables differently)(https://youtu.be/uhSmgR1hEwg) and ran into a problem with views when running the server. My urls work properly but when I go onto the page I can't find any of my model fields. I am new to Django and VSCode (having mostly only used PyCharm in the past) so it may end up being a very simple solution. Here is my code and directories: Directories models.py: from django.db import models import string import random def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): code = models.CharField(max_length=8, default="", unique=True) host = models.CharField(max_length=50, unique=True) guest_can_pause = models.BooleanField(null=False, default=False) votes_to_skip = models.IntegerField(null=False, default=1) created_at = models.DateTimeField(auto_now_add=True) serializers.py: from rest_framework import serializers from .models import Room class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' urls.py: from django.urls import path from .views import RoomView urlpatterns = [ path('home', RoomView.as_view()), ] views.py: from django.shortcuts import render from rest_framework import generics from .serializers import RoomSerializer from .models import Room class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer urls.py: """URL Configuration The `urlpatterns` list routes URLs to views. For more information please … -
How to filter HTML select tags in django
i am trying to use How to use Q objects to filter complex queries, it works with search type input but not with select tag. when I try to filter a set of an input and two selects it returns an empty QuerySet. image below: Debugger image I have no idea why this happens. There is another way to filter sets of HTML tags? My model tfrom django.db import models from categories.models import Category from choices.stt_choices import STATE_CHOICES from choices.occupation_choices import OCCUPATION_AREA_CHOICES class Vacancy(models.Model): name = models.CharField('Name', max_length=255) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) contact_number = models.PositiveBigIntegerField('Phone number') contact_whatsapp = models.PositiveBigIntegerField('WhatsApp') contact_email = models.EmailField('E-mail') occupation_area = models.CharField( 'Occupation area', max_length=3, choices=OCCUPATION_AREA_CHOICES ) state = models.CharField('State', max_length=2, choices=STATE_CHOICES) city = models.CharField('City', max_length=255) number = models.IntegerField('Vacancies number', default=0) date_posted = models.DateTimeField(auto_now=True) img = models.ImageField( 'Image', upload_to='vacancies_img/%Y/%m/%d', blank=True, null=True ) salary = models.CharField('Salary', max_length=255) about_company = models.TextField('About the company') requirements = models.TextField('Requirements') activities = models.TextField('Activities') benefits = models.TextField('Benefits', blank=True, null=True) schedule = models.TextField('Schedule') def __str__(self) -> str: return self.name My view from vacancies.models import Vacancy from django.views.generic.list import ListView from django.shortcuts import render from django.db.models import Q class VacancyHome(ListView): model = Vacancy template_name = 'vacancies/index.html' context_object_name = 'vacancies' class VacancySearch(VacancyHome): template_name = 'vacancies/search.html' def get_queryset(self): … -
Sending email via Django gives me (_ssl.c:3895) error
It looks like there is a problem with the ssl certificate when trying to send emails using django.core.mail.backends.smtp.EmailBackend. Settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_SSL_CERTFILE = certifi.where() EMAIL_SSL_CA_BUNDLE = certifi.where() The password is an app password I created in my google account. I even tried to use third party services like Elastic Email and SendGrid, but it still gives me an error. Removing the EMAIL_SSL_CERTFILE and EMAIL_SSL_CA_BUNDLE will then give me a (_ssl.c:997) error. views.py @api_view(["POST"]) def signupUser(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py import random from user_api.models import CustomUser from django.contrib.auth.hashers import make_password from django.core.mail import EmailMessage from django.core.mail import send_mail from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['username', 'email', 'password', 'profile_image', 'api_key'] extra_kwargs = {'password': {'write_only': True}, 'id': {'read_only': True}} def update(self, instance, validated_data): instance.username = validated_data['username'] instance.email = validated_data['email'] instance.api_key = validated_data['api_key'] instance.profile_image = validated_data['profile_image'] instance.save() return instance def create(self, validated_data): verification_code = random.randint(100000, 999999) user = CustomUser.objects.create(username=validated_data['username'],email=validated_data['email'], password=make_password(validated_data['password']), verification_code=verification_code) user.set_password(validated_data['password']) user.save() email = EmailMessage( 'Hello', f'This is your verification code : {verification_code}', 'email@gmail.com', [validated_data['email']] ) email.fail_silently=False email.send() return user I … -
handle many html files with React and Django
I have a hybrid django+react implementation. Django renders the initial HTML, then react takes control. However, the URLs are managed by Django. In react, the index.js file is supposed to correspond with one html right? Please correct me if I'm wrong. So, which is the correct approach if I have several HTML files that need react. My index.js file looks like this: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import { EfestoComponent, WorkTimeComponent, AresComponent } from './components/pulseHome'; import { PulseComponent} from "./components/pulseHistory"; import reportWebVitals from './reportWebVitals'; const efestosData = JSON.parse(document.getElementById('efestos-data').textContent); const efesto = ReactDOM.createRoot(document.getElementById('efesto')); const worktime = ReactDOM.createRoot(document.getElementById('worktime')); const ares = ReactDOM.createRoot(document.getElementById('ares')); const pulse = ReactDOM.createRoot(document.getElementById('pulse')); efesto.render( <EfestoComponent objects={efestosData}/> ); worktime.render( <WorkTimeComponent/> ) ares.render( <AresComponent/> ) pulse.render( <PulseComponent/> ) As you can see, the efesto, worktime and ares components belong to 1 js file called pulseHome, it holds the components for a file called pulse_home.html. Then the pulse component lives in a pulseHistory js file which holds the components for a pulse_history.html. When I visit any of the two htmls, it raises the error: Uncaught TypeError: document.getElementById(...) is null of course, since the first elements are not present in the second html, and vice versa. I could … -
Understanding django grafana dashboard
I am trying out django dashboards for grafana. I imported a dashbord from grafana.com. One of the panels looks like below: I am unable get the meaning of the information shown by the graph. Naively, I believe it is meant to show average request latency for the selected duration. But then what does it mean by 50th quantile here? Also what is meant by by (le) here? -
Keyerror in django restframework
Views.py class EventCalenderEventListView(ListAPIView): permission_classes=[AllowAny,] serializer_class = serializer.EventCalenderSerializer def get_queryset(self, *args, **kwargs): data = json.loads(self.request.GET.get('filter')) category = data.get('category') query_list = Event.objects.all().values('start_date').distinct() date_list = [] for i in query_list: for key, value in i.items(): date_list.append(datetime.datetime.strftime(value,'%Y-%m-%d')) datas = [] result = {} for dates in date_list: result[dates]= [] query = Event.objects.filter(start_date=dates).order_by('start_date') for i in query: result[dates].append(i) datas.append(result) result = {} return datas Models.py class Event(BaseFields): name = models.CharField(max_length=250) category = models.ForeignKey(EventCategory,on_delete=models.CASCADE,null=True,blank=True) other_event_category = models.CharField(max_length=250,null=True,blank=True) meeting_link = models.CharField(max_length=250,null=True,blank=True) description = models.TextField(null=True,blank=True) start_date = models.DateField(null=True,blank=True) end_date = models.DateField(null=True,blank=True) serializer.py class EventCalenderSerializer(ModelSerializer): category = SerializerMethodField() status = SerializerMethodField() class Meta: model = Event fields = fields=('id','name','category','start_date','end_date','status') def get_category(self, obj): category = {} if obj.category: category['id'] = obj.category.id category['name'] = obj.category.name return category else: category = "" return category def get_status(self,obj): current_date = datetime.strftime(datetime.today(),'%Y-%m-%d') start_date = datetime.strftime(obj.start_date,'%Y-%m-%d') if obj.end_date is not None: end_date = datetime.strftime(obj.end_date,'%Y-%m-%d') if start_date == end_date and start_date < current_date: return "completed" elif start_date < current_date and end_date < current_date: return "completed" elif start_date < current_date and end_date > current_date: return "progress" elif start_date == current_date: return "progress" else: return "upcoming" else: if start_date < current_date: return "completed" elif start_date == current_date: return "progress" else: return "upcomng" Expecting output: [{'2023-06-01':[{"name":event 1,"start_date":"2023-06-01","end_date":"2023-06-07"}], {'2023-06-01':[{"name":event 2,"start_date":"2023-06-01","end_date":"2023-06-07"}, {"name":event … -
Forms dynamique django
what I want my form to do is that when I select a student, for example, the "input" material disappears and gives way to the "input" sector. Hi, I have a problem that I can't solve, the problem is with the django form, what I want my form to do is that when I select a student, for example, the "input" material disappears and gives way to the "input" sector. I try but I can't help. -
How To stop git accessing my changes made in django project in vscode
I had pushed my django project into github from vscode,later i deactivated my virtual environment,but even after deactivating if i try to make any changes in my project it is asking me to apply local changes to git,how to prevent it?Please Help me To Solve this Issue i deactivated the virtual environment and made changes on my project,but it is still asking me to apply those changes to git.I dont want this changes to be applied to github,how to prevent it? -
JS element returns 'null' when retrieving value from textarea
For my project, I'm submitting a "tweet" form asynchronously, but I'm having trouble retrieving the textarea value to pass into my function and update the UI. The values from the tweet/post are saving to my models (including the tweet) and every other field in (username, user profile picture, tweet image) are displaying properly, but its just the textarea that's causing me problems and not displaying at all. Here is the relevant code for reference. Section of index.html <form id="tweet-form" method="post"> <div class="post-section-row"> <a class="creator" href="{% url 'change_profile' %}"> <img src="{{ user_profile.profile_picture.url }}" class="profile-pic small-post-section" > </a> <!-- Cannot retrieve value from this line --> <textarea id="post-content" name="tweet" placeholder="What's Happening?" oninput="autoExpand(this); checkCharacterCount(this)"></textarea> </div> <!-- To display tweet image preview and delete functionality --> <div id="tweet-picture-preview" style="display: none;"></div> <div class="post-section-row"> <div class="error-message"></div> <div class="tweet-actions"> <label for="picture" title="Upload Picture"> <span class="material-symbols-outlined">photo_library</span> <span class="tooltiptext">Upload Picture</span> <input type="file" id="picture" name="tweet-picture" class="file-input" accept="image/jpeg, image/png, image/gif, image/jpg" onchange="previewTweetImage(event)"> </label> <input type="submit" id="post-button" value="Post"> </div> </div> </form> JS file (code within DOMContentLoaded listener) tweetForm.addEventListener('submit', function(event) { event.preventDefault(); const csrftoken = getCookie('csrftoken'); const formData = new FormData(tweetForm); fetch("/post_tweet/", { method: "POST", body: formData, headers: { 'X-CSRFToken': csrftoken, }, }) .then(response => response.json()) .then(data => { console.log(data.message); // This returns … -
How to serve Files with Django Rest Framework
In my django app I have a "Incidence" model that has several FileField and ImageField. I want to create an endpoint with Django Rest Framework to retrieve the information about an "Incidence" but what I have done so far only retrieves the url of the files. I need to return the files in a format that can be downloaded by the client application like binary data or other suggestion. How can I do it? This is what I have done so far Model Definition: class Incidence(BasicAuditModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) geom = models.PointField(verbose_name=_("Localización"), srid=4326, blank=True, null=True) name = models.CharField(_("Nombre"), max_length=255) incidence_type = models.CharField(_("Tipo incidente"), max_length=50, choices=INCIDENCE_TYPE_CHOICES, default="tipo1") description = models.TextField(_("Descripción"), blank=True, null=True) status = models.CharField(_("Status"), max_length=50, choices=STATUS_CHOICES, default="creado") image1 = models.ImageField(verbose_name=_("Foto 1"), upload_to="incidencia_fotos", null=False, blank=False) image2 = models.ImageField(verbose_name=_("Foto 2"), upload_to="incidencia_fotos", null=False, blank=False) image3 = models.ImageField(verbose_name=_("Foto 3"), upload_to="incidencia_fotos", null=False, blank=False) audio = models.FileField(verbose_name=_("Audio"), upload_to="incidencia_audioa", null=False, blank=False) video = models.FileField(verbose_name=_("Video"), upload_to="incidencia_video", null=False, blank=False) def __str__(self): return self.name class Meta: db_table = 'sini_incidence' managed = True verbose_name = 'Incidencia' verbose_name_plural = 'Incidencias' class BasicAuditModel(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="+", verbose_name=_("Creado por"), null=True, blank=False, on_delete=models.SET_NULL) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="+", verbose_name=_("Modificado por"), null=True, blank=False, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True, verbose_name=_("Fecha creado")) modified = models.DateTimeField(auto_now=True, verbose_name=_("Fecha … -
django connecting to mysql in docker gets "wrong" IP address
I am attempting to connect to a remote mysql db from my dockerized django app. This works as expected: In [2]: pymysql.connect(host='remote-host.com', user='user', password='bogus') Out[2]: OperationalError: (1045, "Access denied for user 'user'@'172.XX.XX.XX' (using password: YES)") In [3]: pymysql.connect(host='remote-host.com', user='user', password='secret') Out[3]: <pymysql.connections.Connection at 0x401ef682b0> But this does not (from within django runserver): File "/usr/local/lib/python3.8/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.8/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) django.db.utils.OperationalError: (1045, "Access denied for user 'user'@'192.168.80.4' (using password: YES)") So somehow the shell-based connection is picking up a 172/ IP address for the client (presumably the docker bridge IP - it doesn't correspond to my laptop's en0 IP at any rate), where the exact same code, exact same connection params within runserver causes the mysql server to see the IP of the docker container. Anyone know what's going on, and more importantly how I can prevent it? Attempted: Well, not really much I can do since I don't have access to modify mysql's accepted host list or how it determines the client IP. Expected: The same IP address to be used in both connections. -
Django: Generating a file on page load and deleting it upon exit
Something I would like to do in my Django app is: every time a user views page A, grab information from my database, generate an image based off this and display it to the user. Since I am regenerating an image each time I view the page, I would like it to be unique to each user and deleted when they leave page A to go to any arbitrary page B (and ideally when they simply click x on the browser too, but if not that's okay). So far I can generate the image file and save it just fine. I have tried a few things unsuccessfully and can't figure out how to go forward. Things I have tried: @receiver(request_finished) @receiver(request_finished) def handle_request_finished(sender, **kwargs): ... clean up files here ... My issue with this one is that it happens too quickly and won't load the picture on page A because it will be deleted already. Using a JavaScript function that activates when leaving the page paired with a function in my views.py In template.html: <script> $(window).on('beforeunload', function () { $.ajax({ url: pageLeaveUrl, // links to page_leave function in views.py type: 'GET', async: false // Ensure the request completes before page … -
Can't specify STATICFILES_DIRS correctly in Django
I'm getting the warning: (staticfiles.W004) The directory 'C:/frontend/build' in the STATICFILES_DIRS setting does not exist. It seems like i'm not able to reference my react build folder correctly, all this happened after trying to move django api folders. Here is what my folders look like: enter image description here And here's how my path related setting look like in my settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "frontend/build")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = "static/" # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" STATICFILES_DIRS = [ os.path.join( BASE_DIR, "/frontend/build") ] I've tried debugging my settings.py, it seems like the BASE_DIR is never set correctly, im not able to understand os.path.join -
Django Admin - Add a tabularInline section referred to another class (without foreign key)
I'm developing a Django Admin interface for a sort of ecommerce. I have some database model linked using foreign key. In Django Admin interface, I want to show a TabularInline section inside Customer page to show me all items buyed by a specific customer but I have a classic error about "foreign key" because Customer model and OrderItems model are not directly linked. class Customer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=150) mobile = models.CharField(max_length=20, blank=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] class Meta: verbose_name = "Account" verbose_name_plural = "Accounts" def email_user(self, subject, message): send_mail( subject, message, 'l@1.com', [self.email], fail_silently=False, ) def __str__(self): return self.email class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") full_name = models.CharField(max_length=50) email = models.EmailField(max_length=254, blank=True) address1 = models.CharField(max_length=250) address2 = models.CharField(max_length=250) city = models.CharField(max_length=100) phone = models.CharField(max_length=100) postal_code = models.CharField(max_length=20) country_code = models.CharField(max_length=4, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) total_paid = models.DecimalField(max_digits=5, decimal_places=2) order_key = models.CharField(max_length=200) payment_option = models.CharField(max_length=200, blank=True) billing_status = models.BooleanField(default=False) class Meta: ordering = ("-created",) def __str__(self): return str(self.created) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey(ToolTable, related_name="order_items", on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, decimal_places=2) … -
Get param on anothe page and edit : Vue-Axios-Django-Python
I would like to retrieve the data passed as a parameter via the route and make one of the modifications, but I can't. This is my Python-Django code # CompanyApi @csrf_exempt def companyApi(request, id=0): if request.method == "GET": companies = Companies.objects.all() # companies = Companies.objects.first() # companies = Companies.objects.order_by("company_id").first() companies_serializer = CompanySerializer(companies, many=True) # companies_serializer = CompanySerializer(companies) return JsonResponse(companies_serializer.data, safe=False) elif request.method == "POST": company_data = JSONParser().parse(request) companies_serializer = CompanySerializer(data=company_data) if companies_serializer.is_valid(): companies_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed to Add", safe=False) elif request.method == "PUT": company_data = JSONParser().parse(request) company = Companies.objects.get(company_id=id) # company = Companies.objects.get(company_id=company_data["company_id"]) companies_serializer = CompanySerializer(company, data=company_data) if companies_serializer.is_valid(): companies_serializer.save() return JsonResponse("Updated Successfully", safe=False) return JsonResponse("Failed to Update") elif request.method == "DELETE": company = Companies.objects.get(company_id=id) company.delete() return JsonResponse("Deleted Successfully", safe=False) This is my code is my CompanyEdit page <script setup> import axios from "axios"; import { computed, ref, onMounted, reactive } from "vue"; import { useRoute } from "vue-router"; import CardBoxModal from "@/components/CardBoxModal_JTO.vue"; import FormField from "@/components/FormField.vue"; import FormControl from "@/components/FormControl.vue"; import BaseButton from "@/components/BaseButton.vue"; import SectionMain from "@/components/SectionMain.vue"; import CardBoxWidget from "@/components/CardBoxWidget.vue"; import CardBox from "@/components/CardBox.vue"; const modalOneActive = ref(false); const form = reactive({ company_id: "", company_name: "", company_email: "", company_phone: "", company_address: "", company_city: "", … -
Django signal when model instance with custom field is deleted?
I've got a custom model field in my Django app: secret = VaultField(max_length=200) This takes the value passed and saves it to HashiCorp Vault and stores the path to it in the database, and retrieves it from Vault when accessing. That's all good, I can use this on many models. But now when I delete an instance of a model it doesn't delete it from Vault. I could add a post delete signal on all models that have the VaultField field, but that seems like a lot of duplicate work. Is there anything to add in the class VaultField(CharField): class? Or maybe a post delete signal just on a field being deleted? -
Django or Javascript/Node: learning times in relation to difficulty?
I've been using Python for years, but always for desktop apps. I know Html, Css and little Javascript, but I've never programmed in backend for websites. I would like to learn Django, but having a look I found it very difficult. Knowing Python well and knowing little about Javascript, does it take less time to learn Django from scratch to carry out projects of medium difficulty, or does it take less time to learn Node.js from scratch with Express? (also considering the time to learn Javascript at least sufficiently) -
Gunicorn not finding module - Django
Im trying to deploy my app to Railway.app website, but it keeps giving this message in deploy logs: ModuleNotFoundError: No module named 'ci_jacaranda' I have done some changes in folder structure and now I cant solve what is wrong with it. Basically I changed the old ci_jacaranda/ folder which contains the settings to configs/. This is my project folder configuration: ci_jacaranda ├───apps │ ├───core //[views and urls] ├───configs (old ci_jacaranda) └───__init__.py └───asgi.py └───settings.py └───urls.py └───wsgi.py ├───static └───templates Inside my settings.py INSTALLED_APPS = [ 'admin_datta.apps.AdminDattaConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.core', 'django_bootstrap5', ] ROOT_URLCONF = 'configs.urls' WSGI_APPLICATION = 'configs.wsgi.application' Inside wsgi.py and asgi.py i changed to configs too import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'configs.settings') application = get_wsgi_application() Manage.py import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'configs.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() My Procfile: web: python manage.py migrate && gunicorn configs.wsgi:application I runs in my windows local machine, but as always: not in the server, the … -
django-python like button
Hi lads I want to add like button to make project. but getting error. Exception Value: Reverse for 'like_recipe' with arguments '('',)' not found. 1 pattern(s) tried: ['add_recipe/like/(?P[0-9]+)/\Z']enter image description here[[enter image description here](https://i.stack.imgur.com/My5IO.png)](https://i.stack.imgur.com/AR7Uy.png) I didn't try anything as I cant understand were i problem -
Enforcing row level permission in Django Models
I am trying to enforce row (object) level permissions in Django, on the model level. All the resources on the web revolve around two possible solutions: Option 1. Passing the request manually to a custom manager with a for_user() method: # manager class EntryManager(models.Manager): def for_user(self, user): return self.get_queryset().filter(owner=user) # model class Entry(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) objects = EntryManager() # usage in views/serializers/forms/admin/... Entry.objects.for_user(request.user) Option 2: Using threading.local() variables to store the request/user in the middleware, and than access them in the model. Examples: https://github.com/benrobster/django-threadlocals https://github.com/Alir3z4/django-crequest https://www.viget.com/articles/multi-tenancy-in-django/ I don't like option 1, because it relies on a developer calling a for_user() method, which can be often forgotten. There are a lot of people on the internet that don't like option 2, because of the usage of threadlocals and also because of a Django philosophy that models should be request-unaware. I am coming from a framework such as Laravel which allows access to the Request and User at all levels, so I am puzzled why this is a no-no in Django. I did take a look at django-guardian as well, but the module seems quite complex, and no easy way to filter out all objects linked to a user. Also … -
How to style grouped checkboxes from CheckboxSelectMultiple in django with crispy_form
Here is my form: class MyForm(forms.ModelForm): foo = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'flat'})) class Meta: model = MyModel exclude = ['bar', 'baz'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choices = ( ('Groupe1', ( (1, 'Item1'), (2, 'Item2'), )), ('Groupe2', ( (1, 'Item1'), (2, 'Item2'), )), ) self.fields["foo"].choices = choices self.helper = FormHelper(self) self.helper.form_id = 'myform_id' self.helper.form_class = 'myform_class' self.helper.form_method = 'GET' self.helper.use_custom_control = True self.helper.label_class = 'font-weight-bold' Once rendered, I would like to change the style of the group labels. But I don't know how to access it. When I inspect my form, I see the structure looks like this: <form> <div class="form-group"> <div class="controls"> <strong>Groupe1</strong> <div class="checkbox"> <label class="" for="id_actes_select_0_0"> <div class="icheckbox_flat-green" style="position: relative;"> <input type="checkbox" name="foo" value="Item1" class="flat" id="id_actes_select_0_0"> </div> Item1 </label> </div> ... </div> </div> </form> Group labels are wrapped in strong tags. I would like to style them in css. How to do it with crispy_form ? -
Subtract two quantities value from two different class model in Django
I am trying to do a subtraction from Add_Purchase model to Received_Payment check how many payment received against selected User PK and check if payment not received 100% remaining payment show in HTML form can you please confirm me any one which function use in views.py file I'll share our model here according to above given question thanks. class Add_Purchase(models.Model): date_of_purcahse = models.DateField() supplier_info = models.ForeignKey(add_supplier, on_delete=models.CASCADE) product_type = models.ForeignKey(Product_Type, on_delete=models.CASCADE) product_item = models.ForeignKey(Product_Item, on_delete=models.CASCADE) product_price = models.CharField(max_length=100) product_qty = models.CharField(max_length=100) bill_num = models.CharField(max_length=100) def __str__(self): return self.supplier_info class Received_Payment(models.Model): monthly_inst = models.DecimalField(max_digits=10, decimal_places=2, null=True) client_name = models.ForeignKey(Add_Buyer, on_delete=models.CASCADE) item_payment_received = models.ForeignKey(Cridet_Sale, on_delete=models.CASCADE) payment_date = models.DateField() slip_number = models.CharField(max_length=50) def __str__(self): return str(self.payment_date) -
Permission denied: mod_wsgi, when using mod_wsgi with apache2 and pyenv
I was trying to deploy django app using mod_wsgi (version=4.9.4), apache2 and pyenv, also created the python virtual-env using pyenv, here is the apache configuration used <VirtualHost *:80> ServerName dev.<domain>.com WSGIDaemonProcess dev.<domain>.com python-home=<path><to><pyenv-virtualenv> python-path=<projectdir> WSGIProcessGroup dev.<domain>.com WSGIApplicationGroup %{GLOBAL} ErrorLog "${APACHE_LOG_DIR}/timesheet_internal.log" CustomLog "${APACHE_LOG_DIR}/timesheet_internal.log" common LogLevel Warn Alias /static /var/www/<projectpath>/static <Directory /var/www/<projectpath>/static> Require all granted </Directory> Alias /.well-known/acme-challenge/ "/var/www/<projectpath>/.well-known/acme-challenge/" <Directory "/var/www/<projectpath>/"> AllowOverride None Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec Require method GET POST DELETE PATCH OPTIONS </Directory> WSGIScriptAlias / /var/www/<path>/wsgi.py <Directory "/var/www/<path>/wsgi.py"> Require all granted </Directory> </VirtualHost> <pyenv-virtualenv>/bin/python manage.py --collectstatic --no-input --clear and <pyenv-virtualenv>/bin/python manage.py migrate --no-input both these commands are executed successfully and the app also worked in my local, but on deploying in ec2(ubuntu 22.04) the application ran into following errors [Mon Jun 12 14:17:51.520596 2023] [wsgi:warn] [pid 1224676:tid 140062563575680] (13)Permission denied: mod_wsgi (pid=1224676): Unable to stat Python home /home/ubuntu/.pyenv/versions/3.11.3/envs/timesheet_env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/.pyenv/versions/3.11.3/envs/timesheet_env' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir … -
facing Python Package version issues
I am trying to run an old django project which was build on python 3.6. currently I am using venv with python 3.10 & below is my list of dependencies mysqlclient==1.3.13 arrow==0.12.1 gunicorn==19.9.0 pymongo==3.7.1 pytrends==4.4.0 Faker==0.9.1 newsapi-python==0.2.3 progressbar2==3.38.0 newspaper3k==0.2.7 requests==2.17.1 beautifulsoup4==4.6.3 selenium==3.14.0 lxml==4.2.5 pandas==0.23.4 langdetect==1.0.7 pyjwt==1.6.4 msgpack==0.5.6 bpython==0.17.1 xlsxWriter==1.1.1 feedparser==5.2.1 querystring-parser==1.2.3 google_images_download==2.5.0 xlrd==1.2.0 algoliasearch==2.0.4 PyMySQL==0.9.3 fuzzywuzzy==0.17.0 python-levenshtein==0.12.0 firebase-admin==4.3.0 can any one suggest me package version for smooth project run?