Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to explode text in one column from excel into 2 model in django?
I have a problem when explode text from one column in ms excel and insert it into 2 column in django models. this is my views.py class UploadFileForm(forms.Form): file = forms.FileField() def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_to_database( model=Transaksi, mapdict=['kode', 'kode','unit', 'nominal'], ) return HttpResponse("OK", status=200) else: return HttpResponseBadRequest('Gagal Upload') else: form = UploadFileForm() return render(request, 'kastransaksi/transaksi_formupload.html', {'form': form}) in my excel sheet, there are 3 column. How to explode one column from django views? -
Django - Ignore index error?
So I have a site where users can upload pictures attached to events which will then be shown in an instagram-type layout on the event page. Because of the way my page is designed, though, I can't just iterate the list. I have to call on each object individually (because I am putting them in various spots all over the page, not just in a simple list). Indexing has worked okay for this, but if I try to open an event which has less than the index amount, I get an error. Is there any way to avoid this? Or does anyone have an alternative solution? I need to be able to call on each item in a list individually so that I can individually format where it is and where it links to. views.py: def event_detail(request, slug): Event = Event.objects.get(slug=slug) image1 = Image.objects.filter(event__slug=slug)[0] image2 = Image.objects.filter(event__slug=slug)[1] image3 = Image.objects.filter(event__slug=slug)[2] return render(request, 'events/event_detail.html', { 'event': event, 'image1': image1, 'image2': image2, 'image3': image3, }) Then I call on the objects with {{ image1.url }} etc. Right now it's set up to support 3 (or more) images, but if the event has less than 3 images attached, I get the error. Very … -
Heroku build fail due to bonjour
Hello I am having an error when I am pushing my app to heroku , it says their is a build error with bonjour delisted me having remove bonjour from my requirements. I would really appreciate the help. Thanks below is my output from the terminal. castdrop ryan$ git push heroku master Counting objects: 10905, done. Delta compression using up to 4 threads. Compressing objects: 100% (5108/5108), done. Writing objects: 100% (10905/10905), 11.89 MiB | 6.41 MiB/s, done. Total 10905 (delta 4362), reused 10905 (delta 4362) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-2.7.13 remote: -----> Noticed cffi. Bootstrapping libffi. remote: $ pip install -r requirements.txt remote: Collecting altgraph==0.10.2 (from -r /tmp/build_0a1d196bd08bbb874d8bde1a1990ff5f/requirements.txt (line 1)) remote: Downloading altgraph-0.10.2.tar.gz (481kB) remote: Collecting bdist-mpkg==0.5.0 (from -r /tmp/build_0a1d196bd08bbb874d8bde1a1990ff5f/requirements.txt (line 2)) remote: Downloading bdist_mpkg-0.5.0.tar.gz remote: Collecting bonjour-py==0.3 (from -r /tmp/build_0a1d196bd08bbb874d8bde1a1990ff5f/requirements.txt (line 3)) remote: Could not find a version that satisfies the requirement bonjour-py==0.3 (from -r /tmp/build_0a1d196bd08bbb874d8bde1a1990ff5f/requirements.txt (line 3)) (from versions: ) remote: No matching distribution found for bonjour-py==0.3 (from -r /tmp/build_0a1d196bd08bbb874d8bde1a1990ff5f/requirements.txt (line 3)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected … -
WhiteNoise failing on collectstatic due to 'missing' file
When I enable WhiteNoise locally (added middleware, and STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage') but when I run collectstatic I get the error that The CSS file 'css/business-casual.css' references a file which could not be found: staticfiles/img/clouds.jpg. The file is definitely there (my css has a relative path to its storage spot in my staticfiles directory... I'm pretty sure I did it right). Removing the staticfiles_storage fixes it locally although I'm still having trouble deploying it to heroku. Not sure if the errors are related or not (Can't use django-compress with Heroku) This is pretty much a duplicate of this question, except my path is correct. -
Dynamic model choice field on a django cms plugin
I'm currently working on a django cms plugin with a model choice field dependent on another field in the form. What i'm doing now via ajax is that, when the trigger field is selected, the dependent model choice field is updated via ajax to change the choices in the select field. However on submit, of the form, i'm encountering this error “Select a valid choice. That is not one of the available choices.” I did some digging in stack overflow and found a similar issue While using ajax with django form, getting error "Select a valid choice. That is not one of the available choices." Based on the link above, i should update model choice field in the form of the plugin itself depending on the value of the trigger field which i will get from request.POST How do i go about doing this for a django cms plugin? Which method of the cms plugin should I override? I'm assuming its a method in the plugin's CMSPluginBase class but i'm not sure exactly what method to override and also how will i get the current form being used by my plugin so i could override that in the said method? … -
Dynamic URL in django
I'm so new to django. Please a quick help will be much appreciated. url(r'^shops/(?P[0-9]+)/$', views.shop_single, name='singleshop') is given me page not found error. models.py from __future__ import unicode_literals from django.db import models class SliderTitle(models.Model): slider_title = models.CharField(max_length=20) def __str__(self): return self.slider_title class Slider(models.Model): slider_type = models.OneToOneField(SliderTitle) slider = models.FileField(blank=True) def __str__(self): return str(self.slider_type) class ShopCategories(models.Model): category = models.CharField(max_length=50, unique=True) def __str__(self): return self.category class NewShop(models.Model): category = models.ForeignKey(ShopCategories) main_image = models.FileField() name = models.CharField(max_length=100, unique=True) tagline = models.CharField(max_length=50, default='Enter tagline here2') description = models.TextField(default='enter shop description') shop_image = models.FileField() def __str__(self): return self.name urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.homepage, name='homepage'), url(r'^about/', views.about, name='about'), url(r'^shops/(?P<Newshop_id>[0-9]+)/$', views.shop_single, name='singleshop') views.py def shop_single(request, Newshop_id): cat1 = NewShop.objects.filter(category_id=1) cat2 = NewShop.objects.filter(category_id=2) cat3 = NewShop.objects.filter(category_id=3) cat4 = NewShop.objects.filter(category_id=4) name1 = ShopCategories.objects.filter(id=1) name2 = ShopCategories.objects.filter(id=2) name3 = ShopCategories.objects.filter(id=3) name4 = ShopCategories.objects.filter(id=4) return render_to_response('shop_single.html', {'shop_name1': name1, 'shop_name2': name2, 'shop_name3': name3, 'shop_name4': name4, 'Shop_cat1': cat1, 'Shop_cat2': cat2, 'Shop_cat3': cat3, 'Shop_cat4': cat4, }) my DB from phpmyadin -
Adding a variable in Content disposition response file name-python/django
I am looking to add a a variable into the file name section of my below python code so that the downloaded file's name will change based on a user's input upon download. So instead of "Data.xlsx" it would include my variable (based on user input) + "Data.xlsx". I saw a similar question but based in PHP and couldn't figure out how to adapt it to python. response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename= "Data.xlsx"' Thanks in advance! -
Is it possible to start Daphne in a python script without using an OS call
Is it possible to run a daphne process or even just Django channels from a python script? The recommended way to do it, is to run daphne -b 0.0.0.0 -p 8001 django_project.asgi:channel_layer I was wondering if I could bind that to a variable and run it the way Tornado could from tornado.web import Application application = Application([(r"/", RosbridgeWebSocket), (r"", RosbridgeWebSocket)]) -
Django - csrf token not defined
What this code is supposed to do is let a user click they're description and be able to edit it. I have the modal popping up, but the save button will not save the data and produces the following error: Uncaught ReferenceError: csrftoken is not defined at HTMLButtonElement.<anonymous> (modalShortListDescription.js:6) at HTMLButtonElement.dispatch (jquery.min.js:3) at HTMLButtonElement.r.handle (jquery.min.js:3) Here's where the modal is called: <div class="tab-content col-xs-12"> {% for list in lists %} <input type="hidden" id="idList" id_list="{{list.id}}"> {% if forloop.first and not createTabActive %} <div role="tabpanel" class="tab-pane fade active in" id="list{{list.id}}"> {% else %} <div role="tabpanel" class="tab-pane fade" id="list{{list.id}}"> {% endif %} <div class="content col-xs-12"> <div class="form-horizontal sort-by col-xs-12"> <h3>Description</h3> {% if list.description %} <a href="#" data-toggle="modal" data-target="#modalDescription{{list.id}}" id="editDescription">{{list.description}}</a> {% else %} <a href="#" data-toggle="modal" data-target="#modalDescription{{list.id}}">None</a> {% endif %} {% include "layout/popUp/modal-short-list-description.html" %} </div> Here's the modal itself: <div class="modal fade" id="modalDescription{{list.id}}" role="dialog"> <div class="modal-dialog"> <form class="form-horizontal" action="{% url 'update-list-description' %}" method="post"> {% csrf_token %} <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Description</h4> </div> <div class="modal-body modal-body-exper modal-body-value modal-body-t"> <div class="lineEnterValue lineTeamSize lineTitle"> <div class="form-group {% if form.description.errors %} has-error{% elif form.is_bound %} has-success{% endif %}"> <div class="col-sm-10"> <textarea name="{{ form.description.html_name }}" class="form-control" id="{{ form.description.id_for_label }}" rows="5" style="margin: … -
Windows path python issues
Windows 10 user here, I installed python and Django, and I'm trying to install a website's data as per given tutorial with the command python manage.py loaddata -i fixtures/initial.json It returns an error: File "C:\Users\Joe\Envs\myproject\lib\site-packages\pillow-4.0.0-py3.6-win32.egg\PIL\Image.py", line 2312, in open PermissionError: [Errno 13] Permission denied: 'C:\Users\Joe\Envs\myproject\thesitename\media/' Could you help please? PS : the Windows path "c:\users" presents double backward slashes which do not display here, except for the last slash that is forward and single. -
Dynamically adding forms in formset not saving / Management form manual update?
I've been following this tutorial, and the form duplication/removal part works great however, the only the first form is saved. From the formset's data, I know the values exist as well as that form-TOTAL_FORMS should be 2 (or however many) instead of 1. I assume this is why geo_form.cleaned_data does not contain any of the second form. I'm assuming that if form-TOTAL_FORMS matched then all the form data would be there. If that is correct, how do I update the management form? If there is another solution how would I enact that? (Pdb) for k, v in geo_formset.data.items(): print k, v form-0-tables test1, test2, test3 form-0-name Shelburne, Burlington, Rutland form-1-state OR outfile x.xlsx form-MAX_NUM_FORMS 1000 form-0-survey ACS1 form-1-name Washington, Clackamas form-TOTAL_FORMS 1 form-0-years 2000 form-MIN_NUM_FORMS 0 form-INITIAL_FORMS 0 form-1-region county form-0-state VT form-0-region place Below is the view: class Start(View): def get(self, request): GeoFormset = formset_factory(GeographyForm) CensusFormset = formset_factory(forms.CensusForm) geo_formset = GeoFormset() cen_formset = CensusFormset() out_form = forms.OutfileForm() return render( request, 'start.html', { 'geo_formset': geo_formset, 'cen_formset': cen_formset, 'out_form': out_form } ) def post(self, request): GeoFormset = formset_factory(GeographyForm, min_num=1, validate_min=True, extra=0) CensusFormset = formset_factory(forms.CensusForm, min_num=1, validate_min=True, extra=0) geo_formset = GeoFormset(request.POST) cen_formset = CensusFormset(request.POST) out_form = forms.OutfileForm(request.POST) if geo_formset.is_valid() and out_form.is_valid() and … -
Django IntegrityError: NOT NULL constraint failed:
I keep getting the following error when trying to submit my form? File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) IntegrityError: NOT NULL constraint failed: courses_query.course_id The following is my query_create view: def query_create(request, course_pk,step_pk): #what course this quiz belongs to text = get_object_or_404(models.Text, course_id=course_pk, pk=step_pk) form = forms.QueryForm() #create blank form if request.method == 'POST': logging.error('Inside Post.....................................................................') form = forms.QueryForm(request.POST) if form.is_valid(): query = form.save(commit=False) #dont put anything in daabase make model quiz instance #query.course = course query.text = text query.save() messages.add_message(request, messages.SUCCESS, "Quiz Added!") return HttpResponseRedirect(query.get_absolute_url()) return render (request,'courses/query_form.html', {'form':form , 'text': text}) The following is my Query model: class Query(Step): times = models.IntegerField(default = 0, null=True) feedback = models.CharField(max_length=255, null=True) def get_absolute_url(self): return reverse('courses:query', kwargs={ 'course_pk': self.course_id, 'step_pk': self.id, }) -
Django static import on template
I'm trying to import a css file on my template. Here is the hierachy: -mega_series -mega_series -series -models.py -static -series -css -style.css ... -manage.py -media -covers -static Here is how I import it: {% load static %} <link rel="stylesheet" type="text/css" src="{% static "series/css/style.css" %}"/> In settings.py I have it: STATIC_URL = '/static/' Why isn't the css loaded? -
Combining Django Q Object Lookups into One Filter
I am having an issue with Q object lookups, whereas when user searches for multiple terms, the search returns nothing unless all terms are in the same object. If you go to https://www.soledadmemorial.com/plaques and search for David S Hackley the search returns nothing, but if you search for just David S you get a result. I've tried to combine the filter like (Q(first_name__icontains=query), Q(last_name__icontains=query)) but just get an error. Below is my current code. That works without combining searches form multiple objects. ... if query: queryset_list = queryset_list.filter( Q(first_name__icontains=query) | Q(last_name__icontains=query) | Q(branch__icontains=query) | Q(rank__icontains=query) | Q(group__group_name__icontains=query) | Q(veteran__name__icontains=query) ).distinct() ... -
Django ManyToMany CreateView Fields In Both Tables
I have two models, there are Book and Author and I add ManyToMany field inside Book model class Author(models.Model): name = models.CharField(verbose_name='name', max_length=50) created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return unicode(self.name) class Book(models.Model): title = models.CharField(verbose_name='title', max_length=50) authors = models.ManyToManyField(Author) # Many to many created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return unicode(self.title) If I want to create CreateView from book and access authors, I can just add code like this class BookCreateView(CreateView): model = Book template_name = "books/book_create.html" fields = ['title', 'authors'] but something that I want to ask is I want to create CreateView from Author model and add field named books inside it. I tried to code like this class AuthorCreateView(CreateView): model = Author template_name = "books/author_create.html" fields = ['name', 'books'] and it shows an error "Unknown field(s) (books) specified for Author". help me masters, I'm new in django Thanks :) -
Django get absolute url of Rest framework view
In my django application I am trying to get the absolute url of an endpoint view which is defined as follows: class ProductViewSet(viewsets.ModelViewSet): lookup_field = 'uuid' serializer_class = ProductSerializer permission_classes = (AllowAny,) def get_queryset(self): ... return queryset urls.py router = routers.SimpleRouter() router.register(r'products', ProductViewSet, base_name="product") urlpatterns = [ url(r'^', include(router.urls)), ] models.py from django.core.urlresolvers import reverse class Product(models.Model): uuid = models.UUIDField(default=uuid1) def get_absolute_url(self): return reverse('product', kwargs={'uuid': self.uuid}) however when I do this and try to get the url for a specific product I get an error Reverse for 'product' with arguments '()' and keyword arguments '{'uuid': UUID('d89-f530')}' not found. 0 pattern(s) tried: [] I tried different things but the error is still same, I am not sure how urlresolver works with DRF router view. just as a side note, I am using django 1.10 Any help on this would be really appreciated Thanks -
Django App for User-Created Surveys
I'm looking for a way in my Django app to allow a random user to create a survey for other users to take. To do it on my own, it'd probably involve a handful of JQuery and Django VooDoo. I've seen a lot of survey apps through pip and google, however a lot of them seem to be deprecated or only restrict surveys through the admin portal. I'm currently using Django 1.8 and Python 3... and with most apps using 1.5 or below and Python 2, this proves a bit problematic. Is there an already-built app out there or a more common way of achieving my goal? -
SELECT on JSONField with Django
My application is heavily reliant on APIs that unpredictably make changes to the way they return data. For this reason, I've chosen to use PSQL and JSONFields with Django. I've seen plenty of examples/docs on how to filter by values in a JSONField, but I haven't seen any that allow me to SELECT on these values. What I know works; queryset.filter(jsonfield__key_name = 'value') What I want to know how to do; queryset.values('jsonfield__key_name') Thanks in advance! -
Calling specific field on form.save() Django ModelForm
I have a form where users can add videos to an event. When they submit, I want them to be redirected to the event page, but I'm having trouble figuring out the code necessary. Here's my code: views.py: def add_video(request): if request.method == "POST": form = AddVideo(request.POST) if form.is_valid(): event = form.save() return redirect('event_detail', slug=event.slug) else: form = AddVideo() return render(request, 'add_video.html', {'form': form}) models.py: class Video(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) url = models.CharField(max_length=255) urls.py: url(r'^climbs/(?P<slug>[-\w]+)/$', views.event_detail, name='event_detail'), When I run this code, I keep getting an error that the Video model has no attribute slug. This attribute is found under the Event model. How do I pull the Event from the form and use the corresponding slug? -
How do I update the user's model fields in Django?
I'm currently creating a Social platform with Django. Right now, I'm developing the Profile Settings page and want endusers to be able to change their Header and Display-image. However, I'm not able to make the form work. Both the Header and Display-images are passing correctly through the POST form and end up getting stored in the media root, from where I call all my Header and Display-images in the template. So the problem right now is refering the submitted images as a Header or Display-image for the current user. This is my Profiel (dutch for Profile)Models.py: class Profiel(models.Model): user = models.OneToOneField(User, primary_key=True) Profielfoto = models.ImageField(blank=True, upload_to="profile_image", default="profile_image/no_profile_pic.jpg") Profielheader = models.ImageField(blank=True, upload_to="profile_header") Biografie = models.CharField(blank=True, max_length=150, default="Biografie nog niet ingevuld.") def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profiel.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) and my Views.py @login_required def profile_edit_view(request): if request.method == 'POST': form = Edit_profile_forms(request.POST, request.FILES) if form.is_valid(): form.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('profiel_edit')) else: form = Edit_profile_forms(request.POST, request.FILES) args = {'form':form} return render(request, 'Dashboard/profiel_edit.html', args) I think this is the only thing needed to show you guys for solving this problem, as the form is doing everything else correctly. So my end question … -
Inconsistent Django ORM Query Results With "Q" vs "__in"
I'm trying to find all instances of one of my models that has an attribute set either to None or to an empty string. I think I'm missing something about the ORM's __in query. TextBlock.objects.filter(content='').count() >185 TextBlock.objects.filter(content=None).count() >235 TextBlock.objects.filter(content__in=['', None]).count() >185 TextBlock.objects.filter(Q(content='')|Q(content=None)).count() >420 TextBlock.objects.filter(content__in=[None, '']).count() >185 When I do this with an IntegerFIeld and not using None or empty strings, I get: TextBlock.objects.filter(order=1).count() > 575046 TextBlock.objects.filter(order=2).count() > 11946 TextBlock.objects.filter(order__in=[1,2]).count() > 586992 This is what I'd expect. Was I wrong to expect TextBlock.objects.filter(content__in=['', None]).count() to return 420 results? If so, why? The Q query does what I want, so I'll end up going with that, but I'm still curious about why that third query didn't do what I wanted. Thanks! -
Django Check if Integer Exists in Database Field Array
I have a database with a field that is a "pseudo" array. This array holds integer values. My implementation is as follows: attendees = models.TextField(null=True) # declaring the integer array When I say pseudo, I mean that I am using json to make it into an array. attendees=json.dumps(members) Now the attendees column will contain something like this ["1", "2", "3"] So I want to check if attendees will contain the value "1" for example. Essentially, I want something like this: eventList = Events.objects.all().filter(user_id in Event.attendees) # I know this isn't the correct syntax Any ideas on how to do this as efficiently as possible? -
issue with installing psycopg2
When I try to run "sudo pip install psycopg2" I get this error, I think the problem is at importing setuptools, but I have setuptools already setup, and cannot figure out why its complaining. Command "/usr/bin/python -u -c "import setuptools, tokenize;file='/private/tmp/pip-build-CT6e5f/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-Zvj8Ut-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-CT6e5f/psycopg2/ -
Clean data for many boolean fields in Django Form
Hi I have in a model with 4 bolean Fields: example: method_1 = models.BooleanField(default=False) method_2 = models.BooleanField(default=False) method_3 = models.BooleanField(default=False) method_4 = models.BooleanField(default=False) I want to validate if any field is checked for True otherwise raise a forms.ValidationError User must check 1+ method as True or receive an ValidationError When i try to validate each field i receive 3 of them are None and 1 validated is False or True Is it posiible to validate them all in 1 cleandata function? -
Error : 'QuerySet' object has no attribute 'append'
I'm a novice in Django who following a bit outdated tutorial. anyone who can advice my issue would be much appreciated. I'm testing an GET request which expecting to get all user list. GET request encounters " 'QuerySet' object has no attribute 'append' " below is UserProfile model. class UserProfile(models.Model): user = models.OneToOneField(User) nickname = models.CharField(max_length = 128) comment = models.TextField() country = models.CharField(max_length = 128, blank = True) url = models.CharField(max_length = 128, blank = True) ignores = models.ManyToManyField(User, related_name = 'ignore_set', blank = True, null = True) def __unicode__(self): return "%s"%(self.user,) def serialize(self): data = { 'user':self.user_id, 'username':self.user.username, 'nickname':self.nickname, 'comment':self.comment, 'country':self.country, 'url':self.url, 'ignores':[], } return data below is the view.py (please refer api/user/list ) def user_view(request, method): # api/user/create: api that creating new account. if method == 'create' and request.method == 'POST': try: username = request.POST.get('username') password = request.POST.get('password') if User.objects.filter(username__exact=username).count(): return HttpResponse('duplicate id', 400) user = User.objects.create_user(username,password=password) user.first_name = request.POST.get('name','') user.save() profile = UserProfile() profile.user = user profile.save() return toJSON({'status':'create success'}) except: return toJSON({'status':'bad request'},400) #api/user/update: api that update user's oldpassword with new one elif method == 'update' and request.method == 'POST': try: username = request.POST.get('username') password = request.POST.get('oldpassword') newpassword = request.POST.get('newpassword') user = User.objects.get(username__exact=username) if user.check_password(password) …