Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.8 makemigrations generates a duplicated migration every time due to validators
I have a model which has a field with the following validator: validators=[ FileValidator( allowed_extensions=ALLOWED_PHOTO_EXT, allowed_mimetypes=ALLOWED_PHOTO_MIME_TYPES, max_size=ALLOWED_PHOTO_MAX_SIZE, ) ], Here goes the validator itself @deconstructible class FileValidator(object): """ Validator for files, checking the size, extension and mimetype. Initialization parameters: allowed_extensions: iterable with allowed file extensions ie. ('txt', 'doc') allowd_mimetypes: iterable with allowed mimetypes ie. ('image/png', ) min_size: minimum number of bytes allowed ie. 100 max_size: maximum number of bytes allowed ie. 24*1024*1024 for 24 MB Usage example:: MyModel(models.Model): myfile = FileField(validators=FileValidator(max_size=24*1024*1024), ...) See https://gist.github.com/jrosebr1/2140738 (improved) """ extension_message = _("Extension '%(extension)s' not allowed. Allowed extensions are: '%(allowed_extensions)s.'") mime_message = _("MIME type '%(mimetype)s' is not valid. Allowed types are: %(allowed_mimetypes)s.") min_size_message = _('The current file %(size)s, which is too small. The minumum file size is %(allowed_size)s.') max_size_message = _('The current file %(size)s, which is too large. The maximum file size is %(allowed_size)s.') def __init__(self, *args, **kwargs): self.allowed_extensions = kwargs.pop('allowed_extensions', None) self.allowed_mimetypes = kwargs.pop('allowed_mimetypes', None) self.min_size = kwargs.pop('min_size', 0) self.max_size = kwargs.pop('max_size', DEFAULT_FILE_MAX_SIZE) def __call__(self, value): """ Check the extension, content type and file size. """ # Check the extension ext = splitext(value.name)[1][1:].lower() if self.allowed_extensions and not ext in self.allowed_extensions: message = self.extension_message % { 'extension': ext, 'allowed_extensions': ', '.join(self.allowed_extensions) } raise ValidationError(message) … -
Is there any way to override foreign key delete protection in Django?
I have a webapp that has been running for many years with a bunch of models interconnected via foreign keys with on_delete=models.PROTECT. That is what we want for normal operations. However, now I need to delete old data from the system (e.g. anything more then 2 years old), since things are starting to slow down due to the volume of data. Is there any way, as a one time thing, for me to override the on_delete protection? -
how to create a mysql website where each user has their own private info that they can insert change edit delete
I'm relatively new to mysql and I'm having trouble creating a website where a user registers and has access only to their private information. So far I have created a login/registration page that's linked to my mysql database using php and it works just fine. Every time a user registers, their userid, username, email, and password is inserted into my database. The only problem is I don't know how to make each user have their own private info such a contact list filled with names, numbers, and emails that they can change on the frontend once they have made an account. I was thinking about making a mysql table each time a user makes a new account, but from other stackoverflow posts, I learned that it was a bad idea. It stated that I should just have one giant table with all the users instead of separate tables. But I don't know how to do this and have each user have their own separate data. I have researched this for weeks and couldn't find anything online so I made this stackoverflow account to ask. I also want to mention that I'm using the mysql command line in cloud9 ide so … -
chained dropdown list using Django does not update
I have chained dropdown list using Django (1.11) and ajax. The country and province fields are chained. the form is displayed right. Yet, when I select a country the province does not update. Here is the model file class Country(models.Model): country_name = models.CharField(max_length=24, unique=True) class Province(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) province_name = models.CharField(max_length=24) class User_account(models.Model): first_name = models.CharField(max_length=24) last_name = models.CharField(max_length=24) user_country = models.ForeignKey(Country, on_delete=models.CASCADE) user_province = models.ForeignKey(Province, on_delete=models.CASCADE) The form file : class User_accountModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(User_accountModelForm, self).__init__(*args, **kwargs) self.fields['user_province'].queryset = Province.objects.none() class Meta: model = User_account fields = ['first_name', 'last_name', 'user_country','user_province'] The view file: class User_accountFormView(View): form_class = User_accountModelForm template_name = 'path to register_form' def get(self, request, *args, **kwargs): form = self.form_class(None) return render(request, self.template_name, {'form':form}) def load_provinces(request): country_id = request.GET.get('user_country') provinces = Province.objects.filter(user_country_id=country_id).order_by('name') return render(request, 'path to dropdown list template', {'provinces', provinces}) the url file: urlpatterns = [ url(r'^register/$', views.User_accountFormView.as_view(), name='register'), url(r'^ajax/load-provinces/$', views.load_provinces, name='ajax_load_provinces'),] The register_form html page: <div class="panel-body"> <form class="form-horizontal" action="" method="POST" data-provinces-url="{% url 'ajax_load_provinces' %}" id="registeration_form"> {% csrf_token %} {% include 'path/to/form_template.html' %} {% csrf_token %} {% include 'path/to/provinces_dropdown_list_options.html' %} <div class="form-group"> <div class="col-sm-offset-4 col-sm-7"> <button type="submit" class="btn btn-success"> submit </button> </div> </div> </form> </div> <script type="text/javascript" src=" {% static 'path/to/jquery_3.1.1.min.js' %}"> … -
Django-summernote works properly, but shows text with HTML tags
Recently, I decided to use Django-summernote to edit model-form text fields. I can use the editor without any problem. When it comes to rendering output of the text edited with this tool, it displays with html tags. Looked around a while but not found any solution. Any thoughts on this? -
success_url for Django LoginView?
High level question: Can I use the success_url attribute to change to where a view inheriting from Django's LoginView will redirect? I have a login view that looks something like the below (ignoring import statements): class MyLoginView(LoginView): template_name = 'myapp/mytemplate.html' success_url = reverse_lazy('myapp:my_success_view') However, my login view still redirects to my LOGIN_REDIRECT_URL from my settings.py. Is this the wrong way to change my redirect url in the view? -
Sending an email using sendgrid in a Django project using an HTML template
I am trying to send an email from my Django project using my Sendgrid account. For now, I am sending the email in the following way: import sendgrid import os from sendgrid.helpers.mail import * sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("test@example.com") to_email = Email("test@example.com") subject = "Sending with SendGrid is Fun" content = Content("text/plain", "and easy to do anywhere, even with Python") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) The code is taken from this link: https://github.com/sendgrid/sendgrid-python Now, what I want to do this in the content section, instead of doing a text/plain email, I want to send a nicely formatted HTML email. Preferably, I want some way to reference a template and pass in a context. Is there any way to do this? Thanks. -
How to use request inside of ViewClass
Im working recycle django polls app tutorial I've created Question model which contains authorized field, where i store id of users who are authorized to see questions class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') users = User.objects.values_list('id','username') authorized = MultiSelectField(choices=users,null=True) def __str__(self): return "{question_text}".format(question_text=self.question_text) I'm having a problem with writing my view, because idk how to use flask import request to get user id to show only those questions which are designed for logged in user class VotesView(generic.ListView): template_name = 'polls/votes.html' model = Question def get_queryset(request): return Question.objects.filter(authorized__icontains=request.user.id) Keep getting error: return Question.objects.filter(authorized__icontains=request.user) AttributeError: 'VotesView' object has no attribute 'user' or This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. Thanks for any help, i stucked for 2 days -
Django multiuser Signup Errors
I am new in django python world. I am trying to create a plateform where 2 kind of users can interact with each other, I tried every single strategy found online but every time getting error messages when i hit submit. I used Class AbstractUser for the signup / login common to all users and added an other model with OnetoOneField to it for the Providers , knowing that providers can be both seekers and providers. The first part is working fine but the Provider are throwing different kind of error messages depending on strategy employed and the Boolean Field is not triggered. using django 1.11 and python 3.6.4 Thank you for your help . Here are my models: from django.core.urlresolvers import reverse_lazy from django.views.generic import TemplateView, FormView, CreateView from users.forms import CustomUserCreationForm, ProviderForm from django.contrib.auth import authenticate, login from django.contrib.auth.mixins import LoginRequiredMixin from users.models import CustomUser, Provider from django.shortcuts import redirect, render class SignUp(FormView): form_class = CustomUserCreationForm template_name = 'registration/signup.html' success_url = reverse_lazy('home') def form_valid(self, form): # save the new user first form.save() # get the username and password username = self.request.POST['username'] password = self.request.POST['password1'] # authenticate user then login user = authenticate(username=username, password=password) login(self.request, user) return super(SignUp, self).form_valid(form) … -
Django CreateView Multiple Object Insert
I no have an idea what title should be, but here I have a case that if a form was submitted it will find data from other model and insert every matched. currently here my code. here my models.py class Foo(models.Model): name = models.CharField() value = models.DecimalField() class Bar(models.Model): name = models.CharField() date = models.DateField() foo = models.ForeignKey(Foo, related_name='foo') here my views.py class Foo(CreateView): fields = ('name', 'value') model = models.Foo def form_valid(self, form): self.object = form.save(commit=False) for i in range(30): self.object.bar.foo.append(self.object.id) return super(ModelFormMixin, self).form_valid(form) Bar have ForeignKey to Foo example if form was submitted with range(30) it will find Bar and insert (append) Foo id for every data. now i do with this, self.object.bar.foo.append(self.object.id) but error said 'Foo' object has no attribute 'bar' how to insert append multiple data to Bar from Foo(CreateView) ?... -
F() does not have type len for django
I am trying to use the F() for my queryset I had my previous question about using F() in F() expressions in django keeps giving me 0 but then somehow I figured, I cannot use F()'s length for my function. At first I did not get why then I figured ending up I was trying to do len(F()) which is why I am getting error since F() is type of <class 'django.db.models.expressions.F'> instead of a string or number type. Is there a way to get the F() value so I can use len(F())? Thanks in advance for any help. -
Django date validation, help needed
I tried to validate my DateField to accept only dates from today and future, but I don't know why it's accepting every passed date anyway. My models.py file: def present_or_future_date(value): if value < datetime.date.today(): raise models.ValidationError("The date cannot be in the past!") return value class Event(models.Model): title = models.CharField(max_length=50) text = models.TextField() date = models.DateField(default=datetime.now, validators=[present_or_future_date]) duration = models.TextField(default='0', blank='true') created_at = models.DateTimeField(default=datetime.now, blank='true') def __str__(self): return self.title -
Duplicate object in django, also duplicate child objects (related objects)
I want to learn how to copy an object but also copy the object referencing to that object. As an example (simplified): Model 1: version id name Model 2: file id file name file contents foreign key pointing to version Relationship: One version can have multiple files So one software version can have multiple files. I want to duplicate a complete version. Currently I have the following: def duplicate_version(request,id, MAC_address): new_version = Version.objects.get(pk=id) new_version.pk = None new_version.save() new_files = File.objects.get(version_id=id) <-- here I get the error new_id = new_version.id new_files.version_id = new_id new_files.save() return get_all_versions(request, MAC_address) I understand how to copy an object and change the id (=None). But how do I manage to duplicate all the related files? Error I get: Exception Value: get() returned more than one File -- it returned 2! -
No Product matches the given query with Django
After I deleted a product from Django Admin Panel all the urls seems not to work anymore, not being able to access the admin or anything within my page and I don't really know where the problem might be. I change the debug mode from true to false but still the same. Maybe someone had this issue before. this is my code views.py from django.shortcuts import render from .models import Product # Create your views here. def all_products(request): products = Product.objects.all() return render(request, "products.html", {"products": products}) urls.py from django.conf.urls import url, include from .views import all_products urlpatterns = [ url(r'^$', all_products, name='products'), ] models.py from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=254, default='') description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='images') def __str__(self): return self.name -
Add headers in request Django 2
I'm trying to add a header to the request. Like this: from django.test import TestCase, Client class TestBlabla(TestCase): def test_just_do_it(self): c = Client() c.get(path='/some_path', **{'SOME_HEADER': some_header_data}) And it's working for me in Django < 2.0, for example in Django 1.11. But in currently 2.0.5 - i can't add a header to request. Anyone knows, what's the matter? -
tôi bắt mắc phải một lỗi như sau : The view iot.views.post_new didn't return an HttpResponse object. It returned None instead
tôi bắt mắc phải một lỗi như sau : The view iot.views.post_new didn't return an HttpResponse object. It returned None instead. Hope everybody help please. This is my views.py file: def post_new(request): if request.method == "POST": form = PostForm(request.POST or None) if form.is_valid(): ct = form.save(commit=False) ct.author = request.user ct.upload_time = request.upload_time ct.save() return redirect('iot:detail', pk=ct.pk) else: form = PostForm() return render(request, 'iot/post.html', {"form":form}) -
Reverse and get_absoulute_url with django 2.0
I'm getting an error when accesing my url "...pokemon/list/" Reverse for 'pkmn-detail' not found. 'pkmn-detail' is not a valid view function or pattern name. What i'm trying to do is first show a list of the created pokemons, then link to the detail page of each one through it's number. I have defined a get_absoulte_url method and used reverse with it in my model, so here are my models, views, urls and templates relevant: pokeworld/models.py class Pokemon(models.Model): pkmn_number = models.IntegerField(unique=True) pkmn_name = models.CharField(max_length=30) pkmn_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='Normal') pkmn_desc = models.CharField(max_length=150) pkmn_slug = AutoSlugField(populate_from='pkmn_name', unique_with='pkmn_number') def get_absolute_url(self): return reverse('pkmn-detail', kwargs={'pk': self.id}) pokeworld/views.py class PokemonList(ListView): model = Pokemon template_name = 'pokeworld/pokemonlist.html' def get_queryset(self): return Pokemon.objects.all().order_by('pkmn_number') def PokemonDetail(request, pk): try: pokemon_id = Pokemon.objects.get(pk=pk) except Pokemon.DoesNotExist: raise Http404("Pokemon does not exist") return render(request, 'pokemondetail.html', context={'pkmn_id':pkmn_id}) pokeworld/templates/pokeworld/pokemondetail.html {% extends 'baseP.html' %} {% block title %} Detail {{ pkmn.pkmn_name }} {% endblock %} {% block content %} <h1>#{{ pkmn.pkmn_number }} {{ pkmn.pkmn_name }}</h1> <p><strong>Type:</strong> {{ pkmn.pkmn_type }}</p> {% endblock %} pokeworld/urls.py urlpatterns = [ ... path('pokemon/list/', PokemonList.as_view(), name='pkmn-list'), path('pokemon/detail/<int:pk>', PokemonDetail, name='pkmn-detail'), I really don't know what to edit, i've searched and searched but i don't know if i'm not understading the solutions that others have … -
Incorrectly created object when using signal
I'm want create new object using ORM from signal: pre-save or post-save. But the object is not created correctly and created new a object in CinemaUser instead the CinemaHistory. What I doing worng? models class CinemaHistory(models.Model): title = models.CharField(max_length=50) description = models.TextField() class CinemaUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) price = models.IntegerField() @receiver(pre_save, sender=CinemaUser) def cinema_history(instance, **kwargs): cinema_obj = instance price = instance.price if cinema: CinemaHistory.object.create(title='test', description=test) #and in CinemaUser will created new user new object instead the CinemaHistory -
Django rest framework, serializer invalid when sent through AngularJS
I'm having a problem where when I make a post request from my Angular application served through Django I get invalid serializers, even if the output is correct. I console log the sent data: {"email":"example@gmail.com","username":"example","password":"plaintextforthisexample","confirm_password":"plaintextforthisexample"} Which gives me the response Bad Request (which I have set to happen when serializer.is_valid() is false). However, if I copy and paste what's in the console log into the browsable API under raw data it accepts it and creates a user. I can successfully send get-requests to the same API and get the data back, and the permissions for getting and posts are the same, although that would result in another type of error. The content type is correct as well, when not I get a 415. If the URL is wrong I get a 500. And I can see on the Django server log that post requests are coming in. Could it be because I'm running it from an angular template and not a Django one? -
How To Create Edit Form To Edit A Data Entry In Django
views.py def edit(request, question_id): questioninfo = Question.objects.filter(id=question_id) form = ModelForm(instance=questioninfo) return render(request, "questions/edit.html", {"form": form}) models.py class Question(models.Model): question_add_user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) question_header = models.CharField(max_length=200, blank=False) question_contetnt = models.TextField(max_length=1000) question_add_date = models.DateTimeField(default=datetime.datetime.now) question_p_id = models.CharField(max_length=200) def __str__(self): if len(self.question_contetnt) > 30: return "[" + self.question_header + "] " + self.question_contetnt[0:30] + "..." else: return "[" + self.question_header + "] " + self.question_contetnt urls.py path('edit/<int:question_id>/', edit, name="edit"), Now when i try to go to edit/2 for example i recive this error: AttributeError at /questions/edit/65/ 'ModelForm' object has no attribute '_meta' -
Django serving static html file with javascript
I have an odd case where I'm trying to serve a static index.html file that holds a javascript bundle from webpack in it for vue.js files, but it is sending the incorrect javascript file contents. I've tried both sending the html file as a template view and simply reading the file contents and sending it as an html response. It sends the html file itself correctly, but instead of sending the contents of the javascript file it just copies the index.html content into the javascript file. I checked to make sure that I wasn't accidentally overwriting the javascript file with html content and that's not the case, the javascript is in correct form, but when it is sent to the browser this is what is seen: index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>testprojsimple</title> </head> <body> <div id="app"></div> <script src="js/myvuejs.bundle.js"></script> </body>` </html> myvuejs.bundle.js: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>testprojsimple</title> </head> <body> <div id="app"></div> <script src="js/myvuejs.bundle.js"></script> </body>` </html> Any ideas on why it would be re-sending the index.html content as the javascript file as well? -
Django multiple URL parameters that are agnostic to their order in the URL
I'm building an API which queries a database based on multiple URL filters. In this example there are two parameters which I would like to pass to my views: <tid> and <teams>. Note that in production there would be over 5 different parameters, so I'm trying to avoid brute force solutions. My intended approach was the following regular expression in urls.py url(r'(?P<teams>-?teams=[0-9]*)?(?P<tournaments>-?tid=[0-9]*)?', stats_views.game_query, name='stats_home') This RE successfully matches and passes any URL which is of the form /teams=####-tid=####, and both the teams= and the tid= parameters are optional (this is intended). The problem is that tid= always has to come AFTER the teams= part of the URL. For example if I were to enter the URL /tid=###-teams=###, the <tid> parameter would be passed to views with its intended value, but the <teams> parameter would be passed as None. -
Django - implementing AJAX into the page communication
I'm having trouble with implementing my Django application to function with AJAX/HTTP requests. I want the application to accept both options, but I seem to have trouble at doing so. the views.py that I'm using to separate the functionality based on whether or not the request is AJAX is from django.shortcuts import render, get_object_or_404 from countrydata.models import Continent from countrydata.models import Country from django.http import HttpRequest from django.http import HttpResponse def show_continent(request, continent_code=None): context = { "all_continents": Continent.objects.all() } if continent_code: continent = get_object_or_404(Continent, code=continent_code) context["continent"] = continent ''' if request.is_ajax: return render(request, "selectui/continentmenu.html", context) ''' if not request.is_ajax: return render(request, "selectui/index.html", context) return HttpResponse('') def show_country(request, continent_code, country_code=None): context = { "all_countries": Country.objects.all() } if country_code: country = get_object_or_404(Country, code=country_code) context["country"] = country ''' if request.is_ajax: return render(request, "selectui/countrytable.html", context) ''' if not request.is_ajax: return render(request, "selectui/index.html", context) return HttpResponse('') The commented lines were replaced by the other if-statement, because I had my index.html getting put twice into the websites and this is the fix I came up with. But I'm not sure if the AJAX-type httpresponse still needs some kind of content inside of it. The ajax.js I have to work with is $(function() { "use strict"; $("#continentMenu … -
Django/Ajax - How i post an Ajax as DateField to Django view
I have a html template with inputfields as Django forms {{ form.DateInput }}. If i submit this forms without Ajax (only with Django) my forms go to my view and it works but if i post it with ajax i post it successfull (status 200 ok) but when the debugger check, if my form valid then it fails. So how i have to post with ajax an django dateform? i think ajax post it just as string to the view and not as dateform. ps: if i check after submit the chrome->network->FormData it looks both the same. -
How to use boolean field in form - Python Django
I'm working on a Django blog, i want to use Boolean Field in Form Here is my Code: class CreateProductForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) content = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'id': 'ck-editor-area'})) excerpt = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'rows': '7'}), required=False) price = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Amount'})) status = forms.CharField(widget=forms.Select(choices=(('1', 'Active'),('0', 'Inactive'),), attrs={'class':'form-control'})) quantity = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'})) I want to change the Status field status = forms.CharField(widget=forms.Select(choices=(('1', 'Active'),('0', 'Inactive'),), attrs={'class':'form-control'})) with Boolean Field function (True or False) What should i do? Thank you