Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pip install django~=1.11.0 command = AttributeError: 'tuple' object has no attribute 'filename'
I am trying to install Django after pip upgrade through command: pyhton -m pip install --upgrade pip Then, when i run this command: pip install django~=1.11.0 I get tons of errors : AttributeError : 'tuple' object has no attribute 'filename' Anyone with the quick solution? -
A bug or not a bug (get_paginate_by)
This is a code from Django itself. Please, pay attention that queryset is not used in the method. Well, I can't even imagine how it can be used here. Could you tell me whether this is a bug or not? If it is, I could raise a ticket at Djangoproject. If this is not a bug, we should clarify the purpose of this parameter in the comment. In this case I also could raise a ticket. Or everything is ok here? django/views/generic/list.py class MultipleObjectMixin(ContextMixin): def get_paginate_by(self, queryset): """ Get the number of items to paginate by, or ``None`` for no pagination. """ return self.paginate_by -
Django-admin forgot password not working
In Login.html I found that forgot password links but it does not appear on the screen so I delete the {% if password_reset_url %} section and it become like that but another error I have. As you can see the forgot password link not going to password_change form. So how can I configure that {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} -
Is there a simple method to make it as `""` instead of `None` in the template input?
In the template use the {{ data.user_data.id_card }} to show the value, but I get the None in it: Is there a simple method to make it as "" instead of None in the input? Because I think use the {% if %} is too trouble, and not concise in my code. If there is a template-filter method I can use? -
Check in a view whether it is tests running or not
Django 1.11.5 In production I am going to paginate lists by 10. But for testing purposes I want all the results be shown in the same page. Then with Selenium I select everything by class name, create a set of IDs and compare it with an expected set of IDs. Let's suppose my fixtures contain 28 objects. So, for me paginate by 30 will be Ok for testing purposes. So, I need a tool to check whether it is a test that is running right now or not. Well, at first I tried debug as an indicator: views.py if settings.DEBUG: PAGINATE_BY = 30 else: PAGINATE_BY = 10 tests.py class ComplexSearchForPlaces(StaticLiveServerTestCase): pass This is not a very good idea as in the debug mode and in production we should get more or less the same result. But I would be satisfied. But LiveServerTestCase seems to be setting DEBUG=False. I put a breakpoint - well, it is FALSE. Then I tried to catch the port. But ports seems to be changing. Proof: https://docs.djangoproject.com/en/1.11/topics/testing/tools/#liveservertestcase The live server listens on localhost and binds to port 0 which uses a free port assigned by the operating system. Could you tell me how to check in … -
Downloaded boostrap.min.js does not work in Django template
Downloaded boostrap.min.js did not work in Django template but CDN boostrap.min.js did. Here my base.html code which did not work: Local boostrap.min.js not work i can even open the link of javascript in developer mode of Chrome When i change the code as below, it worked as normal : CDN boostrap.min.js work ps:This is just an example, in an other app, my downloaded boostrap CSS and static files like image and fonts worked but boostrap did not -
Django - Cycle Tag. How can I make it work?
I am a total newbie to Django. I am trying to implement cycle tag. To no avail. My view.py: def music(request): my_list = ['Ravel', 'Bach', 'Verdi', 'Janacek'] context ={'my_list': my_list} return render(request, 'music.html', context) My template file: <head> <style> .row1 { background: #FFFF00; } .row2 { background: #FF0000; } </style> <h1>Music</h1> </head> <body> {% for o in my_list %}<tr class="{% cycle 'row1' 'row2' %}"></tr>{% endfor %} </body> What am I doing wrong? -
Django test: Setting cookie (Django 1.11+)
I have troubles setting cookie in Django test. class Test_views(TestCase): @classmethod def setUpClass(cls): pwd = '12345' cls.c = Client() cls.user_1 = UserFactory(password=pwd) cls.c.login(username=cls.user_1.username, password=pwd) super(Test_views, cls).setUpClass() @classmethod def tearDownClass(cls): super(Test_views, cls).tearDownClass() def test_set_cookie(self): session = self.c.session session['mycookie'] = 'testcookie' session.save() response = self.c.get(reverse('homepage')) ... I print the cookies in the Views to be sure: views.py ... def homepage(request): print(request.session.keys()) ... And indeed, the cookie mycookie doesn't exist. Apparently, that's the right way to set cookie: https://docs.djangoproject.com/en/1.11/topics/testing/tools/#django.test.Client.session -
Django Check if Username already exists
Here's my forms.py, class RegistrationForm(UserCreationForm): class Meta: model = User fields = [ 'username', 'first_name', 'password1', 'password2'] def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] if commit: user.save() return user In views.py, def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() .... How can I check if 'username' already exists. If it exists I wanna raise form validation error. How can I do that? Thank You :) -
Django - Modify Inlineformset Delete button
I do a custom UI/UX for an inlineformset. By default the inlineformset widget has a delete button. I wan to add and remove forms from inlineformset dynamic using javascript. In some cases the delete is just a button instead of the checkbox, in other cases is in a modal window. When a user click delete the form is removed from the page with javascript. So, I try to do this without using the default widget, render fields in the template, but I don't know how to tell Django witch fields to remove and if is necessary to readjust the ids and names of the fields. -
Referer checking failed (uri does not match referrer uri) error in Django app
I'm testing a basic Django app (fresh install) with gunicorn and nginx reverse proxy. I keep running into 403 errors of the following sort upon each and every POST request: Referer checking failed - http://ec2-xx-xxx-xx-xx.ap-south-1.compute.amazonaws.com/signup/ does not match https://ec2-xx-xxx-xx-xx.ap-south-1.compute.amazonaws.com/. This even comes if I'm trying to enter superuser credentials in the admin panel. There's no SSL installed on the server, hence I wanted to check the website in a purely http environment. However, it seems I keep getting forced to https. There's no overt flag I've set in settings.py to do this, nor does the error go away in incognito browsing (in case someone thinks it's HSTS persisting). What could be going on? Ask for more information in case you need it. -
CSRF_FAILURE_VIEW (from settings.py) being called on each post request. Need debugging assistance
I'm testing a Django app. I just did a fresh install on test AWS micro EC2 instance. Next, I installed Postgresql (and a connection pooler), then gunicorn with nginx reverse proxy, then ran syncdb and fired up the app to create a few users. I've used this app's virtual env on and off for over a year now. It's never failed me. However, currently the moment I enter anything and send a POST request, I am shown the default view I've set as CSRF_FAILURE_VIEW in settings.py. It even happens if I try to enter the admin panel. I'm using the same browser I've always used (Firefox), and tested it on a couple of other machines and browsers as well. django.middleware.csrf.CsrfViewMiddleware is part of my middlewares. django.core.context_processors.csrf is part of my template context processors. What could be going on? Can someone help me debug this? -
Field name `user_username` is not valid for model `Profile`
Error Name: Field name user_username is not valid for model Profile I'm building my Edit Profile View. Here is my views.py class ProfileEditAPIView(DestroyModelMixin, UpdateModelMixin, generics.RetrieveAPIView): serializer_class = ProfileEditSerializer def get_queryset(self): logged_in_user = User.objects.filter(username=self.request.user.username) return logged_in_user def get_object(self): queryset = self.get_queryset() obj = get_object_or_404(queryset) return obj.profile def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) I can get user_id correctly but somehow I can't access to its username field This is serializers.py class ProfileEditSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ( 'user_username', <<< 'title', 'gender', 'birth', 'height', 'height_in_ft', 'profile_img', ) Why can't we access to user's username? And how can we solve this? Thanks -
Images are not in ImageAndUser model
Images are not in ImageAndUser model.I wrote in views.py like @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = ImageAndUser() data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) index.html is <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <h2>SEND PHOTO</h2> <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> SELECT FILE <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> When I put SEND button, upload_save method is read.And my ideal system is image& user's data put in ImageAndUser model.However,now ImageAndUser model does not have the data.I really cannot understand why.But terminal says <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required</li></ul></li></ul> so I think i cannot get user data.However,I think user can access upload_save method after he log in the site, so I think the system has user data.I do not know why image&user data is not connected. models.py is class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images/', null=True, blank=True,) How can I fix this?What should I write it? -
Django encoding error when reading from a CSV
When I try to run: import csv with open('data.csv', 'rU') as csvfile: reader = csv.DictReader(csvfile) for row in reader: pgd = Player.objects.get_or_create( player_name=row['Player'], team=row['Team'], position=row['Position'] ) Most of my data gets created in the database, except for one particular row. When my script reaches the row, I receive the error: ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.` The particular row in the CSV that causes this error is: >>> row {'FR\xed\x8aD\xed\x8aRIC.ST-DENIS', 'BOS', 'G'} I've looked at the other similar Stackoverflow threads with the same or similar issues, but most aren't specific to using Sqlite with Django. Any advice? If it matters, I'm running the script by going into the Django shell by calling python manage.py shell, and copy-pasting it in, as opposed to just calling the script from the command line. -
Django messages still shows after page reload
I'm using the following library for notifications: noty Using the following snippet on template: {% if messages %} {% for message in messages %} <script> new Noty({ type: "{{ message.tags }}", layout: "topRight", text: "{{ message }}", timeout: 30000 }).show(); </script> {% endfor %} {% endif %} If I refresh the page the message still appears, as far as I know django messages are deleted after iteration but I don't know how to fix this problem -
Why apache with mod_wsgi timed out?
I was using apache with mod_wsgi to deploy my django project. What I do was: 1. python manage.py startproject mysite as the python tutorial guides, add to apache conf/httpd.conf the following configuration: ServerName www.example.com ServerAlias example.com ServerAdmin webmaster@example.com WSGIDaemonProcess example.com processes=2 threads=15 display-name=%{GROUP} python-path=/root/mysite python-home=/usr WSGIProcessGroup example.com WSGIScriptAlias / /root/mysite/mysite/wsgi.py <Directory /root/mysite/mysite> Require all granted </Directory> type example.com in the address bar, then get time out response: Gateway Timeout The gateway did not receive a timely response from the upstream server or application. How to handle this time-out in case of just a toy django app? I think it's not related to performance issues, but might be some configuration errors. Any one can help? Thanks! -
Django _unaccent and _search in Admin
So I have found a way to use _unaccent and _search together in Django filters, but I'm trying to find a way to properly implement it into the search bar in the admin pages. So far I have the following code, but since I haven't done it properly, admin settings such as search_fields = [] are not applying properly. I would appreciate it if someone could help me merge my solution with the original Django implementation. admin.ModelAdmin function being overwritten: def get_search_results(self, request, queryset, search_term): """ Returns a tuple containing a queryset to implement the search, and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name use_distinct = False search_fields = self.get_search_fields(request) if search_fields and search_term: orm_lookups = [construct_search(str(search_field)) for search_field in search_fields] for bit in search_term.split(): or_queries = [models.Q(**{orm_lookup: bit}) for orm_lookup in orm_lookups] queryset = queryset.filter(reduce(operator.or_, or_queries)) if not use_distinct: for search_spec in orm_lookups: if lookup_needs_distinct(self.opts, search_spec): use_distinct = True break return queryset, use_distinct My code: def get_search_results(self, request, queryset, search_term): # TODO: Make this more professionally implemented … -
How do i make my code for form more dynamic
I love the principle of Django, DRY. I am trying to get into the habit of coding following that convention. In my app, the form I am using has the same concept for now which is checking if its a POST method or not and if it is check if its a valid form or not and save it(along with association) but i could not make it more dynamic as it can be used only for the specific app. The main issue in dynamic is the line where i have used the association, there resume is used which i want dynamic and also improve this code for more better and efficient code. Here it is def addForm(request, form, template): if request.method == "POST": if form.is_valid(): resume_instance = Resume.objects.get(applicant=request.user) new_form = form.save(commit=False) new_form.resume=resume_instance new_form.save() messages.success(request, 'Thank you') messages.warning(request, 'Correct the error') context = { 'form': form } return render(request, template, context) def edit_form(request, form, template): if request.method == "POST": if form.is_valid(): form.save() messages.success(request, 'successfully updated') messages.warning(request, 'Correct the error') context={ 'form': form } return render(request, template, context) def resume_form(request): template='userDashboard/user/resume.html' user = request.user try: resume = Resume.objects.get(applicant=request.user) return edit_form(request, ResumeForm(request.POST or None, instance=resume), template) except Resume.DoesNotExist: print ('error') return addForm(request, ResumeForm(request.POST … -
TemplateDoesNotExist at /accounts/upload_save/ error
I got an error,TemplateDoesNotExist at /accounts/upload_save/ {'form': } . I wrote in views.py like def upload(request, p_id): form = UserImageForm(request.POST or None) d = { 'p_id': p_id, 'form':form, } return render(request, 'registration/accounts/photo.html', d) @csrf_exempt def upload_save(request): if request.method == "POST": form = UploadForm(request.POST, request.FILES) if form.is_valid(): data = Post() data.image = request.FILES['image'] data.save() else: form = UploadForm() return render('registration/accounts/photo.html', {'form':form}) class UploadForm(forms.Form): image = forms.FileField() urls.py is urlpatterns = [ url(r'^regist/$', views.regist,name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), url(r'^profile/$', views.profile, name='profile'), url(r'^photo/$', views.photo, name='photo'), url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'), url(r'^upload_save/$', views.upload_save, name='upload_save'), ] profile.html is <div class="container"> <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> SELECT FILE <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> </div> When I put "SEND" button,I wanna show photo.html in the browser.But now the error happens, although I wrote registration/accounts/photo.html in render.I really cannot understand how to fix this.What should I do? -
Django Signals and form is_valid
This question is related to this. I would like to save my form data in relation to the created signal: Model : class PatientInfo(models.Model): lastname = models.CharField('Last Name', max_length=200) ... class MedicalHistory(models.Model): patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True) physician_name = models.CharField('Physician', max_length=200, null=True, blank=True) ... @receiver(post_save, sender=PatientInfo) def create_medical_history(sender, **kwargs): if kwargs.get('created', False): MedicalHistory.objects.create(patient=kwargs.get('instance')) View class MedicalCreateView(CreateView): template_name = 'patient/medical_create.html' model = MedicalHistory form_class = MedicalForm success_url = '/' def post(self, request, pk): form = self.form_class(request.POST) if form.is_valid(): patiente = form.save(commit=False) physician_name = form.cleaned_data['physician_name'] # do not delete patiente.save() messages.success(request, "%s is added to patient list" % physician_name ) return redirect('index') else: print(form.errors) My code above saves two entry in my MedicalHistory table, patient field is linked to Patient_info.id while the other is empty yet populated with form data. Any help is greatly appreciated. -
Django Model Formset does not validate yet no errors
Super noob who codes for my own small business. Can't seem to figure this one out. Model formset does not validate but manager form shows no errors screenshot of no errors on form def audit(request, location_id): clear = InvAudit.objects.filter(current_amount__isnull=True).delete() ingredients = Ingredient.objects.filter( location=location_id, ) audit_location = StorageLocation.objects.get(pk=location_id) InvAudit.objects.bulk_create([InvAudit(ingredient=x) for x in ingredients]) tasks = InvAudit.objects.filter(current_amount__isnull=True) CreateFormSet = modelformset_factory(InvAudit, fields=('ingredient', 'current_amount' ), max_num=tasks.count(), extra=0) InitFormSet = CreateFormSet(queryset=tasks) if request.method == 'POST': formset = CreateFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() current_stock = Ingredient.objects.filter(location=location_id,).annotate( system_level = Count(Case( When(item__in_stock=True, then=1,)))) mismatch = [] for f in current_stock: difference = current_stock.system_level - formset.filter(ingredient=f.id) if difference != 0: mismatch.append(f.id) return render(request, 'mismatch.html', {'mismatch': mismatch}) else: errors = formset.errors else: formset = InitFormSet return render(request, 'audit.html', {'formset': formset, 'audit_location': audit_location}) And here is my template. <form method="post" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {% bootstrap_form form %} {% endfor %} {% buttons %} <button type="submit" class="btn btn-primary"> {% bootstrap_icon "star" %} Submit </button> {% endbuttons %} </form> Any help much appreciated -
"Unable to setup mongodb with Django"
My Settings.py file has DATABASES = { 'default' : { 'ENGINE' : 'django_mongodb_engine', 'NAME' : 'my_database' } } When i try to run the django i get the following error I have attached the screenshot of the error i refered to this document https://django-mongodb-engine.readthedocs.io/en/latest/topics/setup.html MongoDb is up and running in the port 27017 Django Version:1.7 Python :3.4.3 please suggest the solution to setup the mongodb with django. -
Wrapper to help changing api
have a friend who wants to pull NHL data from an API in such a way he could treat it directly in Excel. In fact, he has got a tremendous experience with Excel and wants to make predictions with it. I would like to create a little web application so that he could make his request easily, directly from an interface. https://www.quora.com/Is-there-any-JSON-API-available-for-getting-NHL-information-rosters-lineups-statistics-etc 1- If I pull NHL data inside a .csv file, will he be able to process information in Excel from that file? 2- Assume I finished this web application, and the API used is no longer supported. I will need to change of API and refactor the entire code so that it will work with the new one. Is there a sort of wrapper I could use to avoid that kind of problem? A type of problem I could encounter is to have to reformat the 'pulling file' so that it could work with my application. -
How to sort objects without a static field value?
Let's say I had a bunch of objects, fathers. So each father would have a bunch of kids. An unbounded number of kids. For each 1 father, there are many kids. I want to sort each father by the average age of kids. Since the number of kids can change and their age will increase, I wouldn't necessarily want to hard-code the average age into the father model. I need to have that value dynamically available, cached somehow so it can be quickly sorted by average child age when looking at 100,000 fathers. Any ideas?