Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Env vars and Docker differences between dev, staging, and prod
Although my specific example involves Django, Docker, and Heroku, I believe these are pretty general testing/QA questions. I have a dockerized Django app tested in dev with Selenium confirming that my static files are being served correctly from my local folder (EXPECTED_ROOT = '/staticfiles/'). This app is deployed to Heroku and I can see (visually and in the dev tools) that the static files are being pulled in from CloudFront correctly as well. I want to formalize this with the same test I'm using in dev. My first question is related to if/how environment variables are used for tests: Do I add for example EXPECTED_ROOT = 'https://<somehash>.cloudfront.net/' as an env var to Heroku and use it in the Selenium test? Also, to run this test in staging I would need to install Firefox in my Docker image like I do in dev. Perhaps this is ok in staging, but in prod I believe I should be aiming for the the smallest image possible. So the question is about differences between staging and prod: Do I keep Firefox in my staging image, run the tests, and then send to production a replica of that Dockerfile, but now without firefox? Any help … -
Problem when trying to import data from a django directory
I started a application in django with discord.py My modules for discord.py is in same directory where is django application started. Looks like this: My problem is when I want to import a botlogic model, get this error ModuleNotFoundError: No module named 'bot.botlogic'; 'bot' is not a package I've tried every possible way ... and I'm still getting this error How should I proceed? -
Different query results for local server and production server
Without changing the code and updating, the display order of pictures on my production server(django,postgresql,bootstrap,nginx,uwsgi) has changed(see the picture). Before/now I can't reproduce this problem on my local server with same backup/code... In Django ORM I have this result: local: Car.objects.filter(model=1) <QuerySet [<CarImage: 1>, <CarImage: 2>, <CarImage: 3>]> production: Car.objects.filter(model=1) <QuerySet [<CarImage: 3>, <CarImage: 2>, <CarImage: 1>]> Reboot nginx/postgresql didn't help. What could have happened and how to fix it? -
How to add data from my local postgresql database on heroku's postgresql database?
I have a Django project on Heroku. It renders templates, but without any data(that I get from my local postgre database). How can I import data on Heroku database from my local db? -
retrieve data from manytomany field in the sequence of it was saved django
views.py ids when its being saved [19, 18, 20] inv.products.set(pd) ids when its retrieved [18, 19, 20] products = obj.products.all() I want it to be retrieved the objects in the sequence of it was saved -
Django: Foreign Key Error when extending the default USER scheme
I am currently struggling with the extension of the User model with the relation OneToOneField. I have the following model: from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) qualified_name = models.CharField(max_length=50, blank=True) phone_number = models.CharField(max_length=17, blank=True) buyout = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() The following forms: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import RegexValidator, ValidationError from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput( attrs={'class': 'form-control inp-xlf', 'id': 'email', 'placeholder': 'name@example.com'}), required=True) password1 = forms.CharField(widget=forms.PasswordInput, required=False) password2 = forms.CharField(widget=forms.PasswordInput, required=False) def clean(self): cd = self.cleaned_data email_cleaned = cd.get('email') virtual_passwd = User.objects.make_random_password() cd.setdefault("password1", virtual_passwd) cd.setdefault("password2", virtual_passwd) cd.setdefault('username', email_cleaned.split("@")[0]) return cd class Meta: model = User fields = ('email',) class ProfileRegisterForm(forms.ModelForm): qualified_name = forms.CharField(strip=True, widget=forms.TextInput( attrs={'class': 'form-control inp-xlf', 'id': 'name', 'placeholder': 'Enter your name...'})) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits " "allowed.") phone_number = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control inp-xlf', 'id': 'phone', 'placeholder': '(+41) 254 48 95'}), validators=[phone_regex], max_length=17) # validators should be a … -
How to import an object of one app into another app in the same django project?
Codes are given below. users.model.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.db import models # from django.contrib.auth.models import User from PIL import Image from .managers import CustomUserManager from django.contrib import admin from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class CustomUser(AbstractUser): username = None first_name = models.CharField('Name',max_length=200,unique=True) email = models.EmailField(_('email address'), unique=True) registration = models.IntegerField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') blog.model.py from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings from multiselectfield import MultiSelectField from django import forms from django.core.validators import MinValueValidator, MaxValueValidator from PIL import Image DAYS_OF_WEEK = [ (0, ' Monday'), (1, ' Tuesday'), (2, ' Wednesday'), (3, ' Thursday'), (4, ' Friday'), (5, ' Saturday'), (6, ' Sunday'), ] class PostManager(models.Manager): def like_toggle(self, user, post_obj): if user in post_obj.liked.all(): is_liked = False post_obj.liked.remove(user) else: is_liked = True post_obj.liked.add(user) return is_liked class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField('Doctor\'s Name',max_length=100) content = models.CharField('Specialty',max_length=100) chamber = models.CharField('Chamber\'s Name',max_length=200) address = models.CharField('Address',max_length=100, blank=True) fees = models.IntegerField(default=0) days … -
Loginform object has no attribute get_user
I have multiuser app mith usertype a and b i am trying to create login form using class based views making my most of my logic lying in forms.py this how my code looks forms.py class UsertypeALogin(forms.Form): username = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") try: user = models.User.objects.get(username=username) if user.user_a: if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError("Password is wrong.")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError("User does not exist.")) views.py class UsertypeaView(LoginView): template_name = 'login.html' form_class = UsertypeALogin success_url = reverse_lazy("dash") error trace This is the error i am getting Internal Server Error: /app/pm/signin/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, … -
How to create drop down in django dynamically , I tried all ways but I am not getting , literally every way passing from views and from models
views.py @user_passes_test(is_manager) def fetch_set(request, book_id): set_list = [] clicked_book = Book.objects.get(pk=book_id) url = clicked_book.url.split("/")[4].split(".")[0] try: repo = requests.get("https://api.github.com/repos/{}/{}/branches".format(github_user, url), headers = headers, proxies=proxy) repo = json.loads(repo.text) for branch in repo: set_list.append(branch['name']) except Exception as e: messages.error(request, e) context = { 'set': SetCreationForm(initial={'repo_name':url, 'acronym': set_list , \ 'book':clicked_book}), 'list': set_list, 'sets': Set.objects.filter(pk=book_id), 'id': book_id, } if request.method == 'POST': form_1 = SetCreationForm(request.POST) context = {'set': form_1, 'id': book_id} try: if form_1.is_valid(): form_1.save() messages.success(request, 'Set is fetched.') return redirect('booksNsets:sets-page') except Exception as e: # messages.WARNING(request, e) form_1.add_error(None, e) return render(request, 'booksNsets/fetch_repo.html', context) return render(request, 'booksNsets/fetch_repo.html', context) models.py class Set(models.Model): class StatusChoice(models.TextChoices): READY_FOR_CORRECTION = 'RC', _('Ready for Corrrection') UNDER_CORRECTION = 'UC', _('Under Corrrection') READY_FOR_VERIFICATION = 'RV', _('Ready for Verification') UNDER_VERIFICATION = 'UV', _('Under Verification') READY_FOR_FORMATTING = 'RF', _('Ready for Formatting') UNDER_FORMATTING = 'UF', _('Under Formatting') READY_FOR_PROOFREADING = 'RP', _('Ready for Proofreading') UNDER_PROOFREADING = 'UP', _('Under Proofreading') COMPLETED_PROOFREADING = 'CP', _('Completed Proofreading (Mark set as completed for finalize)') COMPLETED = 'CD', _('Completed') book = models.ForeignKey( Book, related_name='sets_of_book', on_delete=models.CASCADE, null=True, ) acronym = models.CharField(max_length=25, unique=True,null=True,blank=True) repo_name = models.CharField(max_length=40) start_page = models.IntegerField() end_page = models.IntegerField() notes = models.TextField(null=True, blank=True) # Cache the completion status of the set is_completed = models.BooleanField(default=False, blank=True) class Meta: ordering = ('acronym', … -
Django: Modifying excel data and downloading a ppt
I am currently facing an issue with deployement: I so far created an app where I am inputing a local path to an excel file than using the sample_code.py (shown bellow) I create a report in pptx in the same folder where the excel file is. To Summarize: I input text into a form the text is my path to the excel file I click a button that runs my sample_code.py script A ppt report is generated Why does this not work when deploying on heroku, and how could I improve it? My views.py files are as follows: from django.shortcuts import render import sys from subprocess import run, PIPE # Create your views here. def button(request): return render(request,'home.html') def external(request): inp=request.POST.get('param') out=run([sys.executable,'E:\\project_deployement\\sample_code.py',inp],shell=False,stdout=PIPE) print(out) return render(request,'home.html',{'data1':out.stdout.decode('utf-8')}) the urls.py from django.urls import path from . import views urlpatterns = [ path('', views.button), path('external/', views.external), ] and the home.html file is as follows <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Work Script</title> </head> <body> <form action="/external/" method="post"> {% csrf_token %} Input Path: <input type="text" name="param" required><br><br> {{ data_external }} <input type="submit" value="Generate Toplines"> </form> </body> </html> the last important step is the sample_code.py from pptx import Presentation from pptx.chart.data import CategoryChartData from pptx.enum.chart … -
Best approach to load specific urls (views) in Django project
I have a Django app that exposes the following views: A,B,C...Z. This app is deployed on MACHINE-1. There was a new business requirement to deploy on MACHINE-2 the same Django app but with a subset of those views, let's say A,B and C. My simple solution was to set a config variable (RUN_ON_MACHINE_2=True for the second case and False for the first case). In conclusion, the urls.py file looks something like below (Please do note that I assimilate the views with paths here just to make it shorter): urlpatterns = [A, B, C, ... Z] # If the env var is set to True then only load a subset of the views if config.RUN_ON_MACHINE_2: urlpatterns = [A, B, C] The tests work fine cause they are always executed for [A,B,C ... Z] which of course include [A, B, C]. However, some new business requirements are asking to make changes on view A. I could implement the changes in view A branching the code by the config.RUN_ON_MACHINE_2 variable but I reached the conclusion it's much cleaner to create a new view, A_ForMachine2, which implements only the needed stuff for MACHINE_2. A_ForMachine2 must have the same interface as view A and must … -
Application error An error occurred in the application and your page could not be served. in heroku
I was trying to deploy my python project on heroku. after successful deployment, when I am starting the app it gives me errors like... Application error An error occurred in the application and your page could not be served. If you are the application owner, **check your logs for details**. You can do this from the Heroku CLI with the command heroku logs --tail after clicking on above-highleted link I got these heroku logs 2010-09-16T15:13:46.677020+00:00 app[web.1]: Processing PostController#list (for 208.39.138.12 at 2010-09-16 15:13:46) [GET] 2010-09-16T15:13:46.677023+00:00 app[web.1]: Rendering template within layouts/application 2010-09-16T15:13:46.677902+00:00 app[web.1]: Rendering post/list 2010-09-16T15:13:46.678990+00:00 app[web.1]: Rendered includes/_header (0.1ms) 2010-09-16T15:13:46.698234+00:00 app[web.1]: Completed in 74ms (View: 31, DB: 40) | 200 OK [http://myapp.heroku.com/] 2010-09-16T15:13:46.723498+00:00 heroku[router]: at=info method=GET path="/posts" host=myapp.herokuapp.com" fwd="204.204.204.204" dyno=web.1 connect=1ms service=18ms status=200 bytes=975 2010-09-16T15:13:47.893472+00:00 app[worker.1]: 2 jobs processed at 16.6761 j/s, 0 failed ... how can resolve this error? -
Angular service invoking Django method to connect to a MongoDB database
I have written a service script in my Angular app that adds consumer form info to a local Json-Server database: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Post } from '../models/post.model'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable() export class DbService { consumersApiUrl = "http://localhost:3000/consumers"; constructor(private httpClient: HttpClient) { } addConsumer(post: Post): Observable<Post> { return this.httpClient.post<Post>(this.consumersApiUrl, post, httpOptions); } } This works perfectly... I have now set up a Django backend and a MongoDB database. In my settings.py file, I have my database connection: DB_NAME = 'mongodb+srv://User2021:TestPassword@cluster0.j9jz1.mongodb.net/test' So, I added a new url and a new method to write the info to my database: @Injectable() export class DbService { consumersApiUrl = "http://localhost:3000/consumers"; consumersMongodbApiUrl = "http://localhost:8000/consumers/"; constructor(private httpClient: HttpClient) { } addConsumer(post: Post): Observable<Post> { return this.httpClient.post<Post>(this.consumersApiUrl, post, httpOptions); } addConsumerMongodb(post: Post): Observable<Post> { return this.httpClient.post<Post>(this.consumersMongodbApiUrl, post, httpOptions); } } In the MongodbApiUrl, consumers is the name of my database collection. My first question: Should the link to a real database (whose connection string and name and collection name I know) be like this or should I somehow include the extra info … -
Django - Simple Task list with checkmarks
I have the following django models: class Tasks(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_changed = models.DateTimeField(auto_now=True, auto_now_add=False) title = models.CharField(verbose_name=_('Title'), max_length=50) content = HTMLField(verbose_name=_('Content'), max_length=8000) class TasksStatus(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_changed = models.DateTimeField(auto_now=True, auto_now_add=False) task = models.ForeignKey(Tasks, on_delete=models.SET_NULL, null=True, related_name="task_status") user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="task_user_id", on_delete=models.CASCADE, verbose_name=_("User")) checked = models.BooleanField(default=False, null=True, verbose_name=_("Checked")) On a template i want to post all tasks which exists and give the user the possibility to checkmark each task. This is already written to the database by a ajax view: class UpdateTaskStatus(LoginRequiredMixin, View): def dispatch(self, request, *args, **kwargs): return super(UpdateTaskStatus, self).dispatch(request, *args, **kwargs) def post(self, request): task_id = request.POST.get("task_id") task_status = request.POST.get("task_status") task = Tasks.objects.get(id=task_id) if (task_status == "0"): task_status = True else: task_status = None object, created = TasksStatus.objects.get_or_create(user=request.user, task=task) object.checked = task_status object.save() tasks = Tasks.objects.all() tasks_completed = TasksStatus.objects.filter(user=request.user, checked=True).count() if (tasks.count() != 0): if (tasks_completed != 0): tasks_completed = int(round((tasks_completed / tasks.count()) * 100, 0)) return JsonResponse({"task_id": task_id, "task_status": task_status,"tasks_completed": tasks_completed, "msg": "Task status updated."}) The view which comes to the template is this one: @login_required def participation_dashboard(request): user = request.user if user.groups.filter(name='teacher').exists(): defaultTagGenerator(user) dt = timezone.now() all_data = request.GET.get('filter', None) days_dict = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: … -
How can I modify radio button field in Django to suit my preference?
models.py: class Person(models.Model): GENDER_SELECT = ( ('f', 'Female'), ('m', 'Male'), ('o', 'Other'), ) TITLE_SELECT = ( ('0', 'Mr.'), ('1', 'Mrs.'), ('2', 'Ms.'), ('3', 'Mast.'), ) title=models.CharField(max_length=5,choices=TITLE_SELECT) name=models.CharField(max_length=100) gender=models.CharField(max_length=11,choices=GENDER_SELECT) forms.py: class PersonForm(ModelForm): class Meta: model=Person fields='__all__' widgets={ 'title': forms.RadioSelect(), 'gender': forms.RadioSelect(), } template: <form action="" method="post"> {% csrf_token %} {{form1.as_p}} <input type="submit" value="Submit"> </form> Output: As you can see, the fields display as verticals whereas I want them horizontal. Plus, I don't want that initial '__________' choice. How can I achieve it? -
I write the full python venv path to be able to run manage.py
I have a problem in the virtual environment with django manage.py I use git bash terminal. and when I activate my venve like this : source explorer/Scripts/activate I successfully activate the environment (explorer text above command line appears) , but still the terminal is pointing to the C:/python37/python.exe path When i run : python manage.py runserver I receive this error : $ python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' but when I type the absolute path to python.exe inside my virtual environment as follows : /explorer/Scripts/python.exe manage.py runserver , it works fine I should be just activating the environment and then typing the python manage.py runserver and it should be working Thanks in advance -
How to display RabbitMQ messages dynamically in HTML (frontend)?
I try to pass variables coming from RabbitMQ and display them in the frontend in my Django project. I am using HTML. I can send the messages and receive them in backend and I can display them in console. But I try to display them in the frontend. How can I do that? functions.py def send_message(text): credentials = pika.PlainCredentials('username', 'pass') parameters = pika.ConnectionParameters('ip', 5672, '/', credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body=text) print(" [x] Sent 'Hello World!'") connection.close() class my_class(): def __init__(self, ...) send_message("Downloading...") self.download_all() ... def download_all(self, ...) ... var = "" arr_length = len(scans) for s in scans: i = 1 var = "Progress = " + str(i) + "/" + str(arr_length) send_message(var) i += 1 views.py def setup_wizard(request): functions.my_class(...) return render(request, 'setup_wizard.html', context) Note: Celery don't work for us. -
How to access query parameter in serializer django rest framework
I am trying to access query parameter in the serializer. I am not sure what I am doing wrong, I tried to follow a few solution. class MyViewSet(viewsets.ModelViewSet): ....... serializer_class = MySerializer def get_serializer_context(self): context = super().get_serializer_context() context['test'] = "something" return context In my Serializer, class MySerializer(serializers.ModelSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): print(self.context['test']) return self.context['test'] I am getting this error, Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'test' Interestingly, I can see it can print the value in console and then the exception. I also tried to directly access the request variable like class MySerializer(serializers.ModelSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['request'].query_params['page'] But its showing the same error Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'request' Any suggestions? Thanks in advance. -
take screenshot from a website and return token screenshot as httpsresponse for download in django
i want to take a screenshot from a website and return token screenshot as https for download. I am using Html2Image lib. i am tring this code: def certification1(request, *args, **kwargs): hti = Html2Image() image = hti.screenshot(url='https://www.python.org', save_as='screenshot.png') response = HttpResponse(image, content_type='png') return response but it return url of saved image. like this enter image description here how can i return token image for download? -
Django case insensitive unique constraint
I want my charField to be case-insensitively unique, but I don't want to store everything lower or upper cased. Existing solutions suggest CITextField or checking for uniqueness in the form, but I thought I should be able to do it with a UniqueConstraint, specially with Django 4.0 UniqueConstrain expressions new feature. But with these code: class Tag(models.Model): title = models.CharField(max_length=24, unique=True) ... class Meta: ordering = ['title'] constraints = [ models.UniqueConstraint( Lower('title'), name='unique case insensitive title' ), ] I get this error when running migrate command. (makemigrations works fine) ... File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 282, in _remake_table self.create_model(new_model) File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 353, in create_model sql, params = self.table_sql(model) File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 202, in table_sql constraints = [constraint.constraint_sql(model, self) for constraint in model._meta.constraints] File "<project_path>/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 202, in <listcomp> constraints = [constraint.constraint_sql(model, self) for constraint in model._meta.constraints] File "<project_path>/venv/lib/python3.8/site-packages/django/db/models/constraints.py", line 188, in constraint_sql fields = [model._meta.get_field(field_name) for field_name in self.fields] File "<project_path>/venv/lib/python3.8/site-packages/django/db/models/constraints.py", line 188, in <listcomp> fields = [model._meta.get_field(field_name) for field_name in self.fields] File "<project_path>/venv/lib/python3.8/site-packages/django/db/models/options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: NewTag has no field named 'Lower(F(title))' What I'm doing wrong? Is it possible to set case-insensitive uniqueness on model level in Django … -
How do I modify djoser account verification system
Here's my custom user model: class Account(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_verif = models.BooleanField(default=) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["firstname", "lastname"] objects = AccountManager() def __str__(self): return self.email @property def is_staff(self): return self.is_superuser @property def is_admin(self): return self.is_superuser def has_perm(*args, **kwargs): return True def has_module_perms(*args, **kwargs): return True So right now I have a standard djoser account verification system. So I'm unable to login with unverified user because the is_active field is set to False. Where and how do I modify the code so that every time I verify an account it checks the is_verif field instead of the is_active and the is_active field is always set to True ? Thank you -
Background-color of AutocompleteSelect field not working
I want to set the background-color of a AutocompleteSelect field. When the page loads, the background-color is set, but will be overwritten immediatelly. Code of the form: class ProjectLineAdminForm(forms.ModelForm): work_type = forms.ModelChoiceField( WorkType.objects.all(), widget=AutocompleteSelect(ProjectLine._meta.get_field('work_type'), admin.site), ) def __init__(self, *args, **kwargs): super(ProjectLineAdminForm, self).__init__(*args, **kwargs) # Set background colors of worktype if self.instance.work_type: if self.instance.work_type.code == 'JOHN': self.fields['work_type'].widget.attrs.update({'style': 'width:110px; background-color: red'}) Code of the Inline class: class ProjectLineInline(admin.TabularInline): model = ProjectLine fields = ("work_type",) form = ProjectLineAdminForm I don't have this problem with other fields. -
Getting SystemError: unknown opcode error with LIME explain_instance
I have dump the LIME LimeTabularExplainer using Jupyter Notebook with dill. While I am able to unpack it but I am not able to use it in the .py file in django app to deploy the model. #unpack the LimeTabularExplainer with open('Resources/CLS_explainer.pkl', 'rb') as f: explainer = dill.load(f) #use the explainer exp = explainer.explain_instance(data_row = ts[0], predict_fn=self.model.predict_proba) And Below is the error: XXX lineno: 72, opcode: 160 Internal Server Error: /customerlead Traceback (most recent call last): File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\repo\test\mio\CustomerLeadScore\views.py", line 28, in post score= obj.predict(data) File "C:\repo\test\mio\Services\CustomerLeadScore.py", line 48, in predict exp = explainer.explain_instance(ts[0], predict_fn) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ lime\lime_tabular.py", line 340, in explain_instance data, inverse = self.__data_inverse(data_row, num_samples) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ lime\lime_tabular.py", line 537, in __data_inverse first_row = self.discretizer.discretize(data_row) File "C:\Users\shash\AppData\Local\Programs\Python\Python36\lib\site-packages\ … -
Create a Model instance when a button is clicked (One-to-Many)
I would like to create a Bid for a project when I click the "Bid" button in my template. How do I go about this. see the below example models.py class Project(models.Model): academic_level = models.CharField(max_length=20, choices=ACADEMICS_LEVEL) type_of_paper = models.CharField(max_length=50, choices=TYPE_OF_PAPER) subject_area = models.CharField(max_length=50, choices=SUBJECT_CHOICES) title = models.CharField(max_length=250) slug = models.SlugField(unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("project_detail", kwargs={ "slug": self.slug }) class Bid(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) made_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) date = models.DateField(auto_now_add=True) def __str__(self): return self.project.title views.py class ProjectDetailView(LoginRequiredMixin, DetailView): model = Project def create_bid(self, request): if request.method =="POST": try: project = self.instance made_by = request.user bid = Bid.objects.create(project=project, made_by=made_by) bid.save() messages.success( request, "Bid sent sucessfully! Wait for feedback from the project owner on the Bids Tab") except: messages.error(request, 'cannot send multiple bids for one project') return render(request, 'users/project_detail.html') the Bid button is found in the project_detail template. How do I check for event and how do I get the current project instance in the Detailview above? Thanks in advance -
Access to XMLHttpRequest at 'http://127.0.0.1:8000/login/' from origin 'http://localhost:3000' has been blocked by CORS policy
full error: Access to XMLHttpRequest at 'http://127.0.0.1:8000/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. settings.py: CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOW_HEADERS = ['*'] INSTALLED_APPS = [ 'django_debugger', 'django_extensions', 'corsheaders', 'rest_framework', 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', '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', ] in react (frontend side): function Login(){ const [login,setLogin] = useState({ email: '', password:'' }); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ e.preventDefault(); axios.post(' http://127.0.0.1:8000/login/',login, {withCredentials:true}) } my authentication method is using sessions, I am not sure how to fix this CORS problem