Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django extend AbstractBaseUser Admin Login Page Error
Today I tried to change the UserModel, So I did everything that was supposed to be needed : create the class class User(AbstractBaseUser, PermissionsMixin): With something like that inside : phone = PhoneNumberField(unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(_('active'), default=True) objects = UserManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] def is_staff(self): return self.is_admin The UserManager : class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone, password, **extra_fields): """ Creates and saves a User with the given phone and password. """ if not phone: raise ValueError('The given phone must be set') user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_admin', False) return self._create_user(phone, password, **extra_fields) def create_superuser(self, phone, password, **extra_fields): extra_fields.setdefault('is_admin', True) if extra_fields.get('is_admin') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone, password, **extra_fields) The CustomUserAdmin class : class CustomUserAdmin(UserAdmin): # The forms to add and change user instances # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference the removed 'username' field fieldsets = ( (None, {'fields': ('phone', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, … -
Do django is needed for every virtual environment?
Is it necessary to install separate django for each project? if yes then why? and if no then when i check for django version when virtualenv is not activated their is no error as below E:\web\python\django_1>python -m django --version 2.1.4 And when i activate virtual env i get error as below (django_1-Gx7XQ45n) E:\web\python\django_1>python -m django --version C:\Users\usr_name\.virtualenvs\django_1-Gx7XQ45n\Scripts\python.exe: No module named django Why this is happening? -
My project uses the Google+ API to login,which is deprecated now, need tips/advice to update
I have a project currently deployed, in production, which uses the google+ API and the python social core (Django) (social_core) to login almost all users, now the google+ apis are deprecated and I need to update the authentication system. Any tip, documentation or tutorial I can follow to make it? I followed this tutorial to make the initial login but now that won't work in the near future. This is a school project so I'm pretty much the only developer working with this, any help provided will be much appreciated :D -
get_queryset vs manager in Django
As far as I know, we bring the database by model managers right? e.g. queryset = Model.objects.all() But sometimes, I see some code that seems almost same thing but is a bit different, post = self.get_queryset() which also fetches database but not by manager. What's the difference between fetching database by manager and get_queryset() and their usage? -
ModuleNotFoundError in Django Crontab Command
I have a number of django custom commands which work. However, when I have tried to automate them using crontab, my error log records the following error: ModuleNotFoundError: No module named 'sanct' I have added the virtualenv path to crontab command path. I have a test command which just creates a log file every minute and this seems to execute properly. I'd like the crontab commands to execute. My crontab commands are as follows: job = cron.new(command='/home/arch/myprojectdir/myprojectenv/bin/python /home/arch/myprojectdir/sanct/management/commands/cong_dl.py >>/tmp/out.txt 2>&1') -
Django Admin and third party Javascript
I am running django 2.0, which has jquery 2.2.3. I want to utilize this ImageViewer Javascript app https://github.com/s-yadav/ImageViewer with one of my admin pages. I added the js files and css file to the Media class within my ModelAdmin class, and collected all the static files. The files are loaded on the web page. I am following the app's example for Image Mode (http://ignitersworld.com/lab/imageViewer.html) The page loads, but there is an error in the js console: imageviewer.js:16 Uncaught TypeError: $ is not a function at imageviewer.js:16 at imageviewer.js:789 (anonymous) @ imageviewer.js:16 (anonymous) @ imageviewer.js:789 The first few lines of the ImageViewer script - line 16 is the one with 'body' /* ImageViewer v 1.1.3 Author: Sudhanshu Yadav Copyright (c) 2015-2016 to Sudhanshu Yadav - ignitersworld.com , released under the MIT license. Demo on: http://ignitersworld.com/lab/imageViewer.html */ /*** picture view plugin ****/ (function ($, window, document, undefined) { "use strict"; //an empty function var noop = function () {}; var $body = $('body'), $window = $(window), $document = $(document); The last line of the script is line 789, the source of the second error: }((window.jQuery), window, document)); The header of my admin page: <script type="text/javascript" src="/admin/jsi18n/"></script> <link href="/static/imageviewer.css" type="text/css" media="all" rel="stylesheet" /> … -
Pure Django Form Tying User To Submitted Form And View
I am unsure how to tie a logged in user to a submitted form using regular Django forms. I see alot of examples using ModelForms but none (that I can tell) without using the ModelForms. In my forms.py im having a hard time figuring out how to add the author field. I cannot just add author = forms.ForeignKey or something like that. Then somehow in my view i need to call the authorfield to be saved into the database (my below example is my best guess and probably not right with the "tenant_form.author = request.user". I have a model that looks like this and has a user Foreignkey setup: class AppyModel(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) date_time_form_filled = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) I have a forms.py: class TenantForm(forms.Form): first_name = forms.CharField(required=False, label='First Name') last_name = forms.CharField(required=False, label='Last Name') I have a views.py @login_required def tenant_create_form_view(request): tenant_form = TenantForm() if request.method == 'POST': tenant_form.author = request.user tenant_form = TenantForm(request.POST) if tenant_form.is_valid(): print(tenant_form.cleaned_data) AppyModel.objects.create(**tenant_form.cleaned_data) else: print(tenant_form.errors) context = { 'form': tenant_form } return render(request, 'fill_appy.html', context) -
Coverage detecting import statements as not covered
When testing a Django project with django_nose and coverage.py, the report says the import statements are not covered: Name Stmts Miss Cover Missing ---------------------------------------------- app1/models.py 211 199 6% 1-44, ... Where the first lines of app1/models.py are: import datetime from django.conf import settings from django.db import models from django.utils import timezone How can I tell coverage.py to ignore these statements or how do I test them? -
How to fix "net::ERR_CONNECTION_REFUSED and Error: Network Error" error in Reactjs,Django,Django Rest Frame work project
I am trying pass data from reactjs to django through django rest api by post method but there raising this problem. I have tested post method through Django-REST Api GUI.It's working perfectly. My Reactjs component code: import React, { Component } from 'react' import './Register.css'; import axios from 'axios' const REGISTER_URL = 'http://127.0.0.1:8000/api/register/?format=json' // received api ulr... const initiaState = { username : '', email : '', password: '' } class Register extends Component{ constructor(){ super() this.myRegister = React.createRef() } state = { ...initiaState } changeHandler = (event) => { this.setState({ [event.target.name]: event.target.value }) } submitHandler = (event) =>{ event.preventDefault() console.log(this.state) this.myRegister.current.reset() this.setState({ ...initiaState }); axios.post(REGISTER_URL,this.state) .then(res =>{ console.log(res) }) .catch(error =>{ console.log("ERROR::: "+error) }) } render(){ return( <div className="Register-box"> <form ref = {this.myRegister} className="Form" onSubmit={this.submitHandler }> <div className ="form-group "> <label htmlFor="username" > Name: </label> <input className = "from-control ml-4" type="text" placeholder = ' Enter Your Name ' name = "username" id = "username" value = {this.state.name} onChange = {this.changeHandler} /> </div> <div className ="form-group"> <label htmlFor="email" > Email: </label> <input className = "from-control ml-4" type="text" placeholder = ' Enter Your Email ' name = "email" id = "email" value = {this.state.email} onChange = {this.changeHandler} /> </div> <div className … -
How do I include the region in language.code?
I'm building a language switcher for Django. There are tons of examples but none of them seem to solve the issue I'm having. I always get the short version of the language code. Instead of en-us I get en. {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <a href="/{{ language.code }}{{ request.get_full_path|slice:'6:' }}" class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}" lang="{{ language.code }}"> {{ language.name }} </a> {% endfor %} My LANGUAGES in settings.py are specified as: LANGUAGES = ( ('en-us', _('English')), ('fr-ca', _('French (Canada)')), ) I assumed that {{ language.code }} would give me either en-us or fr-ca. Instead I get en and fr. Just to be sure I checked if LANGUAGE_CODE works and it does return en-us as expected. It's just get_language_info_list that doesn't seem to work for me. I feel like I'm missing something extremely simple here. -
Http Request Not Showing View for Page, But No Error Detected by Server
I'm running into an issue. I've been following a tutorial by Corey Schafer on youtube (link to video for reference "https://youtu.be/a48xeeo5Vnk") and I am encountering an error that is somewhat unique. I am trying to set up a simple Django blog site as practice for building my own site. I only have two Http Requests currently "Home" and "About". According to the tutorial, I am calling the function to view the about page correctly as I am getting no error from the server, however the Http Request isn't processing the view for the about page and is only returning the home page. Home View: Result from http request for home About View: Result from http request for about Project urls.py: Main urls file for project Blog urls.py: Blog urls file for project Blog view.py: Blog views file for project Server Activity: Activity and notifications from server As of this moment, I have already tried to do research on this issue. The main problem is that most issues usually have an error code, whereas this one doesn't have one. And searching on google for about 10-15 minutes was fruitless as a result of not having an error code. I also know … -
how to signout from firebase using django python
I am trying to create user authentication from back-end with python and firebase. So far creating a user and login actions worked perfectly. But for somehow i cannot find any information for signOut action. i'm using Pyrebase library. Any one has a suggestion? Here is the part it works: import pyrebase config = { #my private config informations } firebase = pyrebase.initialize_app(config) auth = firebase.auth() def createAccount(request): if request.method == "POST": email=request.POST.get("email") password = request.POST.get("password") auth.create_user_with_email_and_password(email, password) return render(request, 'beforeLogin/landingPage.html') def verifyLogin(request): if request.method == 'POST': email=request.POST.get("email") password = request.POST.get("password") try: auth.sign_in_with_email_and_password(email, password) except: messages.error(request,'Email or password is not correct.') return render(request, 'beforeLogin/landingPage.html') return redirect(settings.LOGIN_REDIRECT_URL) return HttpResponse("why y r here") I can change my library if you have a better options. Thanks in advance. -
Difference between add_form and form
I'm currently reading a book on Django and reached the point where the author is creating a custom user model using the following code: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser admin.site.register(CustomUser, CustomUserAdmin) could someone possibly explain to me what is the difference between add_form and form? (if anyone could also tell me why we include both CustomUser and CustomUserAdminin admin.site.register(CustomUser, CustomUserAdmin) that would be great) thank you very much for your help! -
localhost not fetching data from pgadmin tables
I am trying to fetch PostgreSQL table data from localhost. Strange here because those tables I migrated from the pyCharm Django project. pgAdmin is filled with tables Not sure what went wrong, I double check my setting.py file and database is configured correctly 'ENGINE': 'django.db.backends.postgresql' along with DB name, username, password etc. also, /etc/paths have these paths. paths Please let me know if any information needed. I am using Mac OS V10.14.2 -
ValueError when saving using ModelMultipleChoiceField
I am writing a hotel reservation system. I have a Model called 'Reservations'. I am able to create a reservation with a start date, end date, reserve one room and assign 1 guest. However, when I went to modify the model, form and view to save more than 1 room and guest, I started getting a ValueError. The error I receive is: ValueError at /reservation/new Cannot assign "]>": "Reservation.fk_guest" must be a "Guest" instance. I understand that I need to assign an instance of Guest, but I don't understand how. /models.py class Property(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50, blank=True) state = models.CharField(max_length=2, choices=STATE_CHOICES, default='NY', blank=True) zip = models.CharField(max_length=5, blank=True) description = models.CharField(max_length=255, blank=True) class Meta: verbose_name = "Property" verbose_name_plural = "Properties" def __str__(self): return f"{self.name}" class Room(models.Model): name = models.CharField(max_length=25) number = models.IntegerField(blank=True) fk_Property = models.ForeignKey(Property, on_delete=models.CASCADE) class Meta: verbose_name = "Room" verbose_name_plural = "Rooms" def __str__(self): return f"{self.name} in {self.fk_Property}" class Guest(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) address = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50, blank=True) state = models.CharField(max_length=2, choices=STATE_CHOICES, default='NY', blank=True) zip = models.CharField(max_length=5, blank=True) phone = models.CharField(max_length=10, blank=True) email = models.CharField(max_length=50, blank=True) dob = models.DateField(null=True) class Meta: verbose_name = "Guest" verbose_name_plural = … -
How to add a value to dropdownlist which is not in database in Django
I have a dropdownlist which the value inside it are from a table of my database, I want to have "other" in dropdownlist that when user click on it a textbox be shown , so it is not part of database values. How can i add it to dropdownlist ? I added "other" to the database, but i know its wrong becouse "other" is not type of cars models.py : class Stocks(models.Model): ... car=models.ForeignKey(Cars,blank=True,null=True,verbose_name=_('car'),on_delete=models.SET_NULL ,to_field='carname') .... class Cars(models.Model): carname=models.CharField(max_length=128,verbose_name=_('carname'),unique="True") def __str__(self): return str(self.carname) class Meta: verbose_name=_('car') verbose_name_plural=_('cars') forms.py : class StocksForm(forms.ModelForm): class Meta(): model=Stocks fields=('car','stname','description','pic','price') .... view.py : def stock(request): st_form=StocksForm(None) if request.method == "POST": st_form =StocksForm(request.POST) ... return render(request,'BallbearingSite/stock.html',{'stocks_form':st_form,}) template : {{ stocks_form.as_p }} -
Find out why I'm getting HTTP 400 error codes when trying to post data
I'm trying to create an order by sending it as a POST request via my DRF API but I keep getting ""POST /shop/orders/ HTTP/1.1" 400 81" errors. The GET is working fine but I only have orders that I manually wrote in the DB. Our project is a fictional webshop where you can put dog babies in your cart and order them. The three main models that we have are Users, Orders and Puppies. Because every order has a list of puppies and every puppy has its own amount we needed an intermediary model for the two as a simple ManyToManyField apparently can't handle extra columns. This makes things much more complicated (at least for someone who is new to Django). I can't find anything on the internet for this special case. I have been trying to get this to work for almost a week now and I don't see what I'm doing wrong. models.py: from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Puppy(models.Model): name = models.CharField(max_length=30) price = models.DecimalField(max_digits=6, decimal_places=2) image_url = models.CharField(max_length=200) age = models.IntegerField(null=True) weight = models.IntegerField(null=True) description_de = models.CharField(max_length=500, null=True) description_en = models.CharField(max_length=500, … -
Django admin return different signed s3 url from DRF retrieve api view
I am setting up a private file upload field in my Django model, where users can upload documents and retrieve them. However, when I try to retrieve the URL from my view, it returns AuthorizationQueryParametersError but when I open the URL from my Django admin, it works correctly. I have noticed that the two URLs have different X-Amz-Signature class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False signature_version = 's3v4' models.py document = models.FileField(blank=True, storage=PrivateMediaStorage()) settings.py AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'BUCKETNAME' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_REGION_NAME = 'ca-central-1' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'MYPROJECT.storage_backends.MediaStorage' AWS_PRELOAD_METADATA = True AWS_PRIVATE_MEDIA_LOCATION = 'media/private' PRIVATE_FILE_STORAGE = 'MYPROEJCT.storage_backends.PrivateMediaStorage' these are the two different URLs I get: https://bucket.s3.amazonaws.com/media/private/ProgressBar.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AWS_ACCESS_KEY_IDcaca-central-1%2Fs3%2Faws4_request&X-Amz-Date=20190118T205749Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=cb387... https://bucket.s3.amazonaws.com/media/private/ProgressBar.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AWS_ACCESS_KEY_IDca-central-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20190118T205724Z&amp;X-Amz-Expires=3600&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Signature=3270... I expected the URLs to be the same, do I need to create an IAM role for every user? -
how to convert barcode render formatted string to html
I am generating a .svg file of barcode with barcode module. CODE128 = barcode.get_barcode_class('code128') package_no_barcode = CODE128(u'PLAI73664PJHS') when I use - package_no_barcode.render, I get - b'<?xml version="1.0" encoding="UTF-8"?>\r\n<!DOCTYPE svg\r\n PUBLIC \'-//W3C//DTD SVG 1.1//EN\'\r\n \'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\'>\r\n<svg height="23.000mm" version="1.1" width="38.000mm" xmlns="http://www.w3.org/2000/svg">\r\n <!--Autogenerated with python-barcode 0.9.0-->\r\n <g id="barcode_group">\r\n <rect height="100%" style="fill:white" width="100%"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="2.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="2.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="3.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.400mm" x="3.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="3.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.800mm" x="3.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="4.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="5.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="5.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="5.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="6.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="6.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="6.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="7.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="8.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="8.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="8.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="8.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="9.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="9.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="10.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="10.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="10.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="11.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="11.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" … -
How to call asyncio def from within Django view (and make it non-blocking)?
How can I run an async function from within Django view? I am trying the following: def tools(request): ids = get_ids() print(ids) return render(request, 'strava_tools/tools.html') def get_ids(): ids = [] async def main(): with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: loop = asyncio.get_event_loop() futures = [ loop.run_in_executor( executor, requests.get, 'https://www.strava.com/api/v3/athlete/activities?page={page}&per_page=200&access_token=11111111'.format(page=page) ) for page in range(1,4) ] for response in await asyncio.gather(*futures): for activity in response.json(): ids.append(activity['id']) pass loop = asyncio.get_event_loop() loop.run_until_complete(main()) return ids But it is throwing an error: RuntimeError: There is no current event loop in thread 'Thread-4' The get_ids function, however, works fine when run by itself in a separate module. Additionaly, is it a good idea, in order to make the function non-blocking for the Django's request-response cycle (so that tools.html can be rendered before the get_ids function ends), to turn the get_ids function into a Celery task? -
html template to pdf with images
I am using django and trying to render invoice pdf, pdf is generating successfully but images are not in pdf. Actually I want to add barcode image, so I dynamically generated a .svg file, but don't know how to put it into pdf. Here is what I am doing .. from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None html - <body> <div class="container-fluid"> <div class="row"> <div class="col-6"> <div class="row"> <div class="col-12"> <span> <img src="{{ package_no_barcode }}" alt="{{ package.package_no }}"> <br> {{ package.package_no }} .... view - class GenerateInvoicePdf(View): def get(self, request, *args, **kwargs): package = Package.objects.get(package_no=request.GET.get('package')) address = package.purchase.order_product.delivery_location CODE128 = barcode.get_barcode_class('code128') package_no_barcode = CODE128(u'{pkg_no}'.format(pkg_no=package.package_no)) if request.user.display_username == seller.display_username: data = { 'package':package, 'address':address, 'package_no_barcode':package_no_barcode, } pdf = render_to_pdf('pdf/invoice.html', data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %(package) content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") I also tried with cid - <img src="cid:{{ package_no_barcode }}" alt="{{ package.package_no }}"> Anyone know … -
custom django-admin command with user auth
I'm trying to use the custom commands from the documentation and I would like to use user authentication as follows: from django.core.management.base import BaseCommand from django.shortcuts import render from django.contrib.auth import authenticate class Command(BaseCommand): def handle(self, *args, **options): if request.user.is_authenticated(): # do something if the user is authenticated However, given that I'm not in a view, I can't use the request.user: NameError: name 'request' is not defined Is there any work around to make a function like this work? Thanks in advance, Alvaro -
Django create download button for each item in db
I have a site where people can upload tasks, and once their task is finished they should be able to download it. I have created a table that shows which are finished and a download button beside it. My question is how do I link that specific path to their file and serve it as a protected download using nginx? My table on the website looks like this currently: My views.py def dashboard(request): query_running = Usertasks.objects.all().filter(user=request.user).filter(TaskStatus__in=["Waiting", "Failed"]) query_finished = Usertasks.objects.all().filter(user=request.user).filter(TaskStatus="Finished") if not request.user.is_authenticated: return redirect('/account/login/') return render(request, 'dashboard.html',{'query_running':query_running, 'query_finished':query_finished,}) The corresponding HTML looks like this <div class="dashboard-2"> <div class="tasks-finished"> <h1>Finished tasks</h1> </div> <div class="tasks-list"> <table> <tr> <th>Name</th> <th>Task ID</th> <th>Status</th> </tr> {% for item in query_finished %} <tr> <td>{{ item.TaskNavn }}</td> <td>{{ item.TaskID }}</td> <td><a href="#">Download</a> </tr> {% endfor %} </table> </div> I have a column in my database that has the corresponding path to the file saved, so I can always query that if needed. It's named outputPath Thanks in advance! -
Passing first_name, last_name to User.objects.create_user() Django
I am trying to register users using their first name, last name, username, email and password. I see in the create_user in Django docs that first_name and last_name are included in the default fields of user model. However when I try to submit my register form, I get an error saying "create_user() takes from 2 to 4 positional arguments but 6 were given". What is wrong with my code? Anyway this can be fixed without creating custom user model? How can I pass the first_name and last_name to create_user() ? forms.py: from django import forms from django.contrib.auth import get_user_model User = get_user_model() class RegisterForm(forms.Form): first_name = forms.CharField() last_name = forms.CharField() username = forms.CharField() email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("Username is taken") return username def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password2 != password: raise forms.ValidationError("Passwords must match.") return data views.py: from django.contrib.auth import authenticate, login, get_user_model from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import LoginForm, RegisterForm User = … -
Import using 2 fields as id field
I have read the documentation for django import_export and noticed that we can import with import_id_fields which field to use as the import id. I was wondering if it is possible to use the combination of fields. For example, I have a model choice field month and name, so during the import, it takes two fields and uses as import id? P.S I apologize for my broken English (it is my 3rd language) models.py: class Book(models.Model): JANUARY = '1' FEBRUARY = '2' MARCH = '3' APRIL = '4' MAY = '5' JUNE = '6' JULY = '7' AUGUST = '8' SEPTEMBER = '9' OCTOBER = '10' NOVEMBER = '11' DECEMBER = '12' MONTH_CHOICES = ( (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March'), (APRIL, 'April'), (MAY, 'May'), (JUNE, 'June'), (JULY, 'July'), (AUGUST, 'August'), (SEPTEMBER, 'September'), (OCTOBER, 'October'), (NOVEMBER, 'November'), (DECEMBER, 'December'), ) name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True) author_email = models.EmailField('Author email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.DateField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) month = models.CharField( max_length=2, choices= MONTH_CHOICES, default=JANUARY, ) def __str__(self): return self.name admin.py: # Register your models here. class BookResource(resources.ModelResource): class Meta: model = Book …