Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetching current user in Django FormView
Im building a listings site and each user is linked to a company. Before the user can post a new listing it must have bought credits. If there are no credits the FormView should show a template with a notification of 0 credits, however if credits > 0 then the actual form with should appear. Im struggling in trying to fetch the current user in the FormView class itself. I know that it can be done via the form_valid method user = self.request.user, but that would mean that the user must first fill the whole form and submit it after checking if he has enough credits. Im tryiing to figure out how to perform the check before the form has been filled and submitted. I couldnt find any resources how can I do something like this: class CreateAd(LoginRequiredMixin, FormView): if currents_user.ad_credits > 0: template_name = 'ads/ad_form.html' form_class = AdForm success_url = '/' else: template_name = 'ads/not_enough_credits.html' form_class = AdForm success_url = '/' -
Django: request.is_ajax() returning False
I'm trying to make the search of 'patient' Dynamic with ajax. Every thing in my code is working well but I don't know wy request.is_ajax() always returns false. I search about it but I didn't find the solution yet, right now my code do the search but with changing of the url and that mean the js dosen't work. I don't know how work well with javascript in Django so please help me. This is my views.py: def index(request): ctx = {} url_parameter = request.GET.get("q") if url_parameter: queryset = Patient.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name')) patients = queryset.filter(fullname__icontains=url_parameter) #patients = Patient.objects.filter(name__icontains=url_parameter) else: patients = Patient.objects.all() ctx["patients"] = patients print(request.is_ajax()) if request.is_ajax(): html = render_to_string(template_name="patient/patients-results-partial.html",context={"patients": patients}) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, "patient/index.html", context=ctx) index.html: {% extends 'base.html' %} {% block content %} <div class="col-md-6 offset-md-4"> {# part added for dynamic search#} {# icon and search-box #} <form class="form-inline"> <i id="search-icon" class="fas fa-search" aria-hidden="true"></i> <input id="patient-input" class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search" aria-label="Search" name="q"> </form> {# artist-list section #} <div id="replaceable-content" class="col-6"> {% include 'patient/patients-results-partial.html' %} </div> </div> <div class="col-md-6 offset-md-4"> <a href="{% url 'register_patient' %}" class="btn btn-primary">Ajouter un nouveau patient</a> </div> <div class="col-md-6 offset-md-4"> <div class="table-responsive"> <table class="table table-striped … -
Serialization in Django Rest Framework
In Django Rest Framework. I have a program that lets a user post some data. I serialize this input, but with this input I also save it to another model and create some default values for it and return them to the user. But I am getting slightly confused on whether or not I should serialize that model too. class FileExample(APIView): def post(self, request, format=None): serializer = FileExampleSerializer(data=request.data) if serializer.is_valid(): serializer.save() other_model = OtherModel(name=request.FILES['file'].name, type_obj='file') other_model.save() return Response({'url': other_model.url}, status=status.HTTP_201_CREATED) For example OtherModel is my other model object that I create which creates some default values. But I was looking at nested serializers but this did not achieve what I wanted, as it threw an error that it was missing a required value. My question is my code will work like this, but should I be serializing OtherModel as well? -
Django get uploaded images
I have created a model to get images and upload them to upload folder and the link is available in database. But when I call the image in my index.html it does not work settings.py USERFILES_DIRS = os.path.join(BASE_DIR, 'upload') STATIC_URL = '/static/' STATICFILES_DIRS = [ USERFILES_DIRS, os.path.join(BASE_DIR, 'static'), ] models.py class MyShoes(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=50) price = models.DecimalField(max_digits=10, decimal_places=2) display_picture = models.ImageField(upload_to='upload', height_field=None,width_field=None, max_length=None) featured = models.BooleanField() views.py def myIndex(request): myShoes = models.MyShoes.objects.all() return render(request,'index.html',{'myshoes':myShoes}) HTML {% for x in myshoes %} <div class="card" style="width: 18rem;"> <img src="{{x.display_picture}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{x.title}}</h5> <p class="card-text">{{x.description}}</p> <p class="card-text">{{x.price}}</p> {{x.display_picture}} <a href="" class="btn btn-primary">Go somewhere</a> </div> </div> {%endfor%} here in my HTML i am getting the url 'upload/shoe-1384193-1279x850.jpg' but HTML does show it in img tag -
I need Mutiple fields from both models in an m2m .csv export
I have a working solution for exporting a .csv file from a join of 2 models via a manytomany relationship and my issue is I don't know how to express, in code, how to bring in multiple fields from the model that is being joined. I can add multiple columns from the model that has the m2m field defined but I can only bring in one column from the model that is being referenced. How do I bring in multiple coulmns from both models? models.py class dbmobile(models.Model): Site_Code = models.CharField('Site Code', max_length=20, blank=True, null=True, choices=SITE) Account_Number = models.CharField('Account Number', max_length=20, blank=True, null=True,) Mobile_Number = models.CharField('Mobile_Number', max_length=20, blank=True, null=True,) User_Name = CharField('User Name', max_length=120, blank=True, null=True,) User_id = models.CharField('User Id', max_length=20, blank=True, null=True,) class expense(models.Model): ExcludeTax = models.DecimalField('Exclude Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) IncludeTax = models.DecimalField('Include Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) user = models.ManyToManyField(dbmobile, blank=True) Date = models.DateField(default=now) views.py def export_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="file.csv"' employees = expense.objects.all() writer = csv.writer(response) writer.writerow (['Date', 'Tax Included', 'User']) for e in employees: writer.writerow([e.Date, e.IncludeTax, ', '.join([e.User_Name for e in e.user.all()]),]) return response -
Django Polls-App: dynamically change number of choices in create-poll-form
After completing the Django beginner tutorial, I managed to build a create form to create a new poll with multiple choices. Now i want to add a button that adds another text-field for another choice. I'm new to web development and i struggle with passing variables from templates to views. I read here: Passing variable from django template to view, that there are essentially 4 ways to do this. I am currently using option nr. 3 to specify the number of choices displayed, but i am sure that option 1 would be more elegant, hence the number of choices wouldn't be displayed in the url. This is my current code: {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static "polls/style.css" %}"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {{ choice_forms.management_data }} <div class="pollschoice">{{ choice_forms.as_ul }}</div> <a href="{% url "polls:create" nr_of_choices|add:1 %}"><input type="button", value="Add Choice"> </a> <a href="{% url "polls:create" nr_of_choices|add:-1 %}"><input type="button", value="Remove Choice"> </a> <input type="submit", value="Save" /> </form> {% endblock %} def createview(request, nr_of_choices): # initialize forms nr_of_choices = max(nr_of_choices, 1) form = QuestionForm(request.POST or None) choiceFormSet = formset_factory(ChoiceForm, extra=nr_of_choices) choice_forms = choiceFormSet(request.POST or None) # save question … -
Django admin doesn't show model/task changes
I Have a celery task running which calls an API to get some response. If the API call is successful, then the output is stored in redis in order to use it as a dropdown list in the admin page. But, if the API response fails, then I disable the add option in the Django admin page which works fine. The issue: After failing when the API response is successful again, then the admin page doesn't show the dropdown list. Instead it shows an empty box. To make it work again, I have to reload the server manually. Is there a way to reload server automatically when the API response changes? -
Django (Quiz/Exam app) forms for multiple table. Need help to create a form which is
Quiz app which has following models from django.db import models from classroom.models import Subject from django.contrib.auth.models import User # Create your models here. class Exam(models.Model): name = models.CharField(max_length=120) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) number_of_questions = models.IntegerField() required_score_pass =models.IntegerField(default=40,) time = models.IntegerField(help_text="duration of test in minutes") def __str__(self): return f"{self.subject}: {self.name}" def get_questions(self): return self.question_set.all() class Question(models.Model): text = models.TextField() exam = models.ForeignKey(Exam, on_delete=models.CASCADE) def __str__(self): return f"{self.exam.name}: {self.text}" def get_answers(self): return self.answer_set.all() def get_correct_answers(self): for answers in self.get_answers(): if answers.correct: return answers.text class Answer(models.Model): text = models.CharField(max_length=200) correct = models.BooleanField(default=False) question =models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return f" question: {self.question.text}, answer: {self.text}, correct: {self.correct}" class Result(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.FloatField() I want to create a form for these models which are depended on each other. Any suggestion/idea for views or template are also welcome. Most of the models needs to save first since they will be need for ForeignKey fields. -
How to use Mailgun's recipient-variables with Django SMTP mail backend?
How can I properly send batch/bulk/mass emails using MailGun in Django using SMTP protocol? What I've tried so far? I am using django.core.mail.backends.smtp.EmailBackend as my EMAIL_BACKEND and this is the code snippet that I have tried to send the emails. from django.core.mail import EmailMultiAlternatives import json to_emails = [ "mail_1@example.com", "mail_2@example.com", "mail_3@example.com", "mail_4@example.com", "jerinpetergeorge@gmail.com", ] mail = EmailMultiAlternatives( subject="Hey - %recipient.name%", body="Hey %recipient.name%,\n\nThis is just a batch email test!!!", from_email="JPG <me@somehost.com>", to=to_emails, ) recipient_variables = { address: {"name": address} for address in to_emails } mail.extra_headers["X-Mailgun-Recipient-Variables"] = json.dumps(recipient_variables) response = mail.send() print(response) and I've got the mail as below, As we can see, the to attribute is filled with all email addresses, which is not what I am expecting. So, how can I tell the Mailgun/Django to parse my variables properly in order to make the emails looks more personal? Notes I prefer to use SMTP protocol I've tried the REST APIs of Mailgun and it was a success (but, I prefer SMTP) I found django-anymail and seems it has the feature. But, It also uses the APIs (correct me if I am wrong) -
Show most frequent tags in Django CreateView
I am trying to show the most frequent tags to select from when adding a post. However, when I added the get_context_data, the form disappeared. class AddPostView(CreateView): model = Post form_class = AddPostForm template_name = 'add_post.html' def get_context_data(self, **kwargs): common_tags = Post.tags.most_common()[:4] context = { 'common_tags': common_tags } return context # gets the user id def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) And this is my form class AddPostForm(forms.ModelForm): class Meta: model = Post fields = ('title','summary', 'body', 'header_image', 'category', 'tags') labels = { "title": "العنوان", "tags": "العلامات", "category": "التصنيف", "summary":"الملخص", "body": "المحتوى", "header_image": "الغلاف", } widgets = { 'title': forms.TextInput(attrs={'class':'form-control'}), 'tags': forms.TextInput(attrs={'class':'form-control'}), 'category': forms.Select(choices=choices_list, attrs={'class':'form-control'}), 'summary': forms.TextInput(attrs={'class':'form-control'}), 'header_image': forms.FileInput(attrs={'class':'form-control'}), 'body': forms.Textarea(attrs={'class':'form-control'}), } -
i want a move this logic to django utils file. I tried some code but failed
This is the code. I am using graphene django. I dont want to write logic in graphQL. I want to shift this logic to utils.py file class CreateCareer(graphene.Mutation): _career = graphene.Field(CareerType) class Arguments: input = CareerInput(required=True) def mutate(cls, root, info, input): try: input["from_date"] except: return GraphQLError("Please select from_date") try: input["current_work_here"] is False and not input["to_date"] except: raise Exception("Please select to_date") if input["current_work_here"] is False: if input["from_date"] > input["to_date"]: return GraphQLError("from_date must less than to_date") career = CandidateCareer.objects.create(**input) return CreateCareer(_career=career) -
Can I extend parent's class list attribute on class level?
Suppose, I have the following parent class: class Parent: permissions = ['CanEdit', 'CanCreate'] I need to extend permissions attribute in my child class without changing the initial contents and so that this change would be on the class level, not instance, meaning: print(Parent.permissions) Output: ['CanEdit', 'CanCreate'] And I need the something like this in my child class: class Child(Parent): permissions += ['CanManage'] print(Child.permissions) With the output: ['CanEdit', 'CanCreate', 'CanManage'] Is this even possible to implement? -
Count combination of 2 fields
I would like all the plays of a song per radiostation. class Airplay(Timestamps): song = models.ForeignKey(Song, on_delete=models.CASCADE) radio = models.ForeignKey(Radio, on_delete=models.CASCADE) airedAt = models.DateTimeField(blank=True) I try to calculate the airplay like this Airplay.objects.all().annotate(play_count=Count(Concat('song__id', 'radio__id'), distinct=True)).order_by('play_count') I see several occurrences of a song x station combination. But play_count is always 1. -
Why is this django registration mechanism not working for my custom user model?
I was working on a project where I was implementing a custom user model using django and registration,login for the same. But unfortunately, I guess the registration mechanism doesn't work correctly. How do I know that is, in Admin panel, it shows the new user where while trying to login with the new user, I get "Please enter a correct username and password. Note that both fields may be case-sensitive." . I've spent around 2 days googling,stackoverflowing. But none of them has solved my problem. My Code Models.py: from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save(using=self._db) return user class UserModel(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True, null=True) last_name = models.CharField(max_length=150, blank=True, … -
Model() got an unexpected keyword argument 'instance'
I am currently trying to get an instance of my model to read from it and print reports based on the model However when trying to reach the URL I get the above error, I assume that the instance variable doesn't work but I don't know why. I have been reading other articles and found that others get this error when they use Form instead of ModelForm, so I don't know if this could be the same thing as that. Please see the below code : Model.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) def __str__(self): return (self.Complex + ' Settings') View.py:: def reportsHome(request): model = SettingsClass.objects.all().order_by('Complex') content ={'model':model } return render(request, 'main/reportsHome.html' , content) def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) complexName = form.Complex #CHECKING TRIAL BALANCE SETTINGS if form.Trial_balance_Year_to_date == True: printTrialBalanceYTD = True ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' #SQL STATEMENT baseSelect = 'SELECT '+ op5 + op4 + ' Debit , … -
Django channels elastic beanstalk (linux 2) hooks postdeploy: -b command not found
For deployment of django channels on elastic beanstalk (linux 2 AMI) I tried implementing this blog ,it required creation of ./platform/hooks/postdeploy/ and in it two files 01_set_env.sh and 02_run_supervisor_daemon.sh, on eb deploy it fails and on checking the eb-engine.logs this error shows up. 2021/09/28 05:05:44.382229 [ERROR] An error occurred during execution of command [app-deploy] - [RunAppDeployPostDeployHooks]. Stop running the command. Error: Command .platform/hooks/postdeploy/02_run_supervisor_daemon.sh failed with error exit status 2. Stderr:.platform/hooks/postdeploy/02_run_supervisor_daemon.sh: line 13: -b: command not found 02_run_supervisor_daemon.sh #!/bin/bash # Get system environment variables systemenv=`cat /opt/elasticbeanstalk/deployment/custom_env_var | tr ' ' ',' | sed 's/%/%%/g' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/:$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` systemenv=${systemenv%?} systemenv=`echo $systemenv | sed 's/,/",/g' | sed 's/=/="/g'` systemenv="$systemenv"" # Create daemon configuration script daemonconf="[program:daphne] command=daphne -b :: -p 5000 backend.asgi:application directory=/var/app user=ec2-user numprocs=1 stdout_logfile=/var/log/stdout_daphne.log stderr_logfile=/var/log/stderr_daphne.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true environment=$systemenv" # Create the Supervisor conf script echo "$daemonconf" … -
BitBucket Deploy to Google Cloud appEngine could not find file Django
I have .yml file for pipline of django the code for deploye is - pipe: atlassian/google-app-engine-deploy:0.7.3 variables: KEY_FILE: $KEY_FILE PROJECT: $PROJECT DEPLOYABLES: 'realpars_platform/app.yaml' VERSION: '${BITBUCKET_BUILD_NUMBER}' PROMOTE: 'true' STOP_PREVIOUS_VERSION: 'true' EXTRA_ARGS: '--verbosity=debug --quiet' But when i run this Error showes. ERROR: (gcloud.app.deploy) [/opt/atlassian/pipelines/agent/build/realpars_platform/app.yaml] does not exist. ✖ Deployment failed. -
Check Python Version Used in Mod_WSGI
I can't find out which python environment is being used or install location is being used by mod_wsgi in Apache. In my apache config I didn't gave any specific venv config. ServerName ServerAlias DocumentRoot /home/Downloads ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/Downloads/static <Directory /home/Downloads/static> Require all granted </Directory> <Directory /home/Downloads/samples> Require all granted </Directory> <Directory /home/Downloads> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess group python-path=/home/Downloads python-home=/home/envlin WSGIProcessGroup group WSGIScriptAlias / /home/Downloads/wsgi.py I removed the critical info and replaced with random info. Here's my apache restart log Apache Logs Apache/2.4.46 (Ubuntu) OpenSSL/1.1.1j mod_wsgi/4.7.1 Python/3.9 configured -- resuming normal operations Question Is there any way to get which python version and install location is being used by mod_wsgi. **Python Path's ** If I fetch python path's normally here's the result. sys.path = [ '/root', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.9/dist-packages', ] -
Python 2.7 Failed building wheel for MySQL-python
I'm new to Python && Django. In activated virtual environment when i run pip install mysqlclient==1.3.9 I get Failed building wheel for MySQL-python I tried to install without specific version as well. I also tried solutions like running: sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-pil python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev and updated pip. ERROR: Command errored out with exit status 1: command: /home/tech/Projects/dpython/sk/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-8CZORn/mysql-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-8CZORn/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-igaywV cwd: /tmp/pip-install-8CZORn/mysql-python/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -ffile-prefix-map=/build/python2.7-5hlAcC/python2.7-2.7.18=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o _mysql.c:44:10: fatal error: my_config.h: … -
Editing Forign Key Attributes Of a Model From Django Admin
I have two model classes in my django project. class User(AbstractBaseUser, PermissionsMixin): username = None phone = models.CharField(max_length=16, unique=True) password = models.CharField(max_length=255, default="asdf") name = models.CharField(max_length=255, default="User") email = models.EmailField(max_length=255, blank=True, null=True) class Booking(models.Model): profile = models.ForeignKey(User, null=False, on_delete=models.CASCADE, db_index=True, default=1) latitude = models.DecimalField(decimal_places=20, max_digits=30, default=1.0000) longitude = models.DecimalField(decimal_places=20, max_digits=30, default=1.0000) Now In the django admin panel, I want to change the name of the user from the edit screen of a booking. I tried with Inline Models, with it I can edit booking from user's edit screen but it is not working in this case. Is there any other options available for this? -
Admin email handler with filter keeps sending emails
I am trying to silence a specific error getting emailed through the django.request logger: 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, } The filter silence_invalid_header is attached to the handler: 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false', 'silence_invalid_header'], 'class': 'django.utils.log.AdminEmailHandler' } } This is the filter configuration: 'silence_invalid_header': { '()': 'mysite.logger_utils.SilenceInvalidHttpHostHeader' } And the filter class itself: class SilenceInvalidHttpHostHeader(logging.Filter): def filter(self, record): return 'Invalid HTTP_HOST header' not in record.msg However, I keep getting emails. Although django.request is set to propagate, it should propagate to Django's default logger django defined in django.utils.log.DEFAULT_LOGGING: 'django': { 'handlers': ['console'], } And that hanlder just writes to the standard output: 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', } So why do I keep getting emails with that error and how can I silence them? -
base64 saves blank image - django
im trying to capture image from webcam , but when i decode it using base64 it only saves a blank image ? this is what i tried class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': data = request.POST.get('documents') format, imgstr = data.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) images = UploadDocumentsForm(request.POST,request.FILES) if data: photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('choose or capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj,'form':images}) here is my template const player = document.getElementById('player'); const docs = document.getElementById('document') const captureButton = document.getElementById('capture'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const imgFormat = canvas.toDataURL(); docs.value = imgFormat const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} <input type="text" name="documents" id="document"> <video id="player" controls autoplay></video> <button id="capture">Capture</button> <canvas id="canvas" width=320 height=240></canvas> <button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">{% trans "save" %}</button> </form> please is there solution , i appreciate your helps .. thank you in advance .. -
Passing data from a view to a form in django
I have a django formtool: the first step it needs to insert a name and select N values from a MultipleChoiceField. When user submit this form in the second step, I need to show N MultipleChoiceField where every elements of each MultipleChoiceField are retrieved from the database. I need to take the values of the first step form, retrieve from Db the data e send these to the second steps (forms.py). For the second step I suppose I need a formset. I have read some few questions about passing value from a view to a form but any solution. This is my code: forms.py from django import forms from station.models import Station from django.forms import formset_factory from .models import Vdl station_all=Station.objects.all() class VdlSelectStationsForm(forms.Form): vdl_name = forms.CharField(label='nome virtual data logger', max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'})) stations = forms.ModelMultipleChoiceField(queryset=station_all) class VdlSelectSensorsForm(forms.Form): sensor_list_for_station = forms.ModelMultipleChoiceField(queryset=Vdl.objects.all()) #filter(id_user = id_user)) VdlSelectSensorsForm = formset_factory(VdlSelectSensorsForm, extra=1) views.py from django.shortcuts import render from .forms import VdlSelectStationsForm, VdlSelectSensorsForm from formtools.wizard.views import SessionWizardView class VdlWizard(SessionWizardView): template_name = "vdl.html" form_list = [VdlSelectStationsForm, VdlSelectSensorsForm] def get_form_initial(self, step): initial = {} # If at second step, add image path to initial data for canvas field if step == '1': first_step_data = self.storage.get_step_data('0') … -
Why I cannot get email user login with line by Django django-social-auth
Django Setting AUTHENTICATION_BACKENDS = [ 'social_core.backends.line.LineOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_LINE_KEY = '???????' SOCIAL_AUTH_LINE_SECRET = '????????' SOCIAL_AUTH_LINE_SCOPE = ['profile email openid'] I follow this scope and request but the response don't send user email to my app -
How to parse date string containing mm/yyyy in django models?
I'm writing existing SQLite3 database to django models. Some dates replicate themselves and I need them encoded, so I create a class in the model to store unique periods in the following form: mm/yyyy. What would be the right syntax to set date, so in django they have the same format, but as a datetime object? class Periods(models.Model): period = models.DateField() def __str__(self): return self.period Thanks in advance.