Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
edit content of table and send changes to database
I have a table that made it editable!something like this. <table> <tr> <th>Name</th> <th>Code</th> </tr> {% for item in list %} <tr> <td contenteditable='true'>{{item.name}}</td> <td contenteditable='true'>{{item.code}}</td> </tr> {% endfor %} </table> also I have a 'submit' button end of the table to submit users changes. now my questions are how to send edited data to my server? how to find which content was edited? which item of the list and which attribute of that was edited? also is there any better idea to editable table? I use django2 on my backend side. -
django raises MultiValueDictKeyError at / 'file'
I'm trying to create a view for uploading a .csv file and parsing it on the template but it's returning a MultiValueDictKeyError at / 'file' The template has <form method="POST" enctype="multipart/form-data">{% csrf_token %} <div class="file-field input-field"> <div class="btn"> <span>Upload a CSV FILE</span> <input type="file" name="file"> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text"> </div> <button class="waves-effect waves-light btn teal" type="submit">Upload</button> </div> </form> Then my views has import csv, io def data_upload(request): template = "home.html" csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a .csv file.') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quoteschar="|"): _, created = Table.objects.update_or_create( page=column[0], keyword=column[1], interval=column[2], email=column[3], billing=column[4], notes=column[5], ) context = {} return render(request, template, context) I'm wondering why it's returning the error(?). -
'_csv.writer' object has no attribute '_committed'
I am getting this error "'_csv.writer' object has no attribute '_committed' " while saving and download the CSV file at the same time I haven't tried anything because I am facing this error for the first time. def index(request): if request.method == "POST": url = request.POST.get('url', '') username = request.POST.get('username','') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price in zip(p_name,p_price): writer = csv.writer(response) writer.writerow([name.text, price.text]) csv_file = csv.writer(response) csv_save_obj = csv_save(username=username,csv_file=csv_file) csv_save_obj.save() return response return render(request, 'index.html') -
Django: Load template at runtime
I am trying to implement a plugin system with the app in my Django proyect. I am using Django 2.2 with Python 3.7 in a virtual environment and I have a method that loads the plugin (app). Then I have the applications in the apps directory and at runtime if the user installs one of these plugin (app) 1. I load the app in the INSTALLED_APPS variable (works fine). 2. I create and execute the migrations (works fine). 3. Charge the app url in the main urlpatterns (works fine). def InstallApps(self, pk): app = PyApp.objects.get(id=pk) app.installed = True app.save() with open('installed_apps.py', 'a+') as installed_apps_file: if installed_apps_file.write('apps.{}\n'.format(app.name.lower())): print('yes') else: print("no") # I load the app in the settings.INSTALLED_APPS variable with open('%s/installed_apps.py' % BASE_DIR, 'r') as ins_apps_file: for line in ins_apps_file.readlines(): settings.INSTALLED_APPS += (line.strip().rstrip('\n'), ) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() apps.populate(settings.INSTALLED_APPS) # Create and execute the migrations call_command('makemigrations', app.name.lower(), interactive=False) call_command('migrate', app.name.lower(), interactive=False) # Reload urlpatterns in memory urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: clear_url_caches() reload(sys.modules[urlconf]) return redirect(reverse('base:apps')) The problem is that when I try to navigate over the url of the recently installed plugin (app) it tells me that it doesn't find … -
Construct QuerySet that returns a list of the five objects with highest IntegerField values in the database
I am following the official Django tutorial and creating a polling website. I have the following models.py: from django.db import models class Question(models.Model): questionText = models.CharField(max_length = 100) pubDate = models.DateTimeField('published date') def __str__(self): return self.questionText class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choiceText = models.CharField(max_length = 200) votes = models.IntegerField(default=0) def __str__(self): return self.choiceText I would like the homepage to display the top 5 most voted on questions, but am struggling to construct the proper QuerySet to get this result. The only thing I have thought of doing is: def index(request): questions = Question.objects.order_by(*question.choice_set.votes*) #I left *question.choice_set.votes* like that because I'm not sure how to properly express that in code or if it is possible in this example Also, would it be better to give the Question class a method like returnMostVotedOn(numberOfQuestions) or is using a QuerySet the correct method? Thanks in advance. *If anyone can think of a better question title feel free to change it, I was struggling to briefly define my question. -
How to solve ImproperlyConfigured Error while using django.views.generic classes
models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Award_list(models.Model): award_id=models.AutoField(primary_key=True) award_name=models.CharField(max_length=50,blank=False) award_image = models.ImageField(default='award.jpg', upload_to='award_pics') def __str__(self): return f'{self.user.award_name} Profile' def save(self,*args,**kwargs): super().save(*args,**kwargs) img = Image.open(self.award_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.award_image.path) class Meta: verbose_name_plural = 'Award' views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import( ListView, DetailView, CreateView, UpdateView, DeleteView from . models import Award_list class AwardCreateView(LoginRequiredMixin,CreateView): models=Award_list fields=['award_name','award_image'] def form_valid(self,form): if request.user.is_superuser: return super().form_valid(form) award_list_form.html {% extends "users/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} urls.py from django.urls import path from .views import ( # PostListView, # PostDetailView, AwardCreateView, # PostUpdateView, # PostDeleteView, # UserPostListView ) from . import views urlpatterns = [ path('movies/awards/new/',AwardCreateView.as_view(),name='award-create') ] Getting Error ImproperlyConfigured at /movies/awards/new/ AwardCreateView is missing a QuerySet. Define AwardCreateView.model, AwardCreateView.queryset, or override AwardCreateView.get_queryset(). I have tried using template_name in url AwardCreateView.as_view() and views AwardCreateView but it's work getting same error ImproperConfigured. -
Password change field reset password django
I created a password reset system through email using django, but when I am at the password page, if I enter the password and confirmation right, it doesn't do anything just reloads the page and seems to throw in error in form.errors, but if i try to show the error nothing comes up. In addition, how do you make it so only one email can be assigned to a user. So when registering or changing your info, the same email can't be used with two accounts. Here is the code to my password reset page: {% extends 'base.html' %} {% block head %} <link href="\static\accounts\css\forms.css" rel="stylesheet"> <script src="\static\registration\js\emailvariable.js"></script> {% endblock %} {% block body %} {% if validlink %} <h3 style="text-align: center">Change password</h3> <form id="login-form" method="post"> {% csrf_token %} <input placeholder="Password" id="id_password" name="password" type="password" class="form-control"> <input placeholder="Confirm Password" id="id_password2" name="password2" type="password" class="form-control"> <div style="text-align:center;"> <button type="submit" class="btn btn-outline-dark centerbutton">Change password</button> </div> {% if form.errors %} <p class=" label label-danger"> <div style="text-align: center"> {{ error | escape }} </div> </p> {% endif %} </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} … -
Django can't load static files
I'm trying to load static files in my django project to the html template. My project structure as follow: base settings __init__.py defaults.py urls.py wsgi.py data web migrations static css fonts img js templates base base.html pages blank.html __init__.py admin.py apps.py models.py tests.py urls.py views.py I defined the following in my defaults.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'web/templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = 'web/static/' STATICFILES_DIRS = [ ] my views.py in the "web" app: from django.shortcuts import render # Create your views here. def blank_page(request): return render(request, 'pages/blank.html') urls.py in "web" app: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.blank_page, name='index'), ] urls.py in "base" app: from django.contrib import admin from django.conf import settings import sys admin.site.site_header = os.environ.get('ADMIN_SITE_HEADER') or 'Django administration' urlpatterns = [ path('admin', admin.site.urls), path('', include('web.urls')) ] if settings.DEBUG or 'test' in sys.argv: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns When i use href in my html template in base.html when calling to the root url from localhost i can't get the static file: {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/style.css' … -
Video streaming in Django: can it be done the same way as flask?
The following method from Miguel Grinberg has worked quite well for me in Flask, but I'm migrating my app to Django, and I was wondering if this can be recreated with built-in Django functions? from flask import Flask, render_template, Response from camera import Camera app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) This works quite well because my streams are motionJPEG, and that's what this code was designed for. I'm specifically wondering about the Response(gen(Camera)), mimetype='multipart/x-mixed-replace';boundary=frame') bit. how would I use a generator to place an incoming frame onto a url/route defined in urls.py? -
Is there a gui interface in moviepy to select the start and end time from video to trim it from webpage django
i want a user to select the start and end using some gui in django ! https://i.imgur.com/n40Shf0.png (something like this) For the time being the below mentioned code is what im doing. But it is not user friendly video.html <video controls> <source src="{{ url }}" type="video/mp4"></source> </video> <div class="row"> <form class="col s12" method="POST"> {% csrf_token %} <div class="row"> <div class="input-field col s6"> <input name="start_time" type="text" class="validate"> <label for="start_time">Start Time</label> </div> <div class="input-field col s6"> <input name="end_time" type="text" class="validate"> <label for="end_time">End Time</label> </div> </div> <input type="submit" value="Start" class="btn"> </form> </div> view.py if request.method == 'POST': start_time = int(request.POST.get('start_time')) end_time = int(request.POST.get('end_time')) path = "C:/Users/Macklon/Desktop/summer/cctv_modified/media/" clip = VideoFileClip(path+video).subclip(start_time, end_time) time = datetime.now().strftime("%H.%M.%S") print(clip.to_videofile(path+time+".mp4")) return render(request, "stream/video_list.html", {"url":video_url,"video_name":video_name}) -
RegexField is not passing validation
As a part of my form I'm using a RegexField with the regex pattern r'^\d{3}'. Once the form is submitted, I'm getting a KeyError when security_code = cleaned_data['security'] is reached. I understand that once a form's is_valid() method is called, the cleaned_data dictionary only retains those key/values that pass validation. I'm not understanding however why a user supplied string to this form field is not passing validation in this case. If I switch the RegexField to a CharField, then data for both fields appears in the cleaned data. from django import forms class CreditCardForm(forms.Form): cc_number = forms.CharField() security = forms.RegexField(r'^\d{3}', max_length=3) def clean(self): cleaned_data = super().clean() card_number = cleaned_data['cc_number'] security_code = cleaned_data['security'] if card_number and security_code: if card_number.startswith('4') and len(security_code) != 3: raise forms.ValidationError("Invalid credit card information") class CommentPage(View): def get(self, request): cc_form = CreditCardForm() return render(request, 'member_access/access.html', {'form' : cc_form}) def post(self, request): submitted_cc_form = CreditCardForm(request.POST) if submitted_cc_form.is_valid(): return HttpResponse("Submission successful!") return HttpResponse(reverse('member_access:user_login')) -
Custom permissions issue in DRF
Im working through Django for APIs by William Vincent and came across this authentication code in my Blog API. Basically it makes it so only the author of a blog post can edit/delete it. It seems too short to me, or missing some code. Mostly the "if author == request.user" wouldnt that just return True or False? Where is the code that actually restricts unauthenticated users? I think im missing something fundamental here. Code: # posts/permissions.py from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Read-only permissions are allowed for any request if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the author of a post return obj.author == request.user code here and here is the class it inherits from: class BasePermission(object): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True -
How do I throw a custom error that specifies what field needs to be filled out
How do I specify what field needs to be filled out when giving an error in django. Right now the error is just "this field is required," but how do I change this field into the actual field like password, or username or something. So instead of the normal error: "This field is required" it should give: "Password is required or Email is required," based of the field. Here is the code for the errors: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p class=" label label-danger"> <div style="text-align: center"> {{ error }} </div> </p> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} -
Django Admin: admin.sites.register(MyModel) doesn't work
By mistake I deleted the migration files, and now my Admin does not register my Models, apparently because they were already registered and appeared correctly but now they do not appear and do not register them, and also if I try to do 'admin.sites.unregister' it indicates that it's not registered. How do I force djago to register my model again? :( Here my admin.py from django.contrib import admin from .models import Post, Category # Register your models here. admin.site.register(Post) admin.site.register(Category) -
Django 2.x drf-yasg how to create API in a custom method (like in swagger)
I am migrating my Django 1.11.7 to 2.x. One of the problems is swagger, it is now deprecated. And I have to now use drf-yasg for the API documentation and creation. Previously, in swagger in looks like this (django-rest-swagger==2.1.1) here is the old code snippet that works nicely in Django 1.11.7: in url.py: url(r'^api/v1/general/get_countries$', api.get_countries, name='get_countries'), in api.py: @api_view(['POST']) def get_countries(request): # ----- YAML below for Swagger ----- """ description: countries list parameters: - name: token type: string required: true location: form """ ...... return Response(countries_list, status=status.HTTP_200_OK) My question is how to do it in drf-yasg similarly, as I want to migrate this code and dont break anything on the mobile. probably try to do this on this latest stable releases: djangorestframework==3.10.3 drf-yasg==1.16.1 -
'PermissionError: [Errno 13] Permission denied:' when uploading to /media/
I get this error PermissionError: [Errno 13] Permission denied: '/svr/portfolio/media/projects/2019-09-11_05-13-24.png' when I try to upload an image to /media/ from the admin panel I tried sudo chmod -R 770 /svr but it makes my entire website unusable due to permissions. With sudo chmod -R 755 /svr it becomes usable again -
Django: How to load related model objects when instantiating a model
I have two related models (1-n). From the parent model, I am doing a lot of operations on the child model. For each operation I am calling: ItensOrder.objects.filter(order=self.pk) What is the best way to load the related objects ONLY ONCE, so I can avoid reaching the database every time I need the related objects. I've been trying this on the parent model: def __init__(self, *args, **kwargs): if self.pk is not None: self.itens = ItensOrder.objects.filter(order=self.pk) else: self.itens = None But this is wrong.... Anybody can help please!? -
How do I get rid of the password constraints (eg. password has to be 8 characters, password can't be too similar to username, etc.) in django
I need to get rid of the password constraints in the default django password register system so that a user doesn't need to have the password be eight characters or the password can't be too similar to the username, and be able to add my own password constraints such as a strength detector. -
Python What is the difference between calling "self.property" and creating a method that returns "self.property"?
Lets say I have a class like this: class SomeClass: some_property = 'property' def get_some_property(self): return self.some_property def some_method(self): pass What is difference (if any) between var1 and var2 in the following: def some_method(self): var1 = self.some_property var2 = self.get_some_property() For a less abstract example of this question, consider the FormMixin class in django.generic.views.edit, which looks something like this: class FormMixin(ContextMixin): """Provide a way to show and handle a form in a request.""" initial = {} form_class = None success_url = None prefix = None ... def get_form_class(self): """Return the form class to use.""" return self.form_class def get_form(self, form_class=None): """Return an instance of the form to be used in this view.""" if form_class is None: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) The method get_form_class returns the form_class property of self, but isn't this exactly the same as calling self.form_class? -
How to group results into array based on similar values, Django Model/Serializers
also: how to group model data based on same values in django also 2: Group serializer results based on value Like the others above I need a results returned in a particular way. I would like to group together results which contain a similar value for one column. As stated above I would like to take this: number | points | player_id -------+--------+---------- 1 | 45 | 1 1 | 68 | 2 2 | 79 | 3 2 | 70 | 4 and get this [ { "number": 1, "records": [ { "points": 45, "player_id": 1 }, { "points": 68, "player_id": 2 } ] }, { "number": 2, "records": [ { "points": 79, "player_id": 3 }, { "points": 70, "player_id": 4 } ] } ] -
How to trigger an event when django foreignkey is modified
I want to update fields in django admin site following the modification by the user of a given foreignkey field. I seek a way to trigger the event straight after foreignkey modification; not before/after save. I looked for the creation of a custom signal through sender/receiver. Also I tried to find a similar signal as the m2m_changed. Perhaps one of these path could be the solution. class Variety(models.Model): specific_name = models.ForeignKey(CatalogList, on_delete=models.CASCADE) def update_other_field(self): #DO SOMETHING EACH TIME specific_name IS MODIFIED Is there a way to trigger an event directly after a foreignkey is modified? -
display flash message with django formview
I have a Django Form that logs when it encounters and error. I would like to improve it by providing visual feedback to the user when the submit fails. Can I use the messages framework with FormView? if so how? # views.py class EventImport(LoginRequiredMixin, FormView): template_name = 'polls/event_import.html' form_class = EventImportForm def form_valid(self, form): form.import(self.request) return super().form_valid(form) # forms.py class EventImportForm(forms.Form): url = forms.URLField() def import(self, request): logger = logging.getLogger('django') try: ... except: trace_back = traceback.format_exc() logger.warning('Failed to import. %s', trace_back) messages.add_message(request, messages.warning, 'Failed to import. ') logger.info('Import complete') error int() argument must be a string, a bytes-like object or a number, not 'function' on messages.add_message(...) -
What is "Application startup file" option on Cpanel python application?
I'm trying to deploy my django project to my host using cpanel, but there are some new options in Create python applications tab. What should i set for the following items: "Application startup file" "Application Entry point" create application -
Django does not raise validation error username and password
Django does not raise validation errors added to forms.py for username and password. It does bring up validation errors for password based on the core password validation, but will not check if passwords are the same. This is all based on the base User model in Django. Can you help me figure out why the forms validation does not work? I get the following error is username is already in use or passwords do not match: "Form is not valid." The if statement if form.is_valid(): fails. Forms.py: class CustomUserCreationForm(forms.ModelForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['username'] def clean_password(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def clean_username(self): username = self.cleaned_data.get('username') user_name = User.objects.filter(username=username) if user_name.exists: raise forms.ValidationError("Username already exists. Please try again.") return username def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.set_password(self.cleaned_data['password1']) if commit: user.save() return user Views.py: def payments(request): form = CustomUserCreationForm(request.POST) if form.is_valid(): password1 = form.cleaned_data['password1'] #this works to do Django core validation, but not form validation try: validate_password(password1) except ValidationError as e: form.add_error('password1', … -
Use a image from a server in Django template
Right now I'm storing the image in the static folder, but this is not working in production. View local_path = "checkimage/static/{}".format(image_file_name) download_blob(server_path, path + '/' + image_file_name, local_path) javascript let img = '<img src="/static/' + image_file_name + '/>'; Which is the correct approach to do this? They are several images and very heavy.