Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django Custom Field with Fernet Cannot Decrypt
This is my custom field that I call in a model. Migrations succeed and I'm able to insert an encrypted value into the data table. However, it will not decrypt. Here's the custom field class: class SecureString(CharField): """Custom Encrypted Field""" #kdf = X963KDF(algorithm=hashes.SHA256(), # length=32, #sharedinfo=None, # backend=default_backend()) key = bytes(settings.FERNET_KEY,'utf-8') f = Fernet(key) def from_db_value(self, value, expression, connection): return self.f.decrypt(str.encode(value)) def get_prep_value(self, value): return self.f.encrypt(bytes(value, 'utf-8')) And here is the error when trying to retrieve values from the data table: File /usr/local/lib/python3.8/site-packages/IPython/core/formatters.py:706, in PlainTextFormatter.__call__(self, obj) 699 stream = StringIO() 700 printer = pretty.RepresentationPrinter(stream, self.verbose, 701 self.max_width, self.newline, 702 max_seq_length=self.max_seq_length, 703 singleton_pprinters=self.singleton_printers, 704 type_pprinters=self.type_printers, 705 deferred_pprinters=self.deferred_printers) --> 706 printer.pretty(obj) 707 printer.flush() 708 return stream.getvalue() File /usr/local/lib/python3.8/site-packages/IPython/lib/pretty.py:410, in RepresentationPrinter.pretty(self, obj) 407 return meth(obj, self, cycle) 408 if cls is not object \ 409 and callable(cls.__dict__.get('__repr__')): --> 410 return _repr_pprint(obj, self, cycle) 412 return _default_pprint(obj, self, cycle) 413 finally: File /usr/local/lib/python3.8/site-packages/IPython/lib/pretty.py:778, in _repr_pprint(obj, p, cycle) 776 """A pprint that just redirects to the normal repr function.""" 777 # Find newlines and replace them with p.break_() --> 778 output = repr(obj) 779 lines = output.splitlines() 780 with p.group(): File /usr/local/lib/python3.8/site-packages/django/db/models/query.py:370, in QuerySet.__repr__(self) 369 def __repr__(self): --> 370 data = list(self[: REPR_OUTPUT_SIZE + 1]) … -
Customize Form for User adding/editing in admin Wagtail
I have customized user profiles in Wagtail by adding fields (drm, cpm). How can I modify the form, or more specifically, the values in the form's lists based on the currently logged-in user and their permissions? Hello everyone, I have customized user profiles in Wagtail by adding fields (drm, cpm). How can I modify the form, or more specifically, the values in the form's lists based on the currently logged-in user and their permissions? For example, let's say you have extended the user profile model in Wagtail to include custom fields drm and cpm, and you want to dynamically populate a choice field in a form based on the user's role or permissions. Here's how you might approach this: # in models.py from django.db import models from wagtail.users.models import UserProfile class CustomUserProfile(UserProfile): drm = models.CharField(max_length=50, blank=True, null=True) cpm = models.CharField(max_length=50, blank=True, null=True) Next, you can create a custom form for a Wagtail admin page and override the form fields based on the user's profile: # in admin.py from wagtail.contrib.modeladmin.options import ModelAdmin from wagtail.contrib.modeladmin.views import CreateView, EditView from wagtail.contrib.modeladmin.helpers import PermissionHelper from .models import CustomUserProfile class CustomUserProfilePermissionHelper(PermissionHelper): def user_can_edit_obj(self, user, obj): # Customize this method to check if the user has … -
Trying To setup MultiTenancy in Django using database schemas
I am trying to setup multitenancy in Django using multiple Databases. Initially my first database was "succesfully" migrated. But then I created another database, tried migration and got this** error !!** ModuleNotFoundError: No module named 'routers' Because of this error I deleted my project and created a new one. Now even the first Database give this error I have routers package installed as well. I don't know how to fix this. Screenshot of error Please help !!!! This is for my Uni project !!!! ........................................................................ -
Django - Form Not Saving Image on Form Submission
For my current ModelForm for some reason all the fields get updated on a form submission as they are supposed to except for the image field. What’s the best solution to get this working with my current code? I think it’s because request.FILES isn’t getting handled correctly in my views.py file but not 100% sure. Side note: If i upload an image to the Django backend, the image field updates how it’s supposed to. This is only happening when there’s a form submission on the front end when the image field isn’t getting updated. Below is my code. Screenshots attached of the Django admin backend and the front end where the data is being displayed. Any help is gladly appreciated. Thanks! views.py def account_view_myaccount_edit(request): user_profile = User_Info.objects.filter(user=request.user) instance = User_Info.objects.get(user=request.user) user = request.user if request.method == 'POST': form = HomeForm(request.POST, request.FILES, instance=instance) if form.is_valid(): listing_instance = form.save(commit=False) listing_instance.user = user listing_instance.save() return redirect('myaccount_edit') # Redirect to a success page else: form = HomeForm(instance=instance) context = { 'user_profile': user_profile, 'form': form } return render(request, 'myaccount_edit.html', context) models.py class User_Info(models.Model): id = models.IntegerField(primary_key=True, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL,blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) address = models.CharField(max_length=100) city … -
Votes not being counted in django poll
I'm working through the polls tutorial and I want to be able to have multiple questions on the same page and only press the vote button once. Right now, I don't get any errors but it is not counting the votes. I tried to write unittests to trace the error but am not sure how to replicate an html form either. In the future, I would also like other types of questions (like free text) mixed in and am not sure if I should create another app for the other question type or modify the Question and Choice in models.py. I saw some other examples but people warned against hardcoding questions/choices in the html but my form should end up remaining pretty static. models.py from django.db import models import datetime from django.utils import timezone class Question(models.Model): def __str__(self): return self.question_text question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.shortcuts import render, get_object_or_404, … -
Error while migrating from a SQLite database to a MySQL database in a Django Project
I'm trying to migrate all of the data in my SQLite database to a new MySQL database, to do so, I've been following the following steps (which I found in another question What's the best way to migrate a Django DB from SQLite to MySQL?). I've tried the following approaches: First I run a py manage.py dumpdata > datadump.json. Then, I change my settings.py file to use my new MySQL database. After that, I run a py manage.py migrate --run-syncdb And then I exclude contentType data by: python manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() And Lastly, I try to run a py manage.py loaddata datadump.json I've also tried to just run py manage.py dumpdata --exclude contenttypes --exclude auth.permission --exclude sessions --indent 2 > dump.json, followed by py manage.py loaddata dump.json. The problem is that, in both approaches, in the very last step, when I'm trying to load the data into my new database, the following error is raised: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I've been trying to investigate what could prevent or fix this error but nothing has come up. Any help is appreciated. Thanks in advance. In case this … -
Djoser verify or activate email address when reset or changed
I was unable to Verfiy a user when user changed their email address serializers.py from djoser.serializers import UserCreateSerializer as BaseUserCreateSerializer, UserSerializer as BaseUserSerializer class UserCreateSerializer(BaseUserCreateSerializer): class Meta(BaseUserCreateSerializer.Meta): fields = ['id', 'name', 'email', 'password'] class UserSerializer(BaseUserSerializer): class Meta(BaseUserSerializer.Meta): fields = ['id', 'name', 'email'] class UserDeleteSerializer(Base...): pass settings.py DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'SEND_CONFIRMATION_EMAIL': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SERIALIZERS': { ... }, 'PERMISSIONS': { ... } } models.py from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): ... user = self.model(email=email, **extra_fields) ... def create_user(self, email, password=None, **extra_fields): ... return self._create_user(email, password, **extra_fields) def create_superuser(self, email=None, password=None, **extra_fields): ... return self._create_user(email, password, **extra_fields) class User(AbstractUser): name = models.CharField(max_length=150) email = models.EmailField(unique=True) soft_deleted = models.BooleanField(default=False) username = None first_name = None last_name = None EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] objects = UserManager() def get_full_name(self): full_name = "%s" % (self.name) return full_name.strip() def get_short_name(self): return self.name I want to add some functionality when user POST requested to base_url/auth/users/reset_email/ with email=registed_email@gmail.com we received a email with a link having uid and token in a link once user POST … -
MS auth - Django adding an 'http' to my URI at callback
I am building a PoC for web applications using Django with Microsoft Authentication. The app in my Azure Directory is all setup, my Site domain matches the URI expected in the app and an initial call was made successfully. BUT, for reasons unknown to me, django sends an additional 'http://'. the error it gives me I am no Django or Azure expert. Here are some snippets. settings.py: AUTHENTICATION_BACKENDS = [ 'microsoft_auth.backends.MicrosoftAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend' ] MICROSOFT_AUTH_CLIENT_ID = env('MS_APP_ID') #the keys are correct in the .env, triple-checked MICROSOFT_AUTH_CLIENT_SECRET = env('MS_SECRET_KEY') MICROSOFT_AUTH_TENANT_ID = env('MS_TENANT_ID') MICROSOFT_AUTH_LOGIN_TYPE = 'ma' MS_AUTH_REDIRECT_URI = 'http://localhost:5000' #matches the redirect URI in the Azure app accounts/urls.py: urlpatterns = [ path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), path('', RedirectView.as_view(url='index'), name='home'), path('accounts/', include('django.contrib.auth.urls')), path('index/', index, name='index'), ] I tried changing the domain url in the 'admin/sites/sites' and in the settings.py variable MS_AUTH*_*REDIRECT_URI, removing the 'http://' prefix, but to no avail.