Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrate a django project to new server with already exists postgresql database of anotehr django project
I have 2 django apps on separate servers. Both have completely different models The database name of app1 is xxxx1 The database name of app2 is xxxx2 how to migrate xxxx2 to server1 without damage anything ? -
Languages Selection process [closed]
I want to be a smart front ended web developer. In future, I will shift in full stack development journey. Now, I want to enter market place because I need to earn money immediately. I have completed following languages: HTML CSS vanila js Bootstrap So please suggest me, in this step which language I should shift now so that I can start earning. Thanks to all my lovely friends. I am looking for a market place to earn money. -
Django ORM for custom python function
I have following two models class Membership(models.BaseModel): user = models.ForeignKey(User) package = models.ForeignKey(Package, on_delete=models.PROTECT, blank=True, null=True, related_name="package_membersips") benefit_end = models.DateField() benefit_start = models.DateField() class Package(models.BaseModel): name = models.CharField(max_length=40) description = models.CharField(max_length=200, null=True, blank=True) class PackageTier(BaseModel): package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package_tiers') min_members = models.IntegerField() max_members = models.IntegerField() retail_price = models.DecimalField(max_digits=5, decimal_places=2) wholesale_price = models.DecimalField(max_digits=5, decimal_places=2) The wholesale_price and retail_price calculation consists of some logic, that is difficult to perform using ORM: def get_package_price(package_instance): count = package_instance.package_memberships.count() tier = package_instance.package_tiers.filter( min_members__lte=count + 1, max_members__gte=count + 1 ).first() if not tier: tier = package_instance.package_tiers.order_by('id').first() return tier.retail_price if tier else 0 def get_package_wholesale_price(package_instance): count = package_instance.package_memberships.count() tier = package_instance.package_tiers.filter( min_members__lte=count, max_members__gte=count ).first() if not tier: tier = package_instance.package_tiers.order_by('id').first() return tier.wholesale_price if tier else 0 These are business logic and I need to aggregate the result based on the year basis. # sample response: {"data": [ { "year": 2021, "commission": 1.0 }, { "year": 2022, "commission": 8.2 }, { "year": 2023, "commission": 11.0 }, ]} Is there any way that I can use get_package_price and get_package_wholesale_price inside Django ORM ? I used following ORM to get membership for each year: Membership.objects.all().annotate(year=ExtractYear('benefit_start')).values('year').order_by('year') The custom function need to be called in this ORM. -
Why is caching not improving the performance in my django view?
I am trying to improve performance of a view by caching a given linear algebra expression and its corresponding result. I am using memcached and pymemcache but for some reason theres no performance gain. Heres my view: @api_view(['POST']) @login_required(login_url='/api/login/') @csrf_exempt def compute_lalg_expression(request): form = LinearAlgebraExpForm(request.POST) if form.is_valid(): new_expr = form.save(commit=False) data_expr = form.cleaned_data data_expr = data_expr['exp'] exp_hash = hashlib.md5(data_expr.encode()).hexdigest() alg_exp = cache.get(exp_hash) if not alg_exp: parsed_exp = parser.parse(data_expr) eval_data = evaluate(parsed_exp) expr_model = LinearAlgebraExpression(exp=eval_data) expr_model.save() create_action(request.user, 'computed an expression', expr_model) serializer = LinearAlgebraExpSerializer(expr_model) cache.set(exp_hash, serializer.data) return Response(serializer.data) return Response(alg_exp) And here is the client I am testing it with. I am testing it by removing the lines associated with caching above so I am removing exp_hash, alg_exp and so on so I remove the if statement that checks whether alg_exp is true or false and i remove cache_set. Anyways heres my client import aiohttp import asyncio import time async def make_request(session): url = 'http://127.0.0.1:8000/api/compute/' payload = {'exp': exp + '*' + exp2} # Replace with your POST data async with session.post(url, data=payload, auth=aiohttp.BasicAuth('jobpink', 'hello123')) as response: return await response.text() async def main(): # Adjust these values as needed num_requests = 5000 # Number of requests to send concurrency = 10 … -
'403 Forbidden: CSRF verification failed. Request aborted.' in Django deployment with Railway
I am trying to deploy a Django app on Railway. I have {% csrf_token %} in each form, yet am still getting the '403 Forbidden: CSRF verification failed. Request aborted.' each time. I have inspected the page to verify the hidden csrf is being created (it is) and that the cookie exists (it does). Here is my settings.py and my full repo for reference """ Django settings for rpisite project. """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'rpiapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'rpisite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'rpisite.wsgi.application' # Database import dj_database_url DATABASE_URL = os.environ['DATABASE_URL'] DATABASES = { "default" : dj_database_url.config(default=DATABASE_URL, conn_max_age=1800) } # … -
Django forms.ModelForm Failed lookup for key [form]
I'm getting error with forms.ModelForm Failed lookup for key or empty form, any suggestions, please? VariableDoesNotExist at /timesheets/ Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <django.views.generic.base.TemplateView object at 0x00000201195B1F50>}] forms.py from django import forms from .models import TimeSheet from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row class TimeSheetForm(forms.ModelForm): class Meta: model = TimeSheet fields = "__all__" def __init__(self, *args, **kwargs): super(TimeSheetForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'AddNewEntry' self.helper.form_method = 'post' self.helper.layout = Layout( Row('date_time_start', 'date_time_end', 'project_code', 'user', 'milage', 'project_type', 'activities', 'expenses', Submit('submit', 'Submit') ) ) add_timesheet.html {% load crispy_forms_tags %} <div id="timesheet-form-container" class="d-none d-flex flex-row flex-nowrap justify-content-between"> <form id="timesheet-form" method="post" class="w-100"> {% csrf_token %} {% crispy form %} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> views.py from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.shortcuts import render from .forms import TimeSheetForm from .models import TimeSheet def add_timesheet(request): if request.method == 'POST': form = TimeSheetForm(request.POST) if form.is_valid(): form.save() return {'success': True} else: form = TimeSheetForm() return render(request, 'timesheets/add_timesheet.html', {'form': form}) timesheets/urls.py from django.urls import path from django.views.generic import TemplateView from . import views urlpatterns = [ path('', TemplateView.as_view( template_name='timesheets/timesheets_main.html'), name='timesheets'), path('add_timesheet/', views.add_timesheet, name='add_timesheet'), path('get_timesheets/', views.get_timesheets, name='get_timesheets'), ] I`m tried … -
Creating new filter in django
I would like to use a range filter in django. Something like this : <br> <table> <thead> <tr> <th>Revenue streams</th> <th>Units</th> <th>Description</th> {% for num in 2022|range:2027 %} <th>{{ num }}</th> {% endfor %} </tr> </thead> So I have created a templatetags folder in my app and added file custom-filters.py that contains : from django import template register = template.Library() @register.filter def range(start, end): return range(start, end + 1) but the page returns : Any idea of what is mising? -
Paygreen integration with Django
I am a little bit lost with the integration of PayGreen payment gateway. I can't search nothing in Google, someone have one link or some example. I need to make via API with Python, I don't have another language knowledge, for the JS integration I mean. If someone can help me, it would be great. I am lost. I have done integrations of Stripe or Monei following instructions and tutorials, but I can't find nothing for PayGreen and I need this one. -
Django cors headers not working with POST requests
My stack is: axios for the javascript client, apache2 reverse proxy, gunicorn, django. I have setup the django-cors-headers plugin. I am able to perform GET requests to the django application. However, when I try to perform a POST query, I have a CORS error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://[...]/move_item. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://[...]/move_item. (Reason: CORS request did not succeed). Status code: (null) How is it possible that changing the http method breaks? I have not set a value to the CORS_ALLOW_METHODS from django-cors-headers. Even if I explicitly do (CORS_ALLOW_METHODS = ("DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT",)), the error persists. My apache config is straightforward. <VirtualHost *:443> ServerName [...] ProxyPass /.well-known ! ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ ProxyPreserveHost On SSLEngine on SSLCertificateFile /etc/letsencrypt/live/[...]/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/[...]/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/[...]/fullchain.pem Alias /.well-known /home/cliclock.justescape.fr/www/.well-known/ <Directory [...]/www/.well-known> Options FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> LogLevel debug ErrorLog [...]/logs/error.log CustomLog [...]/logs/access.log combined Gunicorn is used with this command gunicorn myapp.wsgi How can I fix the situation? -
Django error: "Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'" [closed]
Estoy en un curso de Django y me siento estancado. Vi varias soluciones, pero sigo sin poder solucionar el problema. Error "Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'" Views.py: from django.urls import reverse_lazy, reverse from django.contrib.auth import get_user_model from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView from django.views.generic import CreateView, DetailView, UpdateView, DeleteView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate from .forms import UserUpdateForm # Devuelve el modelo de usuario requerido User = get_user_model() class RegistroEInincioDeSesion(CreateView): form_class = UserCreationForm template_name = "accounts/signup.html" success_url = reverse_lazy("blog:index") # sobreescribimos el medodo form_valid def form_valid(self, form): # validar y registrar datos response = super().form_valid(form) # obtener los datos validos username = form.cleaned_data.get("username") raw_pw = form.cleaned_data.get("password") # comprobar si la contraseña es correcta (que si, por obvias razones) # y obtener el usuario user = authenticate(username=username, password=raw_pw) # iniciar sesion login(self.request, user) # devolver una respuesta HTTP return response class UserDetail(DetailView): model = User template_name = 'accounts/user_detail.html' class UserUpdate(UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/user_edit.html' # se ejecuta si la actualizacion es exitosa def get_success_url(self): # toma el argumento pk definido en la ruta y redirige a la pagina de detalles # del usuario usando el mismo argumento => user_detail/<int:pk> … -
Why is my Docx converter returning 'None'
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the translated document it cannot be opened. When I inspect the file type I saw it identified as XML and docx and it could be opened and read by MS Word when I changed the extension to docx(But it couldn't be read by any PDF readers). When I used my code python to analyze the file by printing the type and the contents of it I got NoneType and None. A working PDF of the file is found in mysite/mysite folder but the one output by my reConverter function that is sent to the browser is the problem file. I tried manually converting it using: wordObj = win32com.client.Dispatch('Word.Application') docObj = wordObj.Documents.Open(wordFilename) docObj.SaveAs(pdfFilename, FileFormat=wdFormatPDF) docObj.Close() wordObj.Quit() but got a CoInitialization error. My original So I've completely narrowed it down to the reConverter function returning a NoneType. Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage … -
User Based Views
I am working on a project whereby I would like to generate a report which has the ability to have a drop down list of users, such that the data in the report changes depending upon the user being selected. I'm looking at this from an admin perspective. I know how to create such a view for request.user, but I'm not entirely sure how to create the functionality for a drop down list of users and then the output changes. Any thoughts as to how to do this? I do have an example of existing code I can provide to show what I am trying to achieve; however it won't necessarily answer my question. Best, Neil -
Navigation bar icon does not center correctly
In my navigation bar the element of the class "fa fa-address-card" is a dropdown menu, but it doesn't line up correctly next to the other two elements next to it ("fa fa-heart" and "fa fa-shopping-cart"), it sits a little above. How do I make it behave like the other two elements next to it? I'm using boostrap 5.0.2 and Jquery 3.7.0 My HTML: <nav class = "navbar navbar-expand-lg navbar-light bg-white py-4 "> <div class = "container barra_navegacao"> <a class = "navbar-brand d-flex justify-content-between align-items-center order-lg-0" href = "{% url 'home' %}"> <img src = "{% static 'base\img\shopping-bag-icon.png' %}" alt = "site icon"> <span class = "text-uppercase fw-lighter ms-2">Pytudo</span> </a> <div class="search-form d-flex justify-content-center align-items-center flex-grow-1"> <form class="d-flex" action="{% url 'listar_produtos' %}" method="GET"> <input type="text" class="form-control me-2" name="nome" placeholder="O que você procura?"> </form> <div class="dropdown"> <a class="nav-link text-uppercase text-dark dropdown-toggle" href="#" role="button" id="categoriasDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Categorias </a> <ul class="dropdown-menu" aria-labelledby="categoriasDropdown"> {% for categoria in categorias %} <li><a class="dropdown-item" href="#">{{ categoria }}</a></li> {% endfor %} </ul> </div> </div> <div class = "order-lg-2 nav-btns"> <div class="dropdown"> <button type="button" class="btn position-relative dropdown-toggle" id="PainelDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-address-card" aria-hidden="true"></i> </button> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="PainelDropdown"> {% if request.user.is_authenticated %} <li><a href="{% url 'account_logout' … -
Django-Docker: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
First-time docker-user: I recently added a cron job to my Django project and dockerized it. When I run docker-compose up --build, the system builds and runs the cron job, which exits with a code 137 (which is expected, since I'm running locally). When I try to run the cron job manually to troubleshoot methods of lowering the cron's CPU usage, I am met with: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known This error is odd to me, since everything is fine upon build, but it seems like the command no longer knows what the database is outside of the build even with the project running. Also, does this mean my cron job can't execute in its designated time The following are links to similar posts that may be helpful to others with a similar issue, but have not solved my problem: Why this error, docker operational error (django project)? How to fix this error django.db.utils.OperationalError: could not translate host name "db" to address . Docker Docker-compose with django could not translate host name "db" to address: Name or service not known Docker run, after docker-compose build could not translate host name “db” to … -
Assign model permissions of Model1 to a Model2 in django using django guardians
I am using Django Guardians in my project and it works fine so far, but there is some problem: I need to assign permissions from model1 to the instance of the model2. Real example: The shop has some contracts and the shop owner wants to assign his employees permission to change contract fields (e.g. field1). So we have 3 models now: Shop, Contract, and User, and each model has it's own defined permissions per field like: can_change_field1, ... All permissions that employee can have must be related to the Shop model because when a shop owner assign contract permissions to his employee (to change field1 in contract in shop1), it mustn't affect another shop (So user will not be able to change that field e.g. field1 in shop2,...). 1st solution can be: to create all permissions in shop model (for all models: Contract,...). But it seems kinda of messy to me. What do you think? Please, Can you suggest some nice solution to this problem? -
angular display status_text differently on local vs prod
I have a simple login method in angular that calls the service API and I want to display the error to the alert service. However, the response parsed from the server is not same local vs prod in cloud environment. this.authService .login(this.f.username.value, this.f.password.value) .pipe(first()) .subscribe({ next: () => { // get return url from query parameters or default to home page this.alertService.success("Login successful"); const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; this.router.navigateByUrl(returnUrl); }, error: (error) => { this.alertService.error(error); this.loading = false; }, }); this works well locally the response shows { "headers": { "normalizedNames": {}, "lazyUpdate": null }, "status": 401, "statusText": "Unauthorized", "url": "http://localhost:4200/api/v1/token/", "ok": false, "name": "HttpErrorResponse", "message": "Http failure response for http://localhost:4200/api/v1/token/: 401 Unauthorized", "error": { "type": "client_error", "errors": [ { "code": "no_active_account", "detail": "No active account found with the given credentials", "attr": null } ] } however, in prod it is giving me different statusText somehow { "headers": { "normalizedNames": {}, "lazyUpdate": null }, "status": 401, "statusText": "OK", "url": "https://remoteurl-cloudrun-app/api/v1/token/", "ok": false, "name": "HttpErrorResponse", "message": "Http failure response for https://simpledc-tkbsnc6b4a-uc.a.run.app/api/v1/token/: 401 OK", "error": { "type": "client_error", "errors": [ { "code": "no_active_account", "detail": "No active account found with the given credentials", "attr": null } ] } I can't understand why. … -
__str__ returned non-string (type dict)
class Order(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) total = models.FloatField() drop = models.CharField(max_length=50) complete = models.BooleanField(default=False) discount = models.ForeignKey(Discount, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.to_dict() def to_dict(self): return { 'id': self.id, 'user': self.user, 'date': self.date, 'total': self.total, 'drop': self.drop, 'discount': self.discount, 'complete': self.complete } So this is my order class and im trying to print my order. But I get this error TypeError: __str__ returned non-string (type dict) How can I fix this and stil return a dict? Also i tried wrapping it in a str() which did not help -
Bootstrap 5 with centering issues on Django template
The second element of my cart, which in this case is a nike product, is not aligned and centered like the others. I would like to know where the problem is in centralizing this element so that it behaves like the others. when I inspect the page, this element shows wrong padding and margin sizes. I'm using bootstrap 5.0.2 and Jquery-3.7.0, My HTML: <!DOCTYPE html> <html lang="pt-BR"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PYTudo</title> </head> <body> <!-- navbar --> <nav class = "navbar navbar-expand-lg navbar-light bg-white py-4 "> <div class = "container barra_navegacao"> <a class = "navbar-brand d-flex justify-content-between align-items-center order-lg-0" href = "/"> <img src = "/static/base/img/shopping-bag-icon.png" alt = "site icon"> <span class = "text-uppercase fw-lighter ms-2">Pytudo</span> </a> <div class="search-form d-flex justify-content-center align-items-center flex-grow-1"> <form class="d-flex" action="/produtos/listar_produtos/" method="GET"> <input type="text" class="form-control me-2" name="nome" placeholder="O que você procura?"> </form> <div class="dropdown"> <a class="nav-link text-uppercase text-dark dropdown-toggle" href="#" role="button" id="categoriasDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Categorias </a> <ul class="dropdown-menu" aria-labelledby="categoriasDropdown"> </ul> </div> </div> <div class = "order-lg-2 nav-btns"> <div class="dropdown"> <button type="button" class="btn position-relative dropdown-toggle" id="PainelDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-address-card" aria-hidden="true"></i> </button> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="PainelDropdown"> <li><a href="/accounts/login/">Entrar</a></li> <li><a href="/gestao/painel_controle/">Painel de controle</a></li> </ul> </div> <button type = … -
Django Admin Dropdown Filtering: Show Exam Class Related Students in Student Assign Field
I'm working on a school management system using Django, and I'm currently facing an issue with customizing the behavior of dropdown fields in the Django admin interface. In my application, I have models for managing exams, students, and student results. Each exam is assigned to a subject, which is associated with a specific class and section. When I'm creating a student result entry in the admin panel, I want to ensure that the student_assign field only displays students who are part of the same class as the exam subject. More specifically, when I select an ExamAssign in the admin form, I want the related student_assign dropdown field to dynamically filter and display only those students who are associated with the same class as the selected exam subject. If I Select Class 10 here I want only to show the related class students (not only the section) here. I've tried implementing this using a custom admin form and overriding the __init__ method, but I'm encountering issues with getting the related students based on the selected exam's subject. Could anyone guide me through the correct way to achieve this functionality? I'd greatly appreciate any help or advice on how to properly filter … -
I cannot host Django app with docker-compose, and boilerplates request
I wish some guidelines, or maybe a tutorial, to develop a good Django app based on examples, its models and practices. At some point, I stumble on some in complexity exponential increment due many Django features. So far, I have been able to construct this app: https://github.com/trouchet/tarzan. I even wrote a Medium blog post based on ChatGPT. However, there is complexity on the way. Example: Command run docker compose up with docker-compose.yaml content as below and Dockerfile as on repository exits the container with logs as follows: version: '3' services: # Your Django application web: image: tarzan-image:latest container_name: tarzan-box ports: - "8000:8000" depends_on: - db db: image: postgres:13 container_name: tarzan-memory env_file: - .env ports: - "5432:5432" Traceback (most recent call last): File "manage.py", line 5, in <module> import django ModuleNotFoundError: No module named 'django' Traceback (most recent call last): File "manage.py", line 5, in <module> import django ModuleNotFoundError: No module named 'django' -
Make Django DB Transaction Idempotent on an External Call
I'm using a Django DB with a Postgres backend. Each user has a "balance" associated with their DB object, which is their current funds in the system. They can cash out the balance via gift cards, which is done by sending a POST request to Amazon's API. I perform two operations when the cash out their balance: Update the DB to set their balance to 0 Send a POST request to the Amazon API to generate a gift card for their balance If only one of these operations happen, that's very bad, for obvious reasons. I know you can use Transactions to make sure multiple database operations happen atomically -- is there a way to do something similar with a DB operation and an external call like this? -
Sending an email with Django is not working
I'm new in Python & Django and I'm training myself with this wonderful language. I'm trying to send an email when an user is signing, the user is correctly created but no mail send. I use one of my mail to test, here is the code: models.py class MyUserManager(BaseUserManager): def create_user(self, email, password=None, company_name=None, company_id=None): if not email: raise ValueError('Vous devez entrer un email.') user = self.model( email=self.normalize_email(email), company_name=company_name.upper(), company_id=company_id.upper() ) user.set_password(password) send_mail('réussi', 'enfin', None, ['checkthegeek@protonmail.com']) user.save() return user views.py def signup(request): form_class = UserRegistrationForm if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() return redirect("main:home") else: form = UserRegistrationForm() return render(request, 'registration/signup.html', {'form': form}) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '***@gmail.com' EMAIL_HOST_PASSWORD = 'mhzvptzlqtylqzsn' SERVER_EMAIL = '***@gmail.com' DEFAULT_FROM_EMAIL = '***@gmail.com' What am I missing ? Thanks for your help. send an email with django. -
Can i make one static files that used in all apps?
Im using Django and i want to make a **static **file that can used in all apps templates this is the tree of my project C:. ├───AISystem │ ├───static │ │ ├───css │ │ ├───imgs │ │ │ ├───myfont │ │ │ └───result │ │ └───js │ └───__pycache__ ├───Text2imageApp │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───text2voiceApp │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ └───texttohandwriting ├───migrations │ └───__pycache__ ├───templates └───__pycache__ as you can see i put my css file in the (../AISystem/static/css/main_style.css) and i want to use it in other apps templates. my setting.py file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'AISystem\static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') template file in this dir : (Text2imageApp/templates/main.html) {% load static %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>IntelliHub</title> <link rel="main_style" href="i dont know what to write here"> how i can link main.html with the main_style.css? -
Being a Developer is hard...lets talk about it [closed]
What do you do when you're frustrated? I know its not a coding question, but we're so into the computer we forget sometimes that we're humans sitting down and typing for hours. What do you do when you just have so much to do in your project and the first thing on that long list is giving you issues and you feel like throwing yourself out a window. how do you get through it? How do you try and figure it out? Just want to hear your opinions -
imported some function from c++ dll to python using ctypes, but some functions doesn't work as expected
so i'm developing a backend using django and i got an image processing step for which i'm using a private c++ .dll developed by my company. i'm using ctypes to load the .dll file and managed to make some of the imported functions work properly. but some functions ("fr_get_fire_img" in this case) doesn't work as expected. i don't know if i am specifying the function's argtypes or the function restype incorrectly and need some guide, thanks in advance! here's the function signature in c#: [DllImport(DLL_NAME)] public static extern IntPtr fr_get_fire_img(byte instance, ref short W, ref short H, ref short step); here's the python code where i'm trying to use the imported function: import ctypes from ctypes import c_char_p as char_pointer from ctypes import c_short as short from ctypes import c_void_p as int_pointer zero = char_pointer(0) w = short(0) h = short(0) step = short(0) fire_dll.fr_get_fire_img.restype = int_pointer source = fire_dll.fr_get_fire_img(zero, w, h, step) print(source, type(source)) and finally this is the error i'm getting from ctypes: Traceback (most recent call last): File "PATH OF PYTHON FILE", line 44, in <module> source = fire_dll.fr_get_fire_img(zero, w, h, step) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ OSError: exception: access violation writing 0x0000000000000000 i couldn't find any reference online so i'd …