Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django create a new column in an already existing table
I'm using Django 3.0.5 and I am trying to create a new column in a table. The table looks like this: class VacationModel(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) emp_id = models.IntegerField() email = models.EmailField() from_date = models.DateField() to_date = models.DateField() reason = models.TextField() time_sent = models.DateTimeField("date sent") req_approved = models.BooleanField(default=False, null=True) req_denied = models.BooleanField(default=False, null=True) # daysoff_given = models.IntegerField() def __str__(self): return self.emp_id The new column would be daysoff_given. I tried adding this column and after running python manage.py makemigrations I got an error saying django.db.utils.OperationalError: no such column I tried following some other answers and I deleted the migrations made inside the mirgations folder, without deleting the __init__.py file. After running makemigrations again the same error occured and then I deleted the whole model and made a new model. I think my database is broken, but is there an actual way to avoid this, since it has already happened 2 times. Whenever I try to add a new column, it always throws that error and I cannot continue. How can I fix this? -
Django and Vue.js with Axios: 500 internal server error with post request
I am currently making a TODO app with Vue.js and Django (Vanilla Django not the Django REST framework) and I am using AXIOS to perform the request post/get, the get request works perfectly fine and I am able to fetch data, but when I create a new task and submit it to the Django I get this error on the front end: xhr.js:185 POST http://127.0.0.1:8000/tasks/ 500 (Internal Server Error) createError.js:17 Uncaught (in promise) Error: Request failed with status code 500 at createError (createError.js:17) at settle (settle.js:18) at XMLHttpRequest.handleLoad (xhr.js:69) Here is my code in the front end HTML and javascript: function sendRequest(url, methode, data) { const r = axios({ url: url, method: methode, data: data, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', headers: { 'X-Requested-With': 'XMLHttpRequest' //to allow django recognizing this request as ajax request } }); return r; } const app = new Vue({ el: '#app', data: { task: '', tasks: [], }, //use hooks to call the function at the event of page loaded created() { const vue_instance_ref = this; const r = sendRequest('', 'get') .then(function (response) { vue_instance_ref.tasks = response.data.tasks; }); }, methods: { createNewTask() { const vue_instance_ref = this; const formData = new FormData(); formData.append('title', this.task); sendRequest('', 'post', formData) … -
Can not seem to get Django to display the correct content in web-pages
I am creating a web-app using Django. I want the app to have 4 sections, the homepage, Culture, Entertainment, and Technology. The home page would display all the articles while the other pages would display articles that relate to that category. I created a class for all the articles. Some of the class objects are: category, title, by, summary. In views.py, for the homepage, I created a function to display all the articles in random order. I then created 3 more functions that display the articles by category. The problem is, the home page is the only one that works properly. I made links to all 4 pages in my navbar, all four links go back to my homepage instead of the category pages i made. The function I made for the homepage or all_blogs is the only one that works. When I modify it so it only displays articles in a certain category it works, but when I try to make a new function and new page, it only displays the homepage. views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def all_blogs(request): blogs = Blog.objects.order_by('?') return render(request, 'blog/all_blogs.html', {'blogs': blogs}) def Entertainment(request): blogs = Blog.objects.exclude(category='Technology, Culture') return … -
How can i imperilment multiple step form in django, for example Application Form that has 3 steps like first of personal information
model.py i create my Application model with many fields class Application(models.Model): family_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) other_name = models.CharField(max_length=100) district = models.CharField(max_length=100) pobox = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=30) date_of_birth = models.DateField(null=True) place_of_birth = models.DateField(null=True) gender = models.CharField(max_length=6, choices=GENDER) status = models.CharField(max_length=50, choices=M_STATUS) spouse = models.CharField(max_length=100) nationality = models.CharField(max_length=100) father_name = models.CharField(max_length=150) mather_name = models.CharField(max_length=150) mother_language = models.CharField(max_length=150) other_language = models.CharField(max_length=150) religion = models.CharField(max_length=250) employee_address = models.CharField(max_length=250) hearth_status = models.CharField(max_length=50, choices=HEARTH) there are other fields that i didn't include here form.py i have my 3 forms from above Model class Form1(forms.ModelForm): class Meta: model = Application fields=('family_name','first_name','other_name','district','pobox','email','phone','date_of_birth','place_of_birth','gender','status','spouse','nationality','father_name', 'mather_name','mother_language','other_language','religion','employee_address','hearth_status','comment') class Form2(forms.ModelForm): class Meta: model = Application fields = ('school_fees_sponsor','sponsor_address','sponsor_letter','program','course', 'training_site','name_of_secondary_school','year_began','year_of_completion') class Form3(forms.ModelForm): class Meta: model = Application fields=('name_of_institution','started_year','end_year','re_name','re_phone','re_name_two','re_phone_two','note', 'all_documents') my views.py class UndergraduateApplicationFormView(SessionWizardView): instance = None template_name = 'application/ugraduate.html' form_list=[Form1,Form2,Form3] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'applicarion_files')) def done(self, form_list, **kwargs): return render(self.request, 'application/ugraduate.html', { 'form_data': [form.cleaned_data for form in form_list] }) def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) my html template this is a html file tha i creeated my own {{ wizard.management_form }} {% if wizard.form.forms %} {% for form in wizard.form.forms %} {{ wizard.form.management_form }} {{ form }} {% endfor %} … -
Django : get value from different table and calculate fields
I would like to get 'weight' from 'Product' and calculate 'total_weight=weight*quantity' as shown on html class Product(models.Model): code = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=64) weight = models.DecimalField(max_digits=20, decimal_places=2) class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) def total(self): return round(self.price * self.quantity, 2) And the html : {% for product in object.invoiceitem_set.all %} <tr> <td>{{product.product}}</td> <td>{{product.price}}</td> <td>{{product.quantity}}</td> <td>{{product.total}}</td> <td>{{product.weight}}</td> <td>{{product.total_weight}}</td> </tr> -
Adding custom views to django admin interface to add more functionality
So I'm trying to extend Django's admin interface. I want to add more functionality to it without overriding it completely. I have a view in my app which returns a list of users who have registered in a particular time frame (last 24 hours e.t.c.) and also a toggle button which can deactivate or activate the users at will. The thing is, I initially created it with it's own template and everything, but now I don't want to reinvent the wheel and just want to add it to django's own admin interface. I've checked multiple solutions online, however they all involve using models, whereas I'm not trying to use any particular model. I just want to be able to pass context from my views to the template. So I'm trying to have something like in the image above, but in the django admin interface. Like just in a div below the other fields. Below are the views that display the data and the toggle buttons @staff_member_required def custom_admin(request): if request.user.is_staff: users_in_past_24_hours = CustomUser.objects.filter(created_at__gt=time_threshold(24)) users_in_past_week = CustomUser.objects.filter(created_at__gt=time_threshold(168)) users_in_past_month = CustomUser.objects.filter(created_at__gt=time_threshold(730)) context = {"users_in_past_24_hours": users_in_past_24_hours, "users_in_past_week": users_in_past_week, "users_in_past_month": users_in_past_month} else: return redirect('unauthorized') return render(request, 'admin_dashboard.html', context) @require_POST @staff_member_required def toggle_user_status_true(request, user_id): user … -
Django Custom UserAdmin wrong change user password URL
I'm doing some refactors on an application written in Django and I've noticed that the URL to change the password for the desired user is wrong in the link. Instead of /admin/myapp/user/<:id>/password/ the url on the link is /admin/myapp/user/<:id>/change/password/. If I go to /admin/myapp/user/<:id>/password/ I can see the password reset screen for django admin but the link to click is wrong. This is my class: @admin.register(User) class UserAdmin(UserAdmin): inlines = [CarInline, ] search_fields = ['id', 'email'] fieldsets = ( (None, {'fields': ('email', 'password')}), ( 'Personal info', { 'fields': ( 'full_name', 'date_of_birth', 'gender', ) }, ), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ) add_fieldsets = ((None, {'classes': ('wide',), 'fields': ('email', 'password1', 'password2')}),) form = UserUpdateForm add_form = UserCreateForm list_display = ('id', 'email') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') ordering = ('email',) -
when error are thrown by these validators they are shown in cmd but i want them to be shown beside the form fields itself
from django.db import models from django.core.validators import DecimalValidator,MinValueValidator,MaxValueValidator from django.contrib.auth import get_user_model as user_model import datetime User = user_model() # Create your models here. class BasicInfo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="basicinfo", null=True) date = models.DateField(default=datetime.date.today) temp = models.DecimalField( max_digits = 4 ,decimal_places=1,validators=[DecimalValidator(max_digits = 4 ,decimal_places=1)]) headache = models.BooleanField() running_nose = models.BooleanField() sore_throat = models.BooleanField() loss_smell_taste = models.BooleanField() difficulty_breathing = models.BooleanField() oxygen_level = models.IntegerField(validators=[MaxValueValidator(0,"To low value"),MaxValueValidator(1000,"Might be incorrect")]) travel = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) if any error is given by these validators error is shown in the cmd but I want it to show beside the input field how to I pass these error there -
I'm making a user login and Registration app in Django and need help in message module of django
I am making an application using Django auth. when the user gets register or activated I want to show success and error messages. Views.py from django.shortcuts import render, redirect from django.views.generic import View from validate_email import validate_email from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError # from django.contrib.auth.tokens import PasswordResetTokenGenerator from .utils import generate_token from django.core.mail import EmailMessage from django.conf import settings from django.contrib.auth import authenticate, login, logout # Create your views here. from django.contrib import messages class RegistrationView(View): def get(self, request): return render(request, 'login/register.html') def post(self, request): data = request.POST global messages context = { 'data': data, 'has_error':False} username=request.POST.get('username') email=request.POST.get('email') password1=request.POST.get('password1') password2=request.POST.get('password2') if not validate_email(email): messages.add_message(self.request, messages.INFO, 'Pls, Enter valid email.') context['has_error']=True # if len(password1) < 8: # messages.add_message(request,messages.ERROR, 'Password should b 8 inch long, bro') # context['has_error']=True if password1 != password2: messages.add_message(self.request, messages.ERROR, 'Password dont match.') context['has_error']=True try: if User.objects.get(email=email): messages.add_message(self.request, messages.ERROR, 'Email is alredy registered') context['has_error'] = True except Exception as identifier: pass try: if User.objects.get(username=username): messages.add_message(self.request, messages.ERROR, 'Username is taken') context['has_error'] = True except Exception as identifier: pass if context['has_error']: return render(request, 'login/register.html', context) else: user = User.objects.create_user(username=username, email=email) user.set_password(password1) user.is_active … -
Django 2.2 with 2 domains
I have a Django web app and 2 domains. I want to use these domains for the different Django apps. For example: firstdomain.com -> stuff app seconddomain.com -> customer app Is it possible? How should urls.py looks like? -
can I get screen resolution request in django?
I wanna change some of the following line based on the resolution of the screen(device): {% if forloop.counter|divisibleby:3 and not forloop.last %} no javascript, just django. so getting the "screen.width" in the view.py for example, would be helpful. -
Django, how to calculate the total of each line
I would like to calculate 'total' for each line. with the following code, it shows only last line total, not each line total. this in case we have many products in this invoice. need total of each product (price*quantity) class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) def total(self): items = self.invoiceitem_set.all() for item in items: amount_due = (item.price * item.quantity) return round(amount_due, 2) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) HTML {% for product in object.invoiceitem_set.all %} <tr> <td>{{product.product}}</td> <td>{{product.price}}</td> <td>{{product.quantity}}</td> <td>{{object.total}}</td> </tr> -
How to solve this modelForm Django error?
I'm trying to follow this tutorial about Django on youtube, and I'm writting exactly the same way the teacher writes on the video, but my code is throwing errors that I can't identify. I've already made some search about it, I've made all the imports apparently correctly and I really don't know where to look. My code: from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User # When form.save() runs, its going to be saved on the User model fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(Modelform): class Meta: model = Profile fields = ['image'] It returns the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File … -
PyChram Django project Interpreter not adding up
My Django projects started showing the error bash-3.2$ python manage.py runserver File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax After googling and trying different approaches, I reinstall PyCharm. Now When I open an old project that was working. the Interpreter shows an old script file name instead of project Venv. I tried to edit and add the interpreter. If I choose to add new, it says the folder is not empty. If I try to create new, it shows total empty. -
Django : object.filter().value_list() problem
I am trying to render data related to a model attribute which is inputed in the frontend by the user in a django view. Unfortunately, I keep running in the same problem here is my view: @method_decorator(login_required, name='dispatch') class SupplierPage(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) context = {} #if query and request.method == 'GET': Supplier = supplier.objects.filter(supplier = query) supplier_items = Item.objects.filter(fournisseur = query) queryset = Item.objects.filter(fournisseur = query) table = SupplierData(queryset) labels = Item.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] print(labels) default_items = Item.objects.filter(fournisseur = query).values_list('number_of_sales', flat=True)[:10] print(default_items) label1s = Item.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] default_item1s = Item.objects.filter(fournisseur = query).values_list('number_of_orders_placed', flat=True)[:10] context.update({'Supplier' : Supplier, 'supplier_items' : supplier_items, 'table': table, 'labels':labels, 'default_items':default_items,'label1s':label1s, 'default_item1s':default_item1s}) return render(request, 'Supplier.html',context) now in my log, I get this: DEBUG (0.001) SELECT "dashboard_item"."reference", "dashboard_item"."fournisseur", "dashboard_item"."demand_30_jours", "dashboard_item"."stock_reel", "dashboard_item"."en_cours_de_reception", "dashboard_$ DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG (0.001) SELECT "dashboard_item"."reference" FROM "dashboard_item" WHERE "dashboard_item"."fournisseur" IS NULL LIMIT 10; args=() DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG (0.001) SELECT "dashboard_item"."number_of_sales" FROM "dashboard_item" WHERE "dashboard_item"."fournisseur" IS NULL LIMIT 10; args=() DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG (0.001) SELECT "dashboard_item"."reference" FROM "dashboard_item" WHERE "dashboard_item"."fournisseur" IS NULL LIMIT 10; args=() DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG … -
Django Axios GET Request not allowed
I'm trying to make a simple, unauthorized request from axios to Django, but it's not working, with result "501 unauthorized". The thing is, this request doesn't require that user is signed in, so I don't know exactly what's the error. my django view: @api_view() @renderer_classes([JSONRenderer]) def main_enterprise_name(request): return Response({'name': Enterprise.objects.get(main_instance=True).name}) The Django URL: path('api/enterprise/main/', views.main_enterprise_name, name='main_name'), Axios config: axios.defaults.xsrfCookieName = "attcsrf" axios.defaults.xsrfHeaderName = "X-CSRFATTTOKEN" const api = axios.create({ baseURL: "http://127.0.0.1:8000", }); api.interceptors.request.use(function (config) { const token = getToken(); if (token){ config.headers.Authorization = 'Bearer '.concat(String(token)); } return config; }); When I make this request in browser, it works just fine, but with axios this fails with unauthorized. -
How can I add a tag <a href=""> to a send email using django and mailgun? [closed]
Using django and mailgun, my email its ok, but the link in my html when it send doesn't look like I need (I mean just to click on a word and redirect to the link), in the email just see the word without a link when you hover it. I don't know what else I can do for this. I have this: def send_confirmation_email(self, user): """ Send account verification link to the created user """ verification_token = self.generate_token(user) subject = 'Confirm your account to make some swaps' from_email = 'ssss <noreply@ssss.com>' html_body = render_to_string( 'verify_account.html', { 'token': verification_token, 'user': user } ) mail = EmailMultiAlternatives(subject, html_body, from_email, [user.email]) mail.attach_alternative(html_body, "text/html") mail.send() and my html: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>Welcome {{ user.username }}</p> <p> Before you start using this app we need you to do one last thing. Please visit the following <a href="localhost:8000/verify/{{ token }}">link</a> </p> </p> </body> </html> Thanks a lot. -
Properly escaping strings in raw Django SQL query
Really the root of the problem is poor database design going back to long before I started here, but that problem isn't going to be resolved by the end of the day or even the end of the week. Thus, I need to find a better way to handle the following to get a feature added. I'm forced to deviate away from the Django ORM because I need to build a raw SQL query due to having to write logic around the FROM <table>. We've elected to go this route instead of updating the models.py a couple times a year with the new tables that are added. There are numerous areas starting here where the Django documentation says "Do not use string formatting on raw queries or quote placeholders in your SQL strings!" If I write the query like this: cursor.execute(""" SELECT * \ FROM agg_data_%s \ WHERE dataview = %s \ ORDER BY sortorder """, [tbl, data_view]) It adds single quotes around tbl, which obviously causes an issue, but will correctly construct the WHERE clause surrounded in single quotes. Doing this, will not put single quotes around tbl, but will force you to put single quotes around the WHERE … -
Cannot pass variables to Django 3 method from HTML template
I am a Django newbie who is trying convert and existing HTML based website to Django 3. The only complex piece of this page is a call to a Django method that uses the django.core.mail package and everything works, but, I am trying to pull some data off of the HTML template and pass it to this method. The method works only it sends a blank email. I am trying to pass contact information that the end user would fill out on the form. If I hard code the data into the method it works. I have tried passing the data through urls.py, but, everything I try fails to even parse when I call the method. When I use a request.GET.get everything seems to work, just no data. I was hoping to use some similar to JQuery like the following in the method. name = str(request.GET.get('Name:', '').strip()) email = str(request.GET.get('Email:', '').strip()) msg1 = str(request.GET.get('Message:', '').strip()) with the fields being in the HTML form. I am going to include some of the relevant configuration items below. urls.py from django.urls import path from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from . import views app_name = 'willdoit' urlpatterns … -
Is there a method to restrict going back in selected views?
I have a question, Adding or inserting an X record redirects me to another page, all good so far. But in Chrome I can go back with the <- button, which makes it difficult for me, because I can make infinite records with different clear IDs, now my question is: How not to regress in different points of view? It is good to go back, but not in the views of: insert, update or delete. There is a Javascript method for Chrome, but it didn't work very well for me. Is there a method? enter link description here I am working with Django 3.1, Python 3.8, Postgresql Your help would be greatly appreciated. -
Order elements in html Django
So I have this elements {% for chat in content %} <a class="clearfix" href="{% if chat.second == request.user %}{{ chat.first }}{% elif chat.second != request.user %}{{ chat.second }}{% endif %}"> <div class="ProfileImg" style="background-image: url({% if chat.second == request.user %}{{ chat.first.profile.avatar.url }}{% elif chat.second != request.user %}{{ chat.second.profile.avatar.url }}{% endif %})"></div> <div class="about"> <div class="name">{% if chat.second == request.user %}{{ chat.first }}{% elif chat.second != request.user %}{{ chat.second }}{% endif %}</div> <input type="hidden" class="number" value="{% if chat.second != request.user %}{{ chat.first_thread_notification }}{% elif chat.second == request.user %}{{ chat.second_thread_notification }}{% endif %}"> <div class="status"> {% if chat.second != request.user %} {% if chat.first_thread_notification >= 1 %}{{ chat.first_thread_notification }} msg sin leer <i class="fa fa-circle notification"></i>{% else %}chat activo{% endif %} {% elif chat.second == request.user %} {% if chat.second_thread_notification >= 1 %}{{ chat.second_thread_notification }} msg sin leer <i class="fa fa-circle notification"></i>{% else %}chat activo{% endif %} {% endif %} </div> </div> </a> {% endfor %} in the input class='number' val there is a value that contain a number, an especific number of each chat. what I need is to order the elements depending on the value of the number I try this but that doesnt work // order the chat values $( … -
Getting error: not enough values to unpack (expected 2, got 1)
I have a project where the user can register and then he is getting a confirmation email. The project is working fine on my local computer but after I deployed the project on pythonanywhere I am getting this error when a client tries to register:not enough values to unpack (expected 2, got 1) Also the email is not send but I can see him on the admin panel. I hope you can help. views.py def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('home') return redirect('/login') else: return HttpResponse('Activation link is invalid!') def confirmation_phase(request): return render(request, 'confirm_email.html') def signup(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Hesabınızı Aktifleştirin.' message = render_to_string('acc_activate_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('/confirmation_phase') else: form = RegisterForm() return render(request, 'signup.html', {'form': form}) traceback Environment: Request Method: POST Request URL: http://itucampus.pythonanywhere.com/signup/ Django Version: 3.1 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
How to make a python script run when ever I browser refresh is performed in django
I currently have a views.py file in my django application this is it def index(request): greeting = "Welcome to FireCDN" description1 = "You are not currently logged in." description2 = "Login / Signup now to enjoy the benefits of a CDN but this time free" description3 = "Hold up 🤚, you need to login in before before you can access this page" description4 = "Error occurred!" time = timezone.now() try: import httplib except: import http.client as httplib def check_internet_connection(url="www.google.com", timeout=4): connection = httplib.HTTPConnection(url, timeout=timeout) try: conn.request("HEAD", "/") conn.close() return True except Exception as e: print(e) return False connect = check_internet_connection() context = { "greeting": greeting, "description1": description1, "description2": description2, "description3": description3, "description4": description4, "time": time, "connection": connect, } return render(request, 'home/index.html', context) The thing is when I reload the browser the following template gets renders {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8"> <meta name="description" content="This is a free alternative to CloudFare and beats the competitors out there like jsDeliv, made with ♥, by LokotamaTheMastermind"> <meta name="author" content="LokotamaTheMastermind"></meta> <meta name="application-name" content="FireCDN"> <meta name="keywords" content="cdn cloudfare firecdn fire free jsdelivr github storage online"> <link rel="icon" href="{% static 'shared/img/favicon.jfif' %}"> <title>FireCDN - {% block … -
Can't create a custom User model in django
I have a custom passwordless user model built in django 1.11. user model looks like this class User(models.Model): email = models.EmailField(primary_key=True) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' is_anonymous = False is_authenticated = True It's a custom user model and depends on a custom auth backend, given like this class PasswordlessAuthenticationBackend(): def authenticate(self, uid): try: token = Token.objects.get(uid=uid) return User.objects.get(email=token.email) except User.DoesNotExist: return User.objects.create(email=token.email) except Token.DoesNotExist: return None def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None The auth is registered and working fine. The token is just this class Token(models.Model): email = models.EmailField() uid = models.CharField(default=uuid.uuid4, max_length=40) The problem is, when I try to call auth.login in my TestCase, it always throws this error: ValueError: The following fields do not exist in this model or are m2m fields: last_login What are m2m fields? How and where do I specify this last_login? -
forms.ValidationError bug?
this is my third day in django and I'm working on my validation form and i came across this weird bug where my validation form didn't do anything so here's the code class RegisterForm(forms.ModelForm): email = forms.EmailField(label="E-Mail", error_messages={'required': 'Please enter your name'}) class Meta: model = LowUser fields =['fullname', 'email', 'password', 'bio'] widgets = { 'password' : forms.PasswordInput() } def clean_fullname(self): data = self.cleaned_data.get("fullname") if 'ab' in data: raise forms.ValidationError('invalid') else: return data if i input "ac" to the fullname it works perfectly fine it adds the input to the database. But if i input "ab" it didn't do anything it doesn't give me any errors nor add the input to my database. And I'm pretty sure my forms.ValidationError is bugging because if i change my raise forms.ValidationError('invalid') to raise NameError('Test') like this def clean_fullname(self): data = self.cleaned_data.get("fullname") if 'ab' in data: raise NameError('Test') else: return data and i input "ab". It works completely fine and it gave me this page and I'm using django 2.1.5 if you're wondering i would appreciate any help thank you in advance