Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to send django multiple filefield's form data through ajax
I've a django form for FileField where I can input multiple files. I'm trying to send this list of files from django template to views using ajax. But in my views I'm getting False for form.is_valid. Also, form.errors shows: file_form.errors <ul class="errorlist"><li>file<ul class="errorlist"><li>This fi eld is required.</li></ul></li></ul> I'm sure I'm not passing the data correctly through ajax. Do you have any idea where I'm going wrong? My template: <form id="file-form" enctype="multipart/form-data", method="POST"> {% csrf_token %} <div id="id_file">{{ file_form }}</div> <br><br> <input type="submit" value="Upload files" name="_upload_file"/> </form> <script type="text/javascript"> $(document).on('submit', '#file-form', function(e)){ e.preventDefault(); $.ajax({ type:'POST', url:'/create-post/', data:{ files:$('#id_file').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ } }) } </script> Thanks in advance! -
Set the default billing address in admin form
I'm working on a Django project where I have several customers, each of which can have multiple postal addresses (office 1, office 2, office 3, ...). I have to choose the default address for each customer. I created a model for postal addresses with ForeignKey pointing to the customer model and in my customer model I entered a PositiveIntegerField to contain the default postal address ID. The problem is that I do not know how to filter in the Admin Form only the addresses relevant to the client and show the description of the address instead of a PositiveIntegerField. Some advice? -
How to avoid appending duplicates on ajax after second call?
I have a button called File which is a dropdown that has another button called open. Once the user clicks open I have an ajax GET request that appends a button after each call. When the user clicks open once, the button is appended. However, when the user clicks open again, the same button is appended again with the same attributes and if the user clicks the open button the third time the button is appended once more, so a total of three times. How do I ensure the button is only appended once? The {{}} is from the django web framework and is not a concern <input type = "button" class = "openGraph" value = "{{titles}}" id="{% url 'openGraph' title=titles.id %}"> This is the occurence when the user presses the open button. $(document).ready(function(){ $('#openXML').on('click',function(event){ var csrftoken = getCookie('csrftoken'); $.ajax({ type: "GET", url: "/loadTitles/", dataType: 'text', headers:{ "X-CSRFToken": csrftoken }, success: function(data){ var json = JSON.parse(data) var length = Object.keys(json).length var pk = "/openGraph/" + json[length-1]['pk'] var title = json[length-1]['fields']['title'] myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>"; $("#loadAllTitles").append(myButton) } }); }) }); Once you click button $(document).ready(function(){ $('.openGraph').on('click',function(event){ //alert("test") //var openUrl = $(this).attr('href'); $('#openModal').modal('hide'); var openUrl = $(this).attr('id'); var csrftoken … -
Best method to create an object with many to many field using Django RF API
I have started a project with an idea that's more than I know I can handle but hey... some of us learn the dumb way right? Currently have 2 models: User model that uses the AbstractUser class and then I have a Role model that provides many roles that may change over time so I need it to be dynamic. This is what my api/models.py looks like: from django.db import models from django.contrib.auth.models import AbstractUser from django import forms class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' CABLER = 1 CLIENT = 2 ENGINEER = 3 PROJECTMANAGER = 4 SALES = 5 PARTNER = 6 ADMIN = 6 ROLE_CHOICES = ( (CABLER, 'cabler'), (CLIENT, 'client'), (ENGINEER, 'engineer'), (PROJECTMANAGER, 'project manager'), (SALES, 'sales'), (PARTNER, 'partner'), (ADMIN, 'admin'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role, related_name='roles') I'm running into several problems but currently when I use postman or The DRF API views I can't create a user with roles or without roles. Attempting with roles: Direct assignment to the forward side of a many-to-many set is prohibited. Use roles.set() instead. Attempting without roles: { … -
Django administration is not accepting password
I used to log in with the same password and username. But today I can't log in anymore though I haven't changed anything. My Django version is 2.0 and the System is Ubuntu 16.04 I have cleared django sessions. -
More that one path for static files with django on IIS
With django (python server) is possible to add more that one path to serve static files using STATICFILES_DIRS = ("C:/some/path/static_two",) on settings file, and works fine, but on production server, in my case IIS, is that possible? I tried adding two virtual dirctories each one whit different paths/locations, but doesn't works, the static file from the second directiry "C:/some/path/static_two" doesn't shows. Someone can help me on how configurate IIS two serve static files from more that one location. thanks in advance. -
Allowing downloads of partial video files from Django
I have a Django app that allows users to make/save 'clips' of video files, that is keep timestamps of start and end times of video files to save in playlists. I would like users to be able to download clips (and playlists as well) they have saved. I have done quite a bit of research on the topic and have gotten ffmpeg working from my terminal to save partial clips (though I've struggled to figure out pathnames for using subprocess.call with ffmpeg), and I have also gotten moviepy working via the terminal to save partial clips. I'm struggling to figure out how to incorporate this into my Django app so that users can click a link and subsequently begin a download of a specific clip (or playlist). I believe I will want to use celery to avoid tying up the server but I'm not even to the point where I can offload a task as I can't figure out how to: 'Clip' the original, longer video file to make it shorter (do I need to make a local copy of a new file first?). Send a response as a download to the user. Here is my models.py: class Match(models.Model): game_id … -
How can I run a postgres command after database initialisation with Django
I'm trying to run some tests for a Django project and to do this Django creates a new database specific for running the tests. In my case the main database is named 'kim' and Django creates a database 'test_kim' to run the tests on. Since I have a CICharField in one of my models, I have to run this command after the database is created and before Django migrations run. psql =# \c db_1 CREATE EXTENSION citext; Now I'm wondering how I can run this command for the test database? -
How to accept data in ModelForm and display data from DB in same webpage
I want to have a ModelForm that accepts user input and on the same webpage, also display all the records in the database. I created one view with a ModelForm called views.users and another view that displays all the users from the database called views.display_users. How do I put these both in my urls.py file? My urls.py code is below. Thank you! # urls.py from django.contrib import admin from django.urls import path from app3 import views urlpatterns = [ path('users/',views.users,name='users'), path('users/',views.display_users,name='display_users'), ] -
Manage static link in js libraries within django
So I was trying to add an audio recording function to my website developed with django. I wanted to do something similar as https://github.com/addpipe/simple-web-audio-recorder-demo so I started by trying to run it without modification. I took the same html as in the git linked above, put the js/ folder in my static/ folder, and simply changed the following lines (index.html, line 32-33) <script src="js/WebAudioRecorder.min.js"></script> <script src="js/app.js"></script> for {% load static %} <script src={% static "js/WebAudioRecorder.min.js" %}></script> <script src={% static "js/app.js" %}></script> These js files load correctly, but the problem is that when I click record on my website, I get a "GET /myapp/record/js/WebAudioRecorderWav.min.js HTTP/1.1" 404 error in my django server. WebAudioRecorderWav.min.js is called within WebAudioRecorder.min.js. I tried to use the {% load static %} trick in the js file, but it doesn’t work. What would be the correct way to work around this? Thanks in advance. -
psycopg2.ProgrammingError: relation "django_content_type" does not exist
I'm getting the following error when I try to download my production database and use it on my local machine. Here's the process I followed: Downloaded and unzipped my (working) production database to my local machine. Run DROP DATABASE databasename; CREATE DATABASE databasename WITH OWNER databaseusername; on Postgres Run psql databasenamae < database_from_production.sql Run python manage.py migrate python manage.py migrate appropriately shows "No migrations to apply." at the top of the stack trace, but for some reason it's now erroring out afterwards. I can't just destroy and restore my production database, it has active user data. When I use a fresh DB on my local machine and run migrations, they apply fine. How can I address this issue? I'm afraid my production database has been corrupted somehow... Operations to perform: Apply all migrations: myapp1, myapp2, admin, auth, authtoken, myapp3, myapp4, contenttypes, myapp5, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "/Users/mysite/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File … -
ckeditor on django 2 blog
I need to add ckeditor in my blog. I did it but it doesn't work. I install and add ckeditor in my INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'ckeditor', ] Add in models.py: from ckeditor.fields import RichTextField class Post(models.Model): ... body = RichTextField(blank=True, db_index=True) ... And I have this: OR IT WORKS ONLY IN DJANGO ADMIN? -
Unable to view multiple thumbnails in a row
I want to Get Thumbnails in a row. It's Getting a single column I have Used Stock HTML Template The Template is working proper itself I have corrected the row class but it's not coming as required My Result {% extends "base.html" %} {% load static %} {{% block content %} <!-- ##### Listing Content Wrapper Area Start ##### --> <section class="listings-content-wrapper section-padding-100"> <div class="container"> <div class="row"> <div class="col-12"> <div class="listings-top-meta d-flex justify-content-between mb-100"> <div class="view-area d-flex align-items-center"> <span>View as:</span> <div class="grid_view ml-15"><a href="#" class="active"><i class="fa fa-th" aria-hidden="true"></i></a></div> <div class="list_view ml-15"><a href="#"><i class="fa fa-th-list" aria-hidden="true"></i></a></div> </div> <div class="order-by-area d-flex align-items-center"> <span class="mr-15">Order by:</span> <select> <option selected>Default</option> <option value="1">Newest</option> <option value="2">Sales</option> <option value="3">Ratings</option> <option value="3">Popularity</option> </select> </div> </div> </div> </div> {% if listings %} {% for listing in listings %} <div class="row"> <!-- Single Featured Property --> <div class="col-x-6 col-md-4"> <div class="single-featured-property mb-50"> <!-- Property Thumbnail --> <div class="property-thumb"> <img src="{{listing.photo_main.url}}" alt=""> <div class="tag"> <span>For Sale</span> </div> <div class="list-price"> <p>₹{{listing.price}}</p> </div> </div> <!-- Property Content --> <div class="property-content"> <h5>{{listing.title}}</h5> <p class="location"><img src="{% static 'img/icons/location.png'%}" alt="">{{listing.adderss}}</p> <p>{{listing.description}}</p> <div class="property-meta-data d-flex align-items-end justify-content-between"> <div class="new-tag"> <img src="{% static 'img/icons/new.png'%}" alt=""> </div> <div class="bathroom"> <img src="{% static 'img/icons/bathtub.png'%}" alt=""> <span>{{listing.bathrooms}}</span> </div> <div class="garage"> <img … -
Custom Django Rest Framework Serializer Field not running `to_representation()` if value is null
I would like a custom (read-only) serializer field that replaces the serialized value if it is None. I assumed that I could just overwrite to_representation(), but that doesn't seem to run. Here is some code: models.py: class Book(models.Model): title = models.CharField(max_length=255) rating = models.IntegerField(null=True) serializers: class ReplaceableSerializerField(serializers.ReadOnlyField): def to_representation(self, value): if value is None: return "this book sucks" return value class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ("title", "rating",) rating = ReplaceableSerializerField(allow_null=True) If I then do the following: hamlet = Book(title="Hamlet") BookSerializer(instance=hamlet).data I get the following response: {'title': 'Hamlet', 'rating', None} Notice how the rating is None instead of "this book sucks". Any idea on how to force to_representation() to run on null fields? -
How to fix deferred tasks being sent to not initialized instance?
My Google AppEngine website is using deferred tasks to do a lot of extra work. Sometimes the amount of deferred tasks cause a new instance to be created. When this happens, all the tasks that are delegated to this new instance fail because they get sent there before the instance has had a chance to initialize. If enough instances are already started up before the tasks come in, no issues occur. Is there a way to tell the deferred system to wait until an instance is fully initialized before sending tasks to it? I'm losing hair over this problem. -
MEDIA_ROOT error : _getfullpathname: path should be string, bytes or os.PathLike, not tuple
I'm new to Django's framework. When I use the MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), command in the settings, I encounter the following error when i trying to upload an image in http://127.0.0.1:8000/admin/products/product/add/ (admin mode): _getfullpathname: path should be string, bytes or os.PathLike, not tuple as i try i found deleting MEDIA_ROOT=... will also erase the error and the images will be placed correctly on the path on media's folder. I think the reason for using MEDIA_ROOT is to understand the path of the media files to Django, but : 1)why when I use it I will encounter an error 2) why I delete this command, everything goes smoothly? Thanks setting.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static'), error screenshot is getfullpathname: path should be string, bytes or os.PathLike, not tuple project/urls.py from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ #url will be here ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i have just an imagefield in my models.py: from django.db import models # Create your models here. class Product(models.Model) : name = models.CharField(max_length=100 , verbose_name="نام جنس",null=True,blank=True) category = models.ForeignKey('Category',on_delete=models.CASCADE , verbose_name="دسته بندی" , null=True ,blank=True) price = … -
Draft/public database pattern for articles with unique fields and multiple edition after published
I have to publish different Map-articles which must have draft/published version and the chance to keep modifying in draft mode after the map was published. The workflow is : create draft version -> wait for approval and publish -> edit draft version -> wait for approval and publish the update -> edit on draft version -> ... On each Map may appears many or none points of interest (PoI) or many or none routes, each PoI or Routes dataset cames from external APIs. On draft mode you could add or delete as many references to dataset as you need. Also, the Map model need an unique SLUG This way the model could be: Map: ID SLUG (Unique) Name Description CreationDate ... Data_Url: ID Type (PoI or Route) url name description ... and a relation of one to many [Map] --< [Data_Url] I found this post that is similar, but do not work for this case, because it don't work when you have unique fields and do not consider the scenario where you can edit the article(map) after is was published. Do you know any pattern that take care of this need. (I'm ussing django for this.) -
no views.py & models.py when I create django project in pycharm
It's weird, I'm using PyCharm as IDE and Linux as a server to create a Django project. After running startapp message on PyCharm Tools -> Run manage.py task, I can see regular dictionary and files on server(as Terminal display shown). But I could not find them on PyCharm screen(as PyCharm display shown). Why? Thank you guys, it's disturbed me for a long time... PyCharm display Terminal display -
Problem with datetime.time() comparison in a pre_save signal
I have those models: class Interval(models.Model): from_time = models.TimeField(auto_now_add=False) to_time = models.TimeField(auto_now_add=False) class CheckIn(models.Model): date_time = models.DateTimeField(auto_now_add=True) interval = models.ForeignKey(Interval, on_delete=models.SET_NULL) The main goal is: When a CheckIn is created the code should check if it's within the given interval's time. I need to compare those two and return their difference in %H:%M:%S format. What I've done so far: Since i have different scenarios what to do with the given CheckIn before it gets saved, I am using a pre_save signal and the time comparison is a part of these scenarios. Here is a pseudo: @receiver(pre_save, sender=CheckIn) def set_action_state(sender, instance, **kwargs): if something: ... if another: ... else: ... else: # instance.date_time.time() is 13:56:56.568860 (2 hours behind, it should be 15 instead of 13) # instance.interval.from_time is 15:07:40 if instance.date_time.time() < instance.interval.from_time: # this returns True when it's meant to return False instance.date_time is a timezone aware date, since i can print it's tzinfo which returns UTC instead of Europe/Sofia as of my TIME_ZONE in settings and I have no clue why. So I manually tried to set it's tz by doing: tz = pytz.timezone('Europe/Sofia') dt1 = instance.date_time.replace(tzinfo=tz) print(dt1.tzinfo) # which is the correct Europe/Sofia print(dt1) # which is 13:56:56.568860, … -
Could not find the GDAL library when starting new django project
I'm beginning on programming with python. I just finished to install all the requirements to start a new web project with django and OSGEO4W. I try to run "manage.py check" and it returns this error message: "django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library >(tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19", >"GDAL2.4.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in >your settings." First, I installed OSGEO4W 32 bits (because my python is in 32 bits) Then, I added an environment variable, there it is: GDAL_DATA = C:\OSGeo4W\share\gdal I believe that all is installed correctly because when I run "gdalinfo --version" in the command line tool it returns me: GDAL 2.4.0, released 2018/12/14 I already tested the existing topics, but I still can't resolve my problem.. I tried to change the libgdal.py file by adding some "gdal240", "gdal24", and so on, but nothing changes. I tried to set the variable as the message says as: GDAL_LIBRARY_PATH = os.getenv('GDAL_DATA') But this time, I get this message: OSError: [WinError 126] The specified module could not be found All I did is follow this tutorial to setup all these on windows: https://docs.djangoproject.com/en/2.1/ref/contrib/gis/install/#windows I don't know if you need more information, please ask and … -
How to delete a database (sqlite3) in Django==2.1?
I created the following models in my app events : from django.db import models from django.utils import timezone from django.urls import reverse class EventType(models.Model): type_of_event = models.CharField(max_length=100, unique=True) def __str__(self): return self.type_of_event class Event(models.Model): type_of_event = models.ForeignKey(EventType, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField() event_date = models.DateTimeField(default=timezone.now()) venue = models.CharField(max_length=200) entry_fee = models.FloatField() def __str__(self): return self.name Due to some errors and changes, I created and deleted the migration file many times. Now, the makemigrations command works but when I try to migrate the models using : python manage.py migrate , it shows the following error: File "/home/anirudh/.local/share/virtualenvs/Amrita-event-manager-DHqKHtGE/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 294, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: table "events_event" already exists I am using django version 2.1 along with sqlite3.