Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
slice a query result string field in annotation using Substr and negative values
I am trying to slice the last two characters of a field and annotate it to query result, using the method given in this post. Something like: Person.objects.all()\ .annotate( code = Substr('Number', 1, -2), ) The above code returns an empty string as soon as I use negative values as the third argument. How can I achieve this? -
how to insert polish characters into database in django
I am trying to insert text containing polish characters: ( ąęó ) into my database. But, django doesn't allow to do this ,I see the error: (1366, "Incorrect string value: '\xC4\x99cej' for column 'comments' at row 1") I have already added # -- coding: utf-8 -- at the beginning of the view file. Was also trying to use decode('utf8')/encode('utf8') functions but it didn't work. I'll be very thankful for help, Thanks in advance -
How to update the specific field in django
I am a beginner in django. My doubt is there is some field which needs to be updated. Change from false to true. Since this is the requirement. So far I've written this. shortlisted_venues = Shortlist.objects.filter(event_planning__in=event_objects, object_type_id=19) shortlist_filter = shortlisted_venues[0] shortlist_filter.from_see_price = True shortlist_filter.save() shortlist_filter.refresh_from_db() so when I run same commands in django shell I see the change in value. But when running by url it doesn't. What am I missing over here, so that my object gets updated. -
Remove spaces from words and generate exact words
I am using python and I am looking a way where I can arrange the words in a meaning full seance and can improve the readability. Sample words are H o w d o sm a l l h o l d e r f a r m e r s f i t i n t o t h e b i g p i c t u r e o f w o r l d f o o d p r o d u c t i o n Output How do small holder farmers fit into the big picture of world food production This one way to remover one time white spaces, where the line has two spaces it will keep the one. Can anyone suggest more ways . I am using python django framework Thanks in advance. -
Django clean method based on condition (one form used in two views)
I have one form which is used in two views. One to save and one edit/update. There is a clean function I use to check unique condition. (form has three fields. A combination of three can come only once.) Now as I am using the same form, it checks this condition for both views - Save and Edit. This results in form throwing an error in edit view stating that the value already exists. How could I use this clean method in such a way that it will check for this validation for save view but will not check for edit view. Edit View: @login_required def permissionEditView(request, pk): data = models.PermissionModel.objects.get(pk=pk) p_form = forms.PermissionForm(instance=data) if request.method == 'POST': p_form = forms.PermissionForm(request.POST, instance=data) if p_form.is_valid(): p_form.save() messages.success(request, 'Permission updated successfully.') return redirect(companyProfileView) return render(request, 'company_profile.html', {'p_form': p_form}) Save view: def permissionFormView(request): p_form = forms.PermissionForm() if request.method == 'POST': p_form = forms.PermissionForm(request.POST) if p_form.is_valid(): p_form.save() messages.success(request, 'Permission added successfully.') return redirect(companyProfileView) return render(request, 'company_profile.html', {'p_form': p_form}) Form with clean method: class PermissionForm(forms.ModelForm): class Meta: model = models.PermissionModel fields = '__all__' def clean(self): role = self.cleaned_data.get('role_name') feature = self.cleaned_data.get('feature') if models.PermissionModel.objects.filter(role_name=role, feature=feature).exists(): raise forms.ValidationError('Permission exists.') def __init__(self, *args, **kwargs): super(PermissionForm, self).__init__(*args, **kwargs) for … -
Django settings.cpython-36.pyc not ignored by gitignore
The file "settings.cpython-36.pyc" is not being ignored even duo I have added it to the .gitignore file. My current gitignore file Gitkraken view, you can see it still picks it up This line "LearnDjango/pycache/" in the gitignore file ignores the other ".cpython-36.pyc" files but not "settings.cpython-36.pyc" View of pycache folder, the 1st and 3rd files are ignored but not the 2nd Please help. P.S I am new to Django and git. -
Database and Models present still programming error is coming in DJango
I am trying to get the models data on the browser using the urls.py and views.py for last 3 days and failing miserably, although I am able to get the database in a json file but not on browser. This is the error log [http://dpaste.com/2DQZX1Z][1] and the code is here models.py from __future__ import unicode_literals from django.db import models class Authors(models.Model): aid = models.AutoField(primary_key=True) aname = models.CharField(max_length=200, blank=True, null=True) adescription = models.CharField(max_length=8000, blank=True, null=True) class Books(models.Model): bid = models.IntegerField(primary_key=True) bname = models.CharField(max_length=200, blank=True, null=True) bdescription = models.CharField(max_length=8000, blank=True, null=True) class Bookauth(models.Model): bid = models.ForeignKey(Books, models.DO_NOTHING, db_column='bid', blank=True, null=True) aid = models.ForeignKey(Authors, models.DO_NOTHING, db_column='aid', blank=True, null=True) views.py from __future__ import unicode_literals from django.shortcuts import render import requests from django.http import HttpResponse from django.db import models from .models import Books import json from django.core import serializers def index(request): return HttpResponse("Hello, world. You're at the polls index.") def getObject(request): all_books = Books.objects.all() html = serializers.serialize('json', all_books) return HttpResponse(html) #data = serializers.serialize("json", Books.objects.all()) #return HttpResponse(data, mimetype='application/json') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^non', views.index, name = 'index'), url(r'^auth', views.author_search, name = 'AuthSearch'), url(r'^book', views.getObject, name = 'Books') ] -
How to make Django authenticate User and Employee?
I have following models: Company, Employee, Bid When a User registers he can create number of companies. Under these created companies, he can add number of employees. These employees must be able to authenticate and create bids under a company in which they are created. User also must be able to create bids under any company. For now, Django authenticates only my User. But I want to add functionality to authenticate Employee as well. How to implement it? I did google it, however, found mostly examples which refer to official documentation. Not really sure which way to go. -
Reverse to the same page with pk as slug field after submit. Error:Reverse with no arguments not found
following scenario: I do have a edit profile page which pulls the data from db so the user can change them. After submitting everything gets stored in the db but the reverse doesn't seem to work. Basically I don't know how to give the pk along to be able to call the same site with reverse. views.py class EditUserProfileView(UpdateView): model = UserProfileInfo form_class = UserProfileForm template_name = "accounts/user_profile.html" def get_object(self, *args, **kwargs): user = get_object_or_404(User, pk=self.kwargs['pk']) return user.userprofileinfo def get_success_url(self, *args, **kwargs): if 'pk' in self.kwargs: pk = self.kwargs['pk'] else: slug = 'main' return reverse("accounts:edit") urls.py app_name = 'accounts' urlpatterns=[ url(r'^edit/(?P<pk>\d+)/$', views.EditUserProfileView.as_view(), name="edit-user-profile"),] html from where I call the edit-user-profile <li class="nav-item nav-link">Hello <a href="{% url 'accounts:edit-user-profile' pk=user.pk %}">{{user.first_name}}</a></li> Cheers -
Run Python GUI application as a web app in Python
i have a desktop Python GUI application.Can any one please suggest how to make it run able as a web app? -
How to re-increment each id attribute in Formset after deleting a Form in Django?
I currently have a formset rendered to a template, where I do a for loop over it to display each form. I have a button which adds extra forms and I also have a delete button which removes any of the forms. My problem is when I delete one of the middle forms, the incrementing from the formset management (ie. id="form-0-choice") gets thrown off. If I add 3 new forms, I now have form 1, 2, 3. If I delete form 2 and then add another form, I now have form 1, 3, 4. Not all the forms will be saved correctly. How would I go about re-incrementing these id's? Is there a better way to manage creating/deleting in a formset manager on the template side? Or, would I need to just use JS to split apart the id's and re-number them based on the TOTAL_NUM_FORMS or however it is spelled. -
django prefetch_related's Prefetch, order_by?
I figured the following query: context['user_artists'] = Artist.objects.filter(users=current_user).all() Coupled with the following usage in templates: {% if user_artists %} ... {% for artist in user_artists %} .... <p class="small">last release: {{ artist.release_groups.last.title }}</p> <p class="small">date: {{ artist.release_groups.last.release_date }}</p> Was hitting the database 3 times for every artist in the query. I know this can be brought down to 2 by simple saving .last in the template, but that still isn't fast enough. I know I can use prefetch_related like so: Artist.objects.filter(users=current_user).prefetch_realted(`release_groups`).all() And I also need eliminate he usage of .last since it implies another query. I can probably use the template engine's slice method to get the last element. But then I have to order the related relationship: meaning, I need release_group ordered by its own release_date before I access them in the template. This must not affect the order of the artist objects. How can this be done? -
Django Form post method returning error
I'm making a single page chat app which will list all the message I post. The thing is in order to make the list and the form appear in single page, I have to define a single view(from what I understand. I'm pretty new to Django.) that point to a url. My django files are like this: chat/urls.py from django.urls import path from chat import views urlpatterns = [ path('chat/', views.ChatListView.as_view(), name='chat'), ] chat/forms.py from django import forms from chat.models import Chat class NewMessageForm(forms.ModelForm): message = forms.CharField(widget=forms.Textarea( attrs={'rows': 3, 'placeholder': 'Type here'}), max_length=1000) class Meta: model = Chat fields = ['message'] chat.html ...#some styling codes <form method="post" novalidate> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-success">Post</button> </form> chat/views.py from django.shortcuts import render from django.views.generic import ListView from chat.models import Chat from chat.forms import NewMessageForm class ChatListView(ListView): model = Chat template_name = 'chat.html' paginate_by = 20 ##I had a hard time rendering the form in html and this code solves the problem (from a stackoverflow answer) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = NewMessageForm() return context ##I'm not sure of this code. Am I doing it right? def new_message(request): if request.method == 'POST': form = NewMessageForm(request.POST) if form.is_valid(): … -
Update View not updating table when Rendering fields manually
When I am using simply this <form action="" method="post" enctype="multipart/form-data"> {% block content %} {% csrf_token %} {{ form }} <input type="submit" value="Update" /> {% endblock content %} </form> It is updating my JobFinal Table I can see POST /JobSchd/jobform_final/3/update/ HTTP/1.1" 302 0 But when changing {{ form }} to {{ form.job_name }} It doesn't update the table and doesn't redirect to the reverse url.And I can see POST /JobSchd/jobform_final/3/update/ HTTP/1.1" 200 4492 Here is my snippet of related View.py class JobFinalUpdate(UpdateView): model = JobFinal form_class = JobFormFinal template_name_suffix = '_update_form' def get_success_url(self): return reverse('JobSchd:user_details',kwargs={'pk': self.request.user.id}) Here is my form.py class JobFormFinal(forms.ModelForm): class Meta: model=JobFinal exclude=['user'] -
how to send null object (image) using axios to django
I have a django backend that will save / remove image when receiving request from API. I have succesfully delete the saved image if i using swagger / postman to call the API (sending the parameter null object). But i can't get it work via Axios. The CURL from Swagger : curl -X PUT --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IlNZU0FETUlOQFRSRUVTLkhBUlBBLkNPTSIsImV4cCI6MTUxNTAzNTU1MiwidXNlcl9uYW1lIjoiU1lTQURNSU5AVFJFRVMuSEFSUEEuQ09NIiwib3JpZ19pYXQiOjE1MTQ5NDkxMDR9.oz3_2fGKlOCesmU_RmSRJZOifZeFFQO1nwAWzyD6BYc' -d '{ \ "menu_type": 255, \ "icon": null, \ "login_id": 1 \ }' My axios sample code : formData.append('menu_type', 255) formData.append('login_id', 1) formData.append('icon', null) const config = { headers: { 'content-type': 'application/json' } } return new Promise(resolve => { axios.put(url + form.menu_uuid + "/", formData, config) .then(function (response) { resolve(response); }) .catch(function (error) { resolve(error.response); }); }); My request payload screenshot : Is there something that i missing that makes this axios request won't work ? -
Creating Django model instance on form submission
I have am trying to create a "stats" app in my project that keeps track of all the leads my site generates. When a user submit the "request info" form a message is automatically sent to the business associated with that product. Simultaneously I would like a model instance to be created in one of the models in the Stats app (different app then we are working in). The Stats works in the background simply collecting info view model instance for certain things. Here is the code breakdown: The view: def ListingView(request,name_initials,l_slug): listing = get_object_or_404(Listing,l_slug=l_slug) images = ListingImage.objects.filter(property=listing) form = ContactPropertyForm(request.POST or None) context = { 'listing':listing, 'images':images, 'form':form, } if form.is_valid(): name = form.cleaned_data.get('name') phone = form.cleaned_data.get('phone') email = form.cleaned_data.get('email') party_size = form.cleaned_data.get('party_size') form_message = form.cleaned_data.get('message') listing_address = listing.address message = name + " " + phone + " " + email + " " + party_size + " " + listing_address to_email = ['email here'] html_message = "<b>Name: </b>" + name + "<br>" + "<b>Phone: </b>" + phone + "<br>" + "<b>Email: </b>" + email + "<br>" + "<b>Group Size: </b>" + party_size + "<br>" + "<b>Property: </b>" + listing_address send_mail('New Lead', message, 'from email', ['To email'], fail_silently=False, … -
Django rest framework storing byte string for image
So what i am doing is to store byte string. And from my understanding, i am using byteio to convert the byte string i store and output it into image. Although i have not read about how ByteIO works so im going to research it later. Maybe im wrong but please give correct me if it is. But i have no idea on using what field for it. I tried using BinaryField for it but got error for its editable=False, setting it to true doesnt fix anything. So do i use CharField to store the byte string or ImageField/FileField works for it too ? -
Django: Submit multi-level form data
I have three models A, B, & C. B has a foreignkey to A while C has a foreignkey to B. I want to create A instance with multiple B and multiple C. E.g A -----B1 -----C11, C12, C13 -----B2 -----C22, C22, C23 -----B3 -----C31, C32, C33 but when I submit the form, I get something like this instead: A -----B1 -----C11, C12, C13 -----B2 -----B3 How do I fix it? models class A(models.Model): a_text = ... created_by = models.Foreignkey(User) class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b_text = ... created_by = models.Foreignkey(User) class C(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) c_text = .... forms class AForm(forms.ModelForm): class Meta: model = A fields = ['a_text',] class BForm(forms.ModelForm): class Meta: model = B fields = ['a', 'b_text',] class CForm(forms.ModelForm): class Meta: model = C fields = ['b', 'c_text',] B_FormSet = forms.inlineformset_factory(A, B, form=BForm, can_delete=False, extra=3) C_FormSet = forms.inlineformset_factory(B, C, form=CForm, can_delete=False, extra=3) views @login_required def create_A_object(request, *args, **kwargs): if request.method != 'POST': A_form = AForm(prefix='a') B_forms = B_FormSet(prefix='b') C_forms = C_FormSet(prefix='c') else: A_form = BaForm(request.POST, request.FILES, prefix='a') B_forms = CaFormSet(request.POST, request.FILES, prefix='b') C_forms = ChFormSet(request.POST, request.FILES, prefix='c') A_valid = A_form.is_valid() B_valid = B_forms.is_valid() C_valid = C_forms.is_valid() if A_valid and B_valid and C_valid: a = … -
WSGI Error deploying Pythong to Heroku
If i run heroku local web my application runs as expected. But when I git push heroku master and go to my herokuapp, I get a server error and my heroku logs give me this: 2018-01-03T02:39:35.291600+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-01-03T02:39:35.291602+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2018-01-03T02:39:35.291603+00:00 app[web.1]: return self.load_wsgiapp() 2018-01-03T02:39:35.291601+00:00 app[web.1]: self.callable = self.load() 2018-01-03T02:39:35.291603+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2018-01-03T02:39:35.291604+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 352, in import_app 2018-01-03T02:39:35.291605+00:00 app[web.1]: __import__(module) 2018-01-03T02:39:35.291611+00:00 app[web.1]: ModuleNotFoundError: No module named 'myNewApp' 2018-01-03T02:39:35.291604+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-01-03T02:39:35.291802+00:00 app[web.1]: [2018-01-03 02:39:35 +0000] [9] [INFO] Worker exiting (pid: 9) 2018-01-03T02:39:37.490787+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myNewApp.herokuapp.com request_id=68ae4976-dfd3-4201-9401-c7caf7189f66 fwd="24.5.227.25" dyno= connect= service= status=503 bytes= protocol=https help please? I'm not sure if I need to add any settings informaiton on here, but I can if needed... -
can not login with Extended AbstractBaseUser model
I'm using Django 2.0 I have extended the AbstractBaseUser to make some modification to the email and use email as username class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_superuser=False): if not email: raise ValueError('User must have an email address') if not password: raise ValueError('User must have a password') user = self.model( email=self.normalize_email(email) ) user.is_staff = is_staff user.is_superuser = is_superuser user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): return self.create_user( email, password=password, is_staff=True ) def create_superuser(self, email, password=None): return self.create_user( email, password=password, is_staff=True, is_superuser=True ) class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=250, blank=False, unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) groups = models.ManyToManyField(Group, blank=True) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' objects = UserManager() @property def staff(self): return self.is_staff @property def active(self): return self.is_active @property def superuser(self): return self.is_superuser def __str__(self): if self.first_name is not None: return self.get_full_name() return self.email def get_full_name(self): if self.last_name is not None: return self.first_name + ' ' + self.last_name return self.get_short_name() def get_short_name(self): return self.first_name I have then run python manage.py makemigrations python manage.py migrate and created superadmin using python manage.py createsuperuser The superuser is created successfully. But when I … -
Form is not shown in html correctly
Form is not shown in html correctly.I wrote in search.html, {% load static %} <form action='/search/' method='POST> <table> {{ form.as_table }} </table> <input name="submit" type="Search" /> {% csrf_token %} </form> in views.py def search(request): form = SearchForm() if request.method == 'GET': return render_to_response( 'search.html', {'form': form}, RequestContext(request)) elif request.method == 'POST': form = SearchForm(request.POST) search_result = POST.objects.all() if form.is_valid(): result = search_result.filter(Q(title__contains=form.cleaned_data['keyword'])) return render_to_response('search.html',{'form':form, 'result':result}) When I access search method,search.html is shown as strings like now search.html It is not From,so I really cannot understand why such a thing happens.No error happens but UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. "A {% csrf_token %} was used in a template, but the context " is shown in terminal.How should I fix this?What is wrong in my code? -
Sending confirmation email from inherited allauth class view
I am inheriting the allauth class view SignupView (from allauth.account.views import SignupView) I am using my own custom view and custom forms.py. Here's what I have: views.py class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' def form_valid(self, form): user = form.save(commit=False) # Do not save to table yet username = form.cleaned_data['username'] password = form.cleaned_data['password'] try: validate_password(password, user) except ValidationError as e: form.add_error('password', e) # to be displayed with the field's errors return render(self.request, self.template_name, {'form': form}) user.set_password(password) user.save() login(self.request, user) return redirect('profiles:Index', slug=username) forms.py class RegisterForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'})) password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'})) My view is successfully showing up and when I click sign up it signs me up and redirects me. However, in the default allauth sign up view, it sends you a confirmation email. With my custom view it doesn't for some reason. What do I have to do in order for my form to be able to send a confirmation email to the user? I am using: this as my reference -
Is it possible to add non model field to method body in Django?
Is it possible to add non model field for instance to PATCH body? Let's take as an example that I would like to change password of the user. In my model I have only field password however in PATCH I would like to add old_password to authenticate user and then update password from password field from body. Any ideas? I found SerializerMethodField but I am not sure whether it is possible to do what I have described above -
Django - Questions around how to validate current environment and how to run in production
my apologies, for what might be a rather simple and amateur set of questions. I recently was voluntold (more like told) to absorb a django/python project that was developed by someone else. That someone else has left, and now I have to pick this up and run with it as there is no other backup. Being a university student (intern at work for another 12 mos), I don't think this experience will go to waste AT ALL so I'm happy to be involved, but because this is production and in use today I need to ramp up rather quickly. // sordid_tale I am new to Python, Django, Anaconda, PostGreSQL and the world. I know some coding from my first two years, and I've been reading through books to get up to speed. Current scenario: Project deployed in production server (windows 2012) project has an open connection to postgresql and publishes a website used by multiple people across the firm to upload math analytics for reporting. i started the project up using the python manage.py runserver 123.123.22.22:8000 which started the DEVELOPMENT server and sent me a big ol' warning sign saying don't do this in production. so i took it down … -
django test urls status code
hello i create some test for my project mainly to enrich my knowledge. and I have some questions. simple test code : test.py from django.test import Client, TestCase class User_Form_Test(TestCase): def test_logged_user_get_dataset(self): response = self.client.get('/details/', follow=True) self.assertEqual(response.status_code, 200) def test_logged_user_get_disasters_projects(self): response = self.client.get('/details-images/', follow=True) self.assertEqual(response.status_code, 200) urls.py url(r'^details/(?P<id>\d+)/$', views.details, name='details'), url(r'^details-images/(?P<slug>[^\.]+)/$', views.details_images, name='details_images') all this code work fine I take passed messages in this two test. my question is how to can test like this example all possible regex from id in first case and second slug in second case automate ?