Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User variable inaccessible in template tag of Django
I’m fairly inexperienced in Web Dev and Django. I need to check if user is_staff or not, in my HTML page, specifically in a custom template tag I’ve written. My base.html is as follows: <body> <header> This is the Header. <h1>Webiste name & logo</h1> <hr> <nav> <h2>This is the navigation bar</h2> {% show_traits %} </nav> <hr> </header> {% block content %}{% endblock %} <hr> <footer> Here starts the footer. <a href="{% url 'login' %}">Sign In</a> <a href="{% url 'register' %}">Sign Up</a> </footer> </body> The first line loads tags from my_tags.py file, which has the following: from django import template from ..models import Trait register = template.Library() @register.inclusion_tag('navigation.html') def show_traits(): traits = Trait.objects.all() return {'traits': traits} The navigation.html file is as follows: This is the user: {{ user.username }} <ul> {% for trait in traits %} <li> {% if user.is_staff %} <a href="{% url 'form-detail' trait.id %}">{{ trait }}</a> {% else %} <a href="#">{{ trait }}</a> {% endif %} </li> {% endfor %} </ul> But when I run my dev server, the base.html file doesn’t seem to show the {{user}} variable: The page source shows that the user wasn’t validated as staff either: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> … -
How to implement Token Authentication in Django
Can anyone tell me how to implement Token Authentication for a Custom Model. Keep in mind I am a beginner in Django. Here is my model class Retailer(models.Model): name=models.CharField( max_length=255, null=False, ) email=models.EmailField( max_length=255, null=False, unique=True ) password=models.CharField( max_length=255, null=False ) def __str__(self): return (self.name) Here is my Login View @api_view(['POST']) def retailerLogin(request): email = request.data['email'] password = request.data['password'] try: retailer = Retailer.objects.get(email=email) if not check_password(password, retailer.password): return JsonResponse({ 'message': 'Incorrect Password...!', 'status': status.HTTP_404_NOT_FOUND }) else: return JsonResponse({ 'retailer': RetailerGETSerializer(retailer).data, 'status': status.HTTP_202_ACCEPTED }) except Retailer.DoesNotExist: return JsonResponse({ 'message': 'Account does not exist...!', 'status': status.HTTP_404_NOT_FOUND }) I want to generate a token whenever retailer logs in so that he receives the token in frontend which is ReactJS in my case. This is i want return JsonResponse({ 'retailer': RetailerGETSerializer(retailer).data, 'status': status.HTTP_202_ACCEPTED, 'token' : some_token }) And later he can send that token as authorization header. I tried to google but they have implemented on Django User Model How should i implement it in my case? -
Need a valid file name! xhtml2pdf with Django
i have a problem, i creating a pdf file from html , using xhtml2pdf library. having created the pdf file, but the image is not come out, how can i fix it? this is my html code: <img src="{% static 'pengurusan/logo.png' %}" height="120cm" width="121cm" alt="My image"> this is my views.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = io.BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8', link_callback=link_callback) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) def myview(request): #Retrieve data or whatever you need postingan_list = Pengajuan_SKTM.objects.filter() return render_to_pdf( 'pengurusan/surat.html', { 'pagesize':'A4', 'postingan_list' : postingan_list, }) def link_callback(uri, rel): result = finders.find(uri) if result: if not isinstance(result, (list, tuple)): result = [result] result = list(os.path.realpath(path) for path in result) path=result[0] else: sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /media/ mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path -
Creating signed request for S3 upload using Django
I have a simple django app on heroku for uploading images and it works as expected when accessed from desktop but fails to sign the requests for upload to AWS S3 when I access the site on mobile. The signing code is shown below: def sign_s3(request): request = request.GET S3_BUCKET = os.environ.get('AWS_STORAGE_BUCKET_NAME') file_name = request.get('file_name') file_type = request.get('file_type') s3 = boto3.client('s3') presigned_post = s3.generate_presigned_post( Bucket = S3_BUCKET, Key = file_name, Fields = {"acl": "public-read", "Content-Type": file_type}, Conditions = [ {"acl": "public-read"}, {"Content-Type": file_type} ], ExpiresIn = 3600 ) return HttpResponse(json.dumps({ 'data': presigned_post, 'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name) })) I set everything in the S3 bucket to public and have the CORS set as <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> I cant tell what could be causing this difference. How can I get this working? -
why everything is not translated in django admin site
I changed the default LANGUAGE_CODE from en-us to fa-ir in settings.py file but some sentences and words are still english and not translated (i have some examples in images attached) here is my admin.py file for my app : from django.contrib import admin, messages from django.utils.translation import ngettext from .models import Product, Category, ProductImage # Register your models here. @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ('Name', 'Slug', 'Parent',) prepopulated_fields = {"Slug": ("Name",)} @admin.register(Product) class ProductAdmin(admin.ModelAdmin): fields = (('Title', 'Slug'), ('Description', 'IsExists'), 'Category', 'Created',) list_display = ('Title', 'Slug', 'Description', 'IsExists', 'Category', 'Created',) prepopulated_fields = {"Slug": ("Title",)} def save_form(self, request, form, change): super().save_form(request, form, change) @admin.register(ProductImage) class ProductAdmin(admin.ModelAdmin): list_display = ('Product', 'Image',) -
Django class based update view not working
I have just started learning Python and Django. I was trying to create a simple blog website, but for some reason, I am unable to update my blog through forms. It takes me back to the detail view without making any changes. Here is the link to the project - https://github.com/k-ken-source/DailyBlog- You can check out the UpdateView in posts/views.py. This class-based view generally works, I have even tried a number of solutions nothing seems to work. Any help would be appreciated. ThankYou in advance. -
Save user first_name as default value for model django
I have an article model with author variable which I want to save as the users first and last name. I use custom user model called Account. author = models.CharField('author',max_length=50 default=User.first_name) When saved it shows the author is <django.db.models.query_utils.DeferredAttribute object at 0x10b461dc0> So how can I retrieve the account first name when saving this form: form = ArticleCreationForm(request.POST) # check if form data is valid if request.method == "POST": if form.is_valid(): form.save() # save the form data to model context['form']= form forms.py: class ArticleCreationForm(forms.ModelForm): # specify the name of model to use class Meta: model = Article fields = "__all__" exclude = ['votes', 'author'] It would be good if you can make it so that the user sees the author field with his name but can't edit it. -
int() is not working in django views when I am trying get a input from template and pass it to the template again. It's showing erros
Please help me. I was trying to convert my age to days using Django. I am getting the year from a template but at the time of casting it into int(), it's not working showing errors. code blow. from django.shortcuts import render # Create your views here. def home(request): grbtext = request.POST.get('webYear') webyear = int(grbtext) // this line is not working days = (2020 - webyear) * 365 context = { 'ageindays': days, } return render(request, 'a2d/index.html', context) -
circumvent authentication of a django app from another django entity to get specific data
I'm beginner to django rest framework , and now I'm working on a project ; In my django app user make some instances that one of its fields is a url which user want to access to access another Django api and get some specific data in json form from one of its methods . the destination url api want username and password by default . So what should I do in destination app and Origin to avoid this authentication ?? and after that get exactly those data not just see the page ! And another thing which could be effective is that I serve the Origin API through NGINX webserver and the destination is on apache . As I've read , one way is django-Middlewares ; like csrf_exempt() . but this middleware completely says that the selected view doesn't need protection however I just want to give this feature to my first Djago app url not anyone ! should I write my own Middleware? How? So please help me if you have any idea . Thanks -
Python Djnago modal popup on master page
I have created a bootstrap popup modal which I have set on master page with header and footer, the modal popup is a signup form. I want to access that signup form from every other page in the project but I don't know what URL I will give for that in views.py. Can anyone help? -
How do I have to setup my docker-compose file so that I can access it from my phone?
I wrote a Django backend app that is supposed to offer a web socket service. I'm currently only running the Docker Container on my PC. The next step is that I want to open a websocket from my Android app to communicate with the backend. Unfortunately I don't have access to the Docker Container from my mobile phone. I have tried both the 10.0.0.1, 0.0.0.0, Docker-machine IP: 192.168.99.100:8000, and my IPv4 address. From other questions I have read that I need a Bridge VM, unfortunately I have no idea how to do this with docker-compose. In general I am a bit behind with Docker. Depending on the IP I enter into the Android App Websocket Builder I get a timeout or "connection refused" or "connection not possible". What do I have to change? For now, everything is on a local network, the phone is on the same network as the computer via WLAN. From my computer I can use the docker machine "default" IP and port 8000 to get to the Django site. version: '3' services: redis: image: redis:latest command: redis-server ports: - "6379:6379" - "6380:6380" web: build: .\experiencesampling command: python manage.py runserver 0.0.0.0:8000 volumes: - .:\code ports: - "8000:8000" … -
How do I ensure crontab commands run once on AWS when there may be multiple instances?
I have a Django project running on AWS using Elastic Beanstalk. It can have between 1 and 6 instances running. I load a crontab file to run some management/commands overnight. I have this config file: container_commands: 01_cron_job: command: "cp .ebextensions/crontab.txt /etc/cron.d/my_cron_jobs && chmod 644 /etc/cron.d/my_cron_jobs" #leader_only: true The file copied across looks like: # Set the cron to run with utf8 encoding PYTHONIOENCODING=utf8 # Specify where to send email MAILTO="me@gmail.com" 1 0 * * * root source /opt/python/current/env && nice /opt/python/current/app/src/manage.py clearsessions 15 0 * * * root source /opt/python/current/env && nice /opt/python/current/app/src/manage.py update_summary_stats >> /opt/python/log/update_summary_stats.log 2>&1 # this file needs a blank space as the last line otherwise it will fail Within the config file, if I set leader_only to false then the command runs on every instance. If I set leader_only to true then the crontab commands run on every instance. What is the best way to set up crontab on AWS Elastic Beanstalk to only run once irrespective of the number of instances? Thank you -
Could not deserialize key data. JWT python
import jwt encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='ES256') 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxKO1T_yoc0Z6XOpOVswacPZg' -
Plotly graph giving weird lines
I am working on a DjangoDash app that will display a Plotly graph of some temperature data. the data is displayed fine when the graph object is in 'markers' mode, but once I put it into lines mode the line starts to connect the wrong data points. Is there a way to make sure that Plotly connects the data points in the right order? import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go from django_plotly_dash import DjangoDash from datetime import datetime, timedelta from home.models import data app = DjangoDash('example') app.layout = html.Div(children =[ dcc.Interval( id='my_interval', disabled=False, interval=1000, n_intervals=0 ), dcc.Graph( id='chart', ) ]) @app.callback( Output(component_id='chart',component_property='figure'), [Input(component_id='my_interval', component_property='n_intervals')] ) def update_value(num): model_data = data.objects.values_list('temp','time') x_values = [] y_values = [] for values in model_data: x_values.append(values[1]- timedelta(hours=7)) y_values.append(values[0]) fig=go.Figure( data=[go.Scatter(x=x_values, y=y_values, mode='lines', name='markers')], layout={'uirevision':True}, ) return (fig) messed up lines on Plotly graph -
Systemctl gunicorn not run django, no module named ... how to fix?
Cannot run django with systemctl and gunicorn Error: ModuleNotFoundError: No module named 'src.settings' But if run gunicorn with my bash script, i located in venv directory, it working. #!/bin/bash NAME="src" # Name of the application DJANGODIR=/webapps/transtolang/src # Django project directory SOCKFILE=/webapps/transtolang/run/gunicorn.sock # we will communicte using this unix socket USER=transtolanguser # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=10 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=src.settings.production # which settings file should Django use DJANGO_WSGI_MODULE=src.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- But if i make by digitalocean tutorial make gunicorn service(I"M NOT USE MY SCRIPT IN THERE) it off with dump error my wsgi import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings.production') application = get_wsgi_application() my app contains in main directory … -
Django: TypeError: 'DeferredAttribute' object is not callable. while every day transfer data one to another table
insert_data_script.py from.models import Consumer_order,Daily_Cart def transfer_daily_data(): new_daily_cart = Daily_Cart() new_daily_cart.ac_no = Daily_Cart.ac_no() new_daily_cart.newspaper = Daily_Cart.newspaper() new_daily_cart.added_date = Cust.Consumer_order.added_date() new_daily_cart.save() print("saving...\n" + new_daily_cart) Model.py class Consumer_order(models.Model): name = models.ForeignKey(Consumer, on_delete=models.CASCADE) ac_no = models.CharField(max_length=32) newspaper = models.ManyToManyField(Newspaper,related_name="Consumer_ac_no") added_date = models.DateField(max_length=32,auto_now_add=True) def __str__(self): return str(self.ac_no) class Daily_Cart(models.Model): ac_no = models.CharField(max_length=32) newspaper = models.CharField(max_length=32) added_date = models.DateTimeField(max_length=32,auto_now_add=True) def __str__(self): return str(self.added_date) TypeError: 'DeferredAttribute' object is not callable Job "transfer_daily_data (trigger: interval[0:01:00], next run at: 2020-08-17 12:33:12 IST)" raised an exception Traceback (most recent call last): File "C:\Users\Rk\Documents\Django\Project--Django\Pro_Venv\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) File "C:\Users\Rk\Documents\Django\Project--Django\Pro_Venv\NewspaperAPI\insert_data_script.py", line 5, in transfer_daily_data new_daily_cart.ac_no = Consumer_order.ac_no() TypeError: 'DeferredAttribute' object is not callable guys iam using Advanced Python Scheduler. While run APS. data not transfer one to another table. that time error comes : DeferredAttribute' object is not callable. guys how to sort out this error -
How do I stop Django from running in Background?
Actually when I try to run PHP file on wamp server, it gives me Django error. Which means Django is running in Background. Right? btw i'm using Windows. -
Iterate django form fields to use in the table header
I have a table header like this <th>{% trans "Unit of Measure" %}</th> <th>{% trans "Description" %}</th> <th>{% trans "Actions" %}</th> I have the idea that if i can iterate the model field verbose name I can avoid writing in the table header like this <th> {% trans "Part Number" %}</th> The problem is i don't know how to implement this kind of stuff If someone has better idea about this I'm please and happy to learn. -
On Makemigration "parent_link" is auto-generated with error "clashes with declared field of the same name", even if "parent_link" exisits in DB
"ContactInformation" is base class Inheritate by child class "PhoneNumber" and "ContactEmail" -
Using Mailchimp in Django project
I want to use Mailchimp for all email communications (like sign up, forgot password, notifications, etc). But I don't know how to connect Django with Mailchimp. Can someone help me with it? Thanks! -
In Django my image is not displaying but alternate is displaying
this is the image src <img src="{% static 'images/cart.png' %}" alt="cart image"> STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] -
Error sub-select returns 4 columns - expected 1 when submitting query
I am trying to submit the django form which takes automatic username from input field and takes a checklist of names. When I submit form it gives me error sub-select returns 4 columns - expected 1 This is my function from views.py def weekly(request): context = '' weekly_form = WeeklyForm() daily_form = DailyForm() context = {'weekly_form': weekly_form, 'daily_form': daily_form} # Weekly Report Code to execute on submit if request.method == 'POST' and 'weekly' in request.POST: form = WeeklyForm(request.POST) print("This line is printed in weekly") if form.is_valid(): tname1 = request.POST.get('teachers') data = form.cleaned_data print (data) print("This line is printed 1") report = wreport(tname = tname1, sname = data['sname'], fdate = data['date'], objective = data['objective'], tplan = data['target'], how = data['how'], material = data['material'], extra = data['support']) report.save() messages.success(request, "Your report was submitted Successfully.") else: print(form.errors) This is my Database model class wreport(models.Model): _id = models.AutoField tname = models.CharField(max_length = 255, default = "") sname = models.CharField(max_length = 255, default = "") classes = models.CharField(max_length = 255, default = "") fdate = models.DateField() objective = models.CharField(max_length = 255) tplan = models.CharField(max_length = 512) how = models.CharField(max_length = 255) material = models.CharField(max_length = 512) extra = models.CharField(max_length = 255) This is my Form … -
Django mysql backend returned "(2000, 'Unknown MySQL error')"
Problem in title. DB logging displayed this: (0.001) SELECT @@SQL_AUTO_IS_NULL; args=None (0.001) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None (0.001) None; args=() (0.000) None; args=() (0.000) None; args=() (0.000) None; args=() (0.000) None; args=() What is None query and why it here? This query generated with next django code: print(AttachmentCategory.objects.all()) Model is very simple: class AttachmentCategory(models.Model): name = models.CharField(max_length=60, blank=True, null=True) class Meta: managed = False db_table = 'attachment_category' On Windows 10 and Arch Linux its falling, but on Ubuntu 20.04(working machine) its worked fine. From DataGrip connection is OK on all of machines. Trouble in crappy queries. Any help or thinks will be very helpful. Thanks. -
Customize serializer.is_valid() Errors
How can I customize errors that get generated by serializer.is_valid(raise_exception=True)? My views.py has the following method class AutoSignupAnonymousUserView(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): data = request.data serializer = AutoSignupAnonymousUserRequestSerializer(data=data) serializer.is_valid(raise_exception=True) . . . request.data looks like this { "device_serial": "android-4000", "device_version": "5.0" } AutoSignupAnonymousUserRequestSerializer looks like this class AutoSignupAnonymousUserRequestSerializer(serializers.Serializer): device_serial = serializers.CharField(max_length=36, required=True, allow_blank=False, allow_null=False) device_version = serializers.CharField(max_length=15, required=False, default='', allow_blank=True, allow_null=False) If the json request has an empty device_serial, I get the built-in error This field may not be blank. { "device_serial": "", "device_version": "5.0" } Error: { "device_serial": [ "This field may not be blank." ] } How can I change this error This field may not be blank. error to my own custom error? -
VS Code shows "Exception has occurred: ModuleNotFoundError" while start debugging
I executed the "Start Debugging" on Visual Studio Code to debug a Django website. However, the VS Code shows "Exception has occurred: ModuleNotFoundError No module named 'maintenance_mode'". I've used "pip3 install django-maintenance-mode" to installed the "django-maintenance-mode" v0.14.0. My INSTALLED_APPS in the WebServer/settings.py includes the 'maintenance_mode' as the https://pypi.org/project/django-maintenance-mode/ mentioned. INSTALLED_APPS = [ 'maintenance_mode', ... ... ] If I remove the usage of the 'maintenance_mode' from INSTALLED_APPS, then the debugging mode works. But I need to use the 'maintenance_mode' module. What should I do to make debugging work with 'maintenance_mode' module?