Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I display a Django model in a Django template?
Trying to figure out Django... I'd like to build a table in a template that is largely all the data from a Django model. My preference would be to send the model queryset PersonDynamic.objects.all() to the template and have it figure out the column names and then loop through each row, adding the fields for that row. This kind of approach would give me a lot of flexibility because if the model changes the template will automatically change with it. One approach could be to just move the column headers and each record into lists which I then send to the template but this seems less efficient than just sending the queryset. What is the best way to do this? Am I right about efficiency? Does sending lists rather than model instances come with a larger risk of problems if there are a bazillion records or does that risk exist, regardless of approach? Thanks! -
Django User Registration - not sure what is going wrong
Very, very new to Django. I'm attempting to create a user registration process with custom form inputs. However, I have a few issues with the general persisting of new users to the database. This is what I have defined in my forms.py: class UserRegistrationForm(UserCreationForm): required_css_class = 'required' email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def __init__(self, *args, **kwargs): super(UserRegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs={'placeholder': 'Username'}) self.fields['username'].required = True self.fields['username'].error_messages = {'required': 'Please enter your username'} self.fields['email'].widget = EmailInput(attrs={'placeholder': 'Email'}) self.fields['email'].required = True self.fields['email'].error_messages = {'required': 'Please enter your email'} self.fields['first_name'].widget = TextInput(attrs={'placeholder': 'Forename'}) self.fields['first_name'].required = True self.fields['first_name'].error_messages = {'required': 'Please enter your first_name'} self.fields['last_name'].widget = TextInput(attrs={'placeholder': 'Surname'}) self.fields['last_name'].required = True self.fields['last_name'].error_messages = {'required': 'Please enter your last_name'} self.fields['password1'].widget = PasswordInput(attrs={'placeholder': 'Password'}) self.fields['password1'].required = True self.fields['password1'].error_messages = {'required': 'Please enter your Password'} self.fields['password2'].widget = PasswordInput(attrs={'placeholder': 'Confirm password'}) self.fields['password2'].required = True self.fields['password2'].error_messages = {'required': 'Please confirm your Password'} I also have the following in my views.py file: class UserRegistrationView(FormView): disallowed_url = '' form_class = UserRegistrationForm success_url = '/blog' template_name = 'oauth/user/registration_form.html' def registration_allowed(self): return getattr(settings, 'REGISTRATION_OPEN', True) def register(self, request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): … -
Django vs Node.js backend for Search Engine (Elasticsearch)
My company is building a search engine for a client. Currently we have to build it from scratch so all the web scraping, insertion and querying will be implemented by us. We decided to use MongoDB as our database and sync it to elasticsearch with mongo-connector. However we cant decide which backend to choose Django or Node.JS. Is there any added pros for either of these backends? All our web scraping is done in python so will integration be a problem if we use Node? Also one of my coworkers suggested that software packaging will be better if we use Django. I couldn't quite understand why software packaging will be an issue if we use Node. Thanks for your time :) -
Django conditional annotation without filtering
I have a Student model and an Entry model. Each Entry has a foreign key to a Student, a year-stamp, and two numeric values (value1 and value2). I am overriding the get_queryset() method in the StudentAdmin class, and using the Django ORM, I want to annotate a field that we'll call "specialvalue". Students have at most one Entry for each year, but they might have none, and they might have an Entry for years in the future. The value of "specialvalue" will be equal to Entry__value1 minus Entry__value2 for the Entry for the current year. If the Student has no Entry for the current year, then specialvalue will just be equal to None, and these Students will NOT be removed from the queryset. How can I do this? At first I tried splitting the queryset into two: queryset_1 = queryset.filter(entry__year=THIS_YEAR).annotate(specialvalue=...) queryset_2 = queryset.exclude(entry__year=THIS_YEAR).annotate(specialvalue=Value(None)) and then annotating them separately and merging them with the | pipe operator, but unfortunately this results in the wrong results due to a known bug in Django's ORM. Thank you! -
Django Modal Not Loading
Someone asked this same exact question but it did it not help me out. I tried implementing the tips, but my modal was still not loading within my django site. (note: I am an intermediate programmer, but not great. Not super familiar with Javascript, but have been developing in django for 2 years.) I am trying to add an item to a grocery list. On the grocery list page, I want the user to be able to click "add item" and have the Add Item Form pop up in a modal. I've researched and have looked through many stack overflow resources and others, as well, and cannot find a solution. It's been about 4-5 weeks of research. Depending on the code combination I use, half the time a modal pops up with no form and half the time a grey grid overlays my screen without a modal or a form. In either case, my crispy form (and django form) will not render within the modal. I'm assuming my form is valid, because my form will render and work perfectly when directly within the html, without a modal. add_item_test.html <div class="modal hide" id="itemModal"> <form class="well" method="post" action="/send_add_item/"> <div class="modal-header"> <button type="button" … -
Validate other state form field in django
I keep getting form validation error when I try to validate a Django form such that, if 'other state'(State outside the united states) is selected, the user must type his state on another field (Other state field). If his state is a US state the other state field is not required. Below is my code; models.py class User(models.Model): First_Name = models.CharField(max_length=100) Last_Name = models.CharField(max_length=100) Date_of_Birth = models.DateField() State_of_Origin = models.CharField(max_length=50, choices=STATE_CHOICES) Other_State = models.CharField(max_length=50, null=True) Marita_status = models.CharField(max_length=50, choices=STATUS_CHOICES) Country = CountryField(default='NG') Email = models.EmailField(unique=True) Phone_Number = PhoneNumberField("Phone Number(+1..)", default='+1') Form.py class RegForm(forms.ModelForm): Date_of_Birth = forms.DateField(widget=AdminDateWidget()) #Other_State = forms.CharField(max_length=50, required=False) class Meta(): model = User fields = '__all__' def clean_State_of_Origin(self): State_of_Origin = self.cleaned_data['State_of_Origin'] return State_of_Origin def clean_Other_State(self): Other_State = self.cleaned_data['Other_State'] if Other_State != 'Other': self.Other_State = forms.CharField(max_length=50, required=False) else: raise forms.ValidationError("Name is invalid") -
Django shell mode in docker
I am learning how to develop Django application in docker with this official tutorial: https://docs.docker.com/compose/django/ I have successfully run through the tutorial, and docker-compose run web django-admin.py startproject composeexample . creates the image docker-compose up runs the application The question is: I often use python manage.py shell to run Django in shell mode, but I do not know how to achieve that with docker. -
bootstrap modals only working on some elements and not working on others.Elements are dynamically rendered
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> this is my html's head content. my template contains Dynamically rendered post element(thumbnail) which contains a Modal. <li><div class="thumbnail" id="{{post.0.pk}}"> <a href="#exampleModalLong{{post.0.pk}}" class="popup" data-toggle="modal">(Input form)</a> <!-- Modal --> <div class="modal fade" id="exampleModalLong{{post.0.pk}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> ........ javascript that renders these posts is: if ($(window).scrollTop() == ($(document).height() - $(window).height())) { ready=false; $.ajax( { url:'/home/scroll/loadcontent/', method:'get', data:{posts:str}, dataType:'json', success:function(response) { $("#col1").children('#tiles').append(response.col1); $("#col1").children('#tiles').append(response.col4); $("#col2").children('#tiles').append(response.col2); $("#col2").children('#tiles').append(response.col5); $("#col3").children('#tiles').append(response.col3); $("#col3").children('#tiles').append(response.col6); } }).always(function(){ ready = true; //Reset the flag here }); } } window.onscroll=yHandler; in this arrangement all the elements that are rendered in col1($("#col1").children('#tiles').append(response.col1);) are having there modals working while any of the others is not... -
Customising the user registration form: Django HTML mashup?
I've build a user registration form and what I hope is a correctly working back end registration mechanism (as far as I know this is not working as I need to define the password validation method in the form): forms.py class UserRegistrationForm(forms.ModelForm): password_setp = forms.CharField(label = 'Password', widget = forms.PasswordInput) password_conf = forms.CharField(label = 'Repeat Password', widget = forms.PasswordInput) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password_setp', 'password_conf',) def passwordconf_validation(self): cleaned_pw = self.cleaned_data if cleaned_pw['password_setp'] != cleaned_pw[password_conf]: raise forms.ValidationError("I\'m sorry, your chosen passwords do not match. Please try again.") return cleaned_data['password_conf'] def __init__(self, *args, **kwargs): super(UserRegistrationForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True views.py: class UserRegistrationView(CreateView): template_name = 'oauth/user/registration_form.html' model = User fields = { 'username', 'first_name', 'last_name', 'email', } def get_queryset(self): """ Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). """ if self.queryset is not None: queryset = self.queryset if hasattr(queryset, '_clone'): queryset = queryset._clone() elif self.model is not None: queryset = self.model._default_manager.all() else: raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'" % self.__class__.__name__) return queryset def user_registration(request): if request.method == 'POST': user_form = … -
Newbie - Django Project with Multiple Apps - Unable to render Views
I am in process of developing a Django Project that has 3 apps namely Customer, Investments and Stocks. Each Customer can have multiple Investments and Stocks but not the other way round. So far, everything works well on Admin side of the application. I am able to CRUD as an admin, but my goal is to have a 3 separate user levels - customer, advisor and admin (this is working fine!). A customer can only view his/her profile, investments and stocks pertaining to it. An advisor can view information of multiple customers and their portfolios. I think I can separate these by different Authentication levels/restrictions. These are my files, This is my customer model, from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Customer(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=200) cust_number = models.AutoField(max_length=5, primary_key=True) city = models.CharField(max_length=50) state = models.CharField(max_length=50) zipcode = models.CharField(max_length=10) email = models.CharField(max_length=200) home_phone = models.CharField(max_length=50) cell_phone = models.CharField(max_length=50) created_date = models.DateTimeField( default=timezone.now) updated_date = models.DateTimeField( blank=True, null=True) def created(self): self.created_date = timezone.now() self.save() def updated(self): self.updated_date = timezone.now() self.save() def __str__(self): return self.name This is my investment model, from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Investment(models.Model): … -
SelectDateWidget when DateField is not required
Django 1.11 I'd like to use SelectDateWidget. class FrameDate(models.Model): through_date = models.DateField(null=True, blank=True, verbose_name=_("through")) ... class FrameDateForm(ModelForm): def clean_through_date(self): pass # Breakpoint class Meta: model = FrameDate exclude = [] years = range(1800, datetime.datetime.now().year + 1) widgets = { 'frame': forms.HiddenInput(), 'from_date': forms.SelectDateWidget(years=years), 'through_date': forms.SelectDateWidget(years=years) } As we can see, this DateField is not required. And have an empty choice at the top of the list ("---"). The problem is that when a user inputs only a month we'll get ValueError springing out to the user in case of Debug=True. There is that method clean_through_date and the break point in it. But in case of incomplete set of month, day and year the program will not even call this clean_through_date() method. This method is called in two cases: 1) if the through_date is completely empty. 2) if it is completely filled. If it is partially filled, form validation is ignored completely. The program explodes at CreateView. Could you comment on it? And give me a kick here: how to warn the user that s/he must either fill month, day and year or don't touch the through_date at all. -
Djnago form not getting submitted facing attribute error
I am trying to store a field value from a webform to djnago database, my models.py and views.py are given belwo. I am facing AttributeError: 'WSGIRequest' object has no attribute 'get' * error I am new to django and python, please let me know my mistake here. VIEWS.PY MODEL.PY -
Django URLs arent working
Keep getting a 404 error whenever I try and access the site. This is my urls.py in my app called userprofile: urlpatterns = [ url(r'ˆ$', views.index, name = 'index') ] These are my urls.py: from userprofile import urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'ˆusers/', include('userprofile.urls')), ] and this is my views.py: def index(request): return HttpResponse("Hello, world. You're at the polls index.") I dont get any errors in the console. -
How to assign current year in with tag
In django I want to do something like this, which will pass current year to url name {% with now "Y" as year %} <a href="{% url 'createAwardWinner' year %}"><i class="fa fa-gavel fa-fw"></i> Create</a> {% endwith %} but its not able to interpret I want to do year = now 'Y' How should I do this -
Get Django version from source project
How are you friends. I have got one django source project and I would like to know what the version of this project is. How to get django framework version from source project? Cheers! -
not allowing users to enter same value for a field in object
I have this code ** models.py ** Class Collection(models.Model): user = ForeignKey(User) title = Charfield(max_length=250) order = IntegerField() I want to allow user to add collection objects. but they have to enter a different number for (order) for every object. for example: 1,2,3,4,5,6,7 with limit from 1-10. I know I can set a unique value for a filed. But, I want all users to be allowed to enter 1-10 for order field Any idea how to handle this? -
Django Rest Framework builtin docs error
When using the DRF default docs following the official documentation. It throws the following error when accessing /docs/ . This image shows the error message.Why did this happen ? -
Why python code accelerates?
I faced with interesting phenomena. I created Django project. I set up a current time at the beginning of application, and at the end. It was just reading data from text file and showing in web page. Initially in text file it was 10k line of information. On next try I showed file with 15k lines. Third time with 20k lines. I was wondering that the execution time(End_time-start_time) would increase, but for some reason it decreased. Here the link where you can download the project: https://www.dropbox.com/s/cc0oio2xgvaaa7f/mysite.zip?dl=0 Hope to hear from you soon -
Set defalut value for hidden ModelForm field Django
I want to pass an initial value for HiddenInput form field in Meta class of ModelForm object. If the field is not hidden, e.g. as: class Meta: model = SomeModel fields = ['some_id', 'some_amount',] and I pass initial values via kwargs to this form constructor, then initial values are set to these fields correctly. But when I try to hide one field (but I still need it to be set up to initial value from kwargs), e.g. as: class Meta: model = SomeModel widgets = {'ord_id': forms.HiddenInput(),} fields = ['some_id', 'some_amount',] Then 'ord_id' is not set up to initial value from kwargs and I get the following error when trying to submit such form: (Hidden field ord_id) Select a valid choice. That choice is not one of the available choice So is there any way to pass initial value to Hidden form field correctly? -
File storage for web application
I'm developing a (Django + Postgresql) web application(photo sharing) that I'm going to deploy in a http web server(apache), but I decided I'll store the files(mainly pics) elsewhere. Since I have little to no knowledge about hardware, should I expand the server and store them in it? Or should I make another server for storage(NAS,...)? -
Django - ajax call conditional method
i want to remove a record by ajax call, when if condition is true. but my ajax alway remove it. how to solve it? def delete_order(request, pk, user=None): try: if request.user == 'owner': order = Food.objects.get(food_name=order.order_name).price latestCredit = Credit.objects.filter(user = request.user).last().creditAmount nextCredit = float(latestCredit) + float(orderPrice) q = Credit(user = request.user, creditAmount = nextCredit, status='1') q.save() order.delete() return HttpResponse("removed") else: return HttpResponse("you cant removed") except Exception: return HttpResponse("error occured") ajax $('.delete').click(function(){ url_delete = 'my-url.com; $.ajax({ type: 'GET', url: url_delete, data:$(".delete_reserv").serialize(), success:function(data) { $row.remove(); } }); }); -
Django-mptt admin categories
In my Django project i have model: class Category(MPTTModel): name = models.CharField(default='', max_length=50, verbose_name='Название') slug = models.SlugField(default='') parent = TreeForeignKey('self', related_name='children', null=True, blank=True, verbose_name='Родительская категория' ) order = models.PositiveSmallIntegerField(blank=False, null=False, default=0, verbose_name='Порядок') is_active = models.BooleanField(default=True, db_index=True, verbose_name='Отображать на сайте') class Meta: verbose_name = 'Категория' verbose_name_plural = 'категории' class MPTTMeta: order_insertion_by = ['order'] If i add main categories first (one, two, three), and then add sub-categories (four - inside one, five - inside two, six - inside three) i would like to see it in admin panel like this: -one --four -two --five -three --six But i have this ordering: -one -two -three --four --five --six What i'm doing wrong? -
Django; An attempt was made to access a socket in a way forbidden by its access permissions
While trying to login in my Django Web App, i encounter OSError at /accounts/login/. The Error Code: OSError at /accounts/login/ [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 1.11.1 Exception Type: OSError Exception Value: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Exception Location: C:\Python35-32\lib\socket.py in create_connection, line 702 Python Executable: C:\Python35-32\myvenv_python3\Scripts\python.exe Python Version: 3.5.2 Python Path: ['C:\\Users\\Kaleab\\Desktop\\ecomstore', 'C:\\Python35-32\\lib\\site-packages\\sqlalchemy-1.1.7-py3.5-win32.egg', 'C:\\Python27', 'C:\\Python35-32\\myvenv_python3\\Lib\\site-packages', 'C:\\Python35-32', 'C:\\Users\\Kaleab\\Desktop\\ecomstore', 'C:\\Python35-32\\myvenv_python3\\Scripts\\python35.zip', 'C:\\Python35-32\\DLLs', 'C:\\Python35-32\\lib', 'C:\\Python35-32\\myvenv_python3\\Scripts', 'C:\\Python35-32\\lib\\site-packages', 'C:\\Python35-32\\lib\\site-packages\\win32', 'C:\\Python35-32\\lib\\site-packages\\win32\\lib', 'C:\\Python35-32\\lib\\site-packages\\Pythonwin'] I have tried Admin privileges, but didn't work. My searches on stackoverflow suggest the port may be used by an application, however it works for the 127.0.0.1:8000/admin. Can you please suggest any solution to the problem? I am using Django 1.11, Python 3.5 on my development server(localhost) on my Windows 8.1. VPN connection is disconnected. I am using Symantec Endpoint Antivirus, what do i need to check if access is blocked? -
index of cgi-bin page
I'm having a hard time putting a second website on my vps, the latest problem is that when I type the url a page with "index of cgi-bin" is displayed, I'm still new to this stuff and I don't know what it really means, I googled it and I found that the problem was probably caused by a misconfiguration(I'm using django), which was the case, but I solved it and waited for google more than 24 hours and still the same ugly page. Here is what I did: created 2 files /etc/apache2/sites-available/site1.com.conf and /etc/apache2/sites-available/site2.com.conf typed a2ensite for both and a2dissite for the default service apache2 restart the first site went well but not the second So after solving the django problem I decided to put the default apache2 page in the VirtualHost to be sure it's not a django problem anymore and here it's content: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For … -
Global Name Create is not Defined in django
from django.shortcuts import render, HttpResponse, redirect from django.contrib.auth.forms import UserCreationForm # Create your views here. def home(request): name="Rishabh" numbers=[1,2,3,4,5] args={'name':name, 'numbers':numbers} return render(request, "accounts/home.html",args) def register(request): if request.method=='POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form=UserCreationForm() args={'form':form} return render(request,'accounts/reg_form.html',args) while running this code I get an error called global name create is not defined. I cannot even create a user by admin too