Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Optimal implementation of custom intermediary model
class C: attribute_c = models.CharField() class B: class_a = models.ForeignKey(A) class_c = models.ForeignKey(C) foo = models.SomeField(null=True) boo = models.SomeOtherField(null=True) class A: attribute_a = models.CharField() items = models.ManyToManyField(C, through='B') How can I create a relation between class A and class C (through class B) without doing it through Forms.py? If I do use Forms.py without any previous modification, then the following error message appears, as expected: Cannot set values on a ManyToManyField which specifies an intermediary model. Use app.B's Manager instead. My problem: I have classes that are very similar to the ones I wrote above. They have been working fine until now, when some requirements changed. These requirements forced me to introduce a custom intermediary class, adding the attributes foo and boo. I have a ton of tests using FactoryBoy and thus creating instances of class A without using forms. If I have to manually insert this relation everytime I create an instance of class A, it will be a pain. What is the best way to circumvent this problem? PS: I'm using Django 1.11.17. -
ValueError: The view Account.views.Login didn't return an HttpResponse object. It returned None instead
Anyone has an idea why my code is not running on the line 'if user is not None:' onwards? traceback 1 2 Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 137, in _get_response "returned None instead." % (callback.module, view_name) ValueError: The view Account.views.Login didn't return an HttpResponse object. It returned None instead. [18/Jan/2019 21:59:25] "POST /login/ HTTP/1.1" 500 56866 views.py class Login(View): form_class = AccountForm template = 'login.html' def get(self, request): form=self.form_class(None) return render(request, self.template, {'form':form}) def post (self, request): if request.method=="POST": form = self.form_class(request.POST) if form.is_valid(): print('1') username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") print('2') user = authenticate(username=username, password=password) if user is not None: print('3') if user.is_active: login(request, user) return redirect('home.html') else: return HttpResponse("Inactive user.") else: return render(request, 'login.html') urls.py urlpatterns = [ ... path('emailverification/passwordchange/', views.PasswordChange, name='passwordchange'), ] template {%extends 'base_form.html'%} {%block content%} <div class=container-fluid> <form method="POST"> {%csrf_token%} <label for="username">username</label> <input type="text" placeholder="username" name="login" required><br> <label for="password">password</label> <input type="password" placeholder="password" name="login" required><br> <button type="submit" class="btn btn-success">Submit</button> </form> <div class="container signin"> <p>Do not have an account? <a href="{% url 'registration'%}">register here</a>.</p> <p>Forgot password?<a href="{%url 'passwordreset'%}">retrieve password</a></p> <p>Improve your password security.<a href="{%url 'passwordchange'%}">change password</a></p> </div> <div> {%endblock content%} -
Troubles making an user update view
I have a custom user model, subclass of AbstractBaseUser. I'm currently having troubles making an update view, so user could change his profile. Changing user through admin interface works fine. This is a form that I use to change user objects in both admin and app`s interface. class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user's password, but you can change the password using " "<a href=\"{}\">this form</a>." ), ) class Meta: model = User fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) password = self.fields.get('password') if password: password.help_text = password.help_text.format('../password/') user_permissions = self.fields.get('user_permissions') if user_permissions: user_permissions.queryset = user_permissions.queryset.select_related('content_type') def clean_password(self): return self.initial["password"] I'm using fields = '__all__' to be able to change all the fields through admin interface. But in app's intreface I want user to change only some fields. This in my view: def update_user(request): form = UserChangeForm(request.POST or None, instance=request.user, fields=('email', 'first_name')) if request.method == 'POST': if form.is_valid(): form.save() return redirect('home') return render(request, 'update_user.html', {'form': form}) return render(request, 'update_user.html', {'form': form}) If I pass fields parameter like that UserChangeForm(request.POST or None, request.user, fields=('email', 'first_name')) I get __init__() got an unexpected keyword argument 'fields' … -
Setup firebase mobile auth with django allauth
Is it possible to integrate firebase mobile auth with django-allauth? As all providers that are pre-configured in django-allauth are using OAuth2 protocol but not firebase mobile auth.