Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Installed Virtualenv and activating virtualenv doesn't work
I cloned my Django Project from Github Account and activated the virtualenv using famous command "source nameofenv/bin/activate " And when I run python manage.py runserver It gives me an error saying : ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Django ImportError manage.py while deployment
I'm trying to deploy django app developed locally following the this guide, having server on debian not fedora. After installing requirements.txt and setting up database when i try to execute second sanity check (or anything connected with manage.py) the following error occurs: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/opt/anpene/anp/local/lib/python2.7/site-packages/debug_toolbar/apps.py", line 15, in ready dt_settings.patch_all() File "/opt/anpene/anp/local/lib/python2.7/site-packages/debug_toolbar/settings.py", line 243, in patch_all patch_root_urlconf() File "/opt/anpene/anp/local/lib/python2.7/site-packages/debug_toolbar/settings.py", line 231, in patch_root_urlconf reverse('djdt:render_panel') File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 568, in reverse app_list = resolver.app_dict[ns] File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 360, in app_dict self._populate() File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 293, in _populate for pattern in reversed(self.url_patterns): File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/opt/anpene/anpene/config/urls.py", line 26, in <module> url(r'^contact/', include('contact_form.urls')), File "/opt/anpene/anp/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module … -
'dict' object has no attribute 'push'
My views.py: def my_view(request): if request.method == 'POST': #code else: form = #my_form context_dict = {} context_dict['myfield'] = 3 return render(request, 'core/my_template.html', context_dict, {'form': form}) #return render(request, 'core/my_template.html', {'form': form}, context_dict) #return render_to_response('core/my_template.html', context_dict, {'form': form}) #return render_to_response('core/my_template.html', {'form': form}, context_dict) It gives an AttributeError: 'dict' object has no attribute 'push' I found this question but neither solutions work for me. This line below doesn't gives error but looks like don't pass anything( {{ myfield }} doesn't print anything) return render(request, ('core/add_regent.html', context_dict), {'form': form}) I'm using django 1.9 Thank you for your help. -
UPLOAD file to django
I try upload file to django from html throw ajax CLIENT SIDE: <input type="file" class="text-field" name="media"> <input type="button" class="btn" value="SEND"> var files; $('.text-field').change(function(){ files = this.files; console.log(files); }); $('.btn').click(function(){ var data = new FormData(); $.each(files, function(key, value){ data.append(key, value); console.log(key + ' : ' + value); console.log(value); }); $.ajax({ type: 'POST', url: 'url', enctype: 'multipart/form-data', data: data, cache: false, dataType: 'json', processData: false, contentType: false, success: function(data){ console.log(data); } }); BACK side: @csrf_exempt def my_file(request): print request.POST print request.FILES result: MultiValueDict: {u'0': [TemporaryUploadedFile: about.php (application/octet-stream)]} Please help how to upload file -
TypeError: relative imports require the package argument in python
I just started learning Python(2.7) and facing an issue. I am using windows 10. I have created a virtual environment(c:\virtualenvs\testenv) and activated it. My app folder path is c:\pyprojects\pytest. This folder has got requirements.txt with all the packages listed. The prompt looks like (testenv) c:\pyprojects\pytest\pip install -r requirements.txt It installs all the required packages successfully under testenv. Then I ran the following command (testenv) c:\pyprojects\pytest\python manage.py runserver and got the following error-- Unhandled exception in thread started by <function wrapper at 0x03ABF8F0> Traceback (most recent call last): File "C:\virtualenvs\testenv\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\virtualenvs\testenv\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\virtualenvs\testenv\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\virtualenvs\testenv\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\virtualenvs\testenv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\virtualenvs\testenv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\virtualenvs\testenv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\python27\Lib\importlib\__init__.py", line 30, in import_module raise TypeError("relative imports require the 'package' argument") TypeError: relative imports require the 'package' argument Now I checked the file -- C:\Python27\Lib\importlib__init__.py and it says if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") level = 0 for character in name: if character != '.': break level += 1 name … -
Optimization of big queryset/context in django
I have to present a very complex page with a lot of data coming from 3 different tables related with ForeignKey and ManyToManyField... I was able to do what I want but performance is terrible and I'm stuck trying to find a better approach... here are detailed code: Models: class CATSegmentCollection(models.Model): theFile = models.ForeignKey('app_file.File', related_name='original_file') segmentsMT = models.ManyToManyField('app_mt.MachineTransTable', related_name='segMT', blank=True,) segmentsTM = models.ManyToManyField('app_tm.TMTable', related_name='segTM', blank=True, through='app_cat.TM_Source_quality',) ... class TM_Source_quality(models.Model): catSeg = models.ForeignKey('app_cat.CATSegmentCollection') tmSeg = models.ForeignKey('app_tm.TMTable') quality = models.IntegerField() class MachineTransTable(models.Model): mt = models.ForeignKey('app_mt.MT_available', blank=True, null=True, ) ... class TMTable(models.Model): ... From these models (I just wrote what is relevant to my problem) I present all the CATSegmentCollection entries related to a single file... together with its associated TM and MT segments. In other words each entry in CATSegmentCollection has zero or more TM segment from the TMTable table and zero or more MT segment from the MachineTransTable table. This is what I do in the ListView (and I use AjaxListView because I'm using a infinite scrolling pagination from django-el-pagination): class CatListView(LoginRequiredMixin, AjaxListView): Model = CATSegmentCollection template_name = 'app_cat/cat.html' page_template='app_cat/cat_page.html' def get_object(self, queryset=None): obj = File.objects.get(id=self.kwargs['file_id']) return obj def get_queryset(self): theFile = self.get_object() return CATSegmentCollection.objects.filter(theFile=theFile).prefetch_related('segmentsMT').prefetch_related('segmentsTM').order_by('segment_order') def get_context_data(self, **kwargs): context = super(CatListView, … -
Chrome not connecting to network
I was wondering how I could let Chrome connect to my network. I am using a website called Codeanywhere.com and I was using a Django container. I used the built-in terminal and installed Python 3.4 and Django 10. I created a project and ran the server, and it said it had created one at this ip: http://127.0.0.1:8000/. However, whenever I try to access it, it the site can't be reached. If it helps, I am using a Chromebook Thinkpad, and it is a school computer. They do block things with Lightspeed Systems and they have a lot of blacklisting things going on. I am trying to learn Django for a project. Below is a screenshot of the screen when I try to access the server. My screenshot of the error screen. I can't embed my image yet, I don't have 10 reputation points :/ It's a link instead. -
Django root project namespace not working
I decided to have the front pages such as the main landing page and the 'about me' page etc. at the root of my project instead as a different app. This means the project looks like this: /django-helloworld /Hello_World __init__.py url.py views.py wsgi.py /static style.css /templates index.html My urls.py looks like this: from django.conf.urls import url, include from django.contrib import admin from . import views app_name = 'Hello_World' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^admin/', admin.site.urls), The problem is, when I try to point to a url in my template, it works by doing: <a href="{% url 'index' %}">Home</a> But if I try referencing the namespace like so: <a href="{% url 'Hello_World:index' %}">Home</a> I get this error: NoReverseMatch at / 'Hello_World' is not a registered namespace What am I doing wrong? Thanks in advance. -
Django Spirit Installation
so i am pretty new to Django and i am trying to implement a forum on my website using Spirit, but i can't seem to install it. I follwed the steps on github: $ git clone https://github.com/nitely/Spirit.git $ cd Spirit $ virtualenv venv $ source ./venv/bin/activate $ pip install . $ cd example $ python manage.py spiritinstall $ python manage.py runserver but i keep getting errors like ImportError: No module named spirit.settings The documentation is pretty bad too for this package too so if anybody used it and can provide me with some instructions I would be very grateful . -
Change value in a django modelform formset
fellow devs, I'll get straight to the point. I'm trying to create a mechanism that saves an object into table Collections, and several objects Attribute_Values into another table with a common foreign key pointing to an object in Collections. MODELS: class Collections(models.Model): name = models.CharField(max_length=64) description = models.CharField(max_length=255, blank=True, default='') class Additional_Attributes(models.Model): name = models.CharField(max_length=64) collection = models.ForeignKey(Collections) FORMS: class Collection_New_Form(forms.ModelForm): class Meta(): model = Collections fields = ["name", "description"] class Collection_New_Attributes_Form(forms.ModelForm): class Meta(): model = Additional_Attributes fields = ["name", "collection"] widgets = {"collection": forms.HiddenInput} def __init__(self, *args, **kwargs): super(Collection_New_Attributes_Form, self).__init__(*args, **kwargs) print self.fields["collection"].initial def clean_collection(self): data = self.cleaned_data print "cleaned data:", self.cleaned_data, "| instance:", self.instance, "| initial:", self.initial return self.cleaned_data["collection"] The 'clean_collection' method was my shot at changing the data at clean stage, but it appears, the validation never gets to clean_collection method, because the default 'clean' method stops at the moment it doesn't find the collection value. VIEW: class Collection_New(View): view_template = "collection_new.html" buttons = [Buttons.COLLECTION_SELECT, Buttons.LIST_MENU] def get(self, request, *args, **kwargs): name_form = Collection_New_Form() raw_formset = formset_factory(Collection_New_Attributes_Form, can_delete=True) formset = raw_formset() return render(request, self.view_template, {"name_form": name_form, "formset": formset, }) def post(self, request, *args, **kwargs): name_form = Collection_New_Form(request.POST) if name_form.is_valid(): collection = name_form.save() raw_formset = formset_factory(Collection_New_Attributes_Form, can_delete=True, extra=0) … -
Retrieve inserted object after save : Django Rest Framework
I'm having a NewsFeed Model and it's serializer. Now when Admin enters all the values from django administrator i want send push, so i'm using following method in models.py, signals.post_save.connect(news_feed_post_save, sender=NewsFeed) now with this when push send, i have to add the full added object, Here is my news_feed_post_save method def news_feed_post_save(sender,instance,created, **kwargs): if created : data = { "pushType" : PushType.NEWS_FEED, } # print("--------------->pk", serializers.serialize('json', [ NewsFeed.objects.get(pk=instance.newsId), ])) # print("--------------->pk", instance.newsTitle) push.sendPush(content= serializers.serialize('json', [ NewsFeed.objects.get(pk=instance.newsId), ]),data=data) I have tried above way to get the full response. It's working but only returning model fields on the fields declared in serializer, It's not returning all the fields declared in serializers.py. What should i have to change to retrieve full all the fields value. -
Django & Bootstrap sample project
Dears, I'm new in web development, I almost know Django and Bootstrap, I wonder if there was a sample project written with these two framework in Github or anywhere it could be more helpful to review and learning. I couldn't find sample, can anyone introduce me one? -
Django Custom Admin Form bulk save implmentation
I am trying to implement a CSV Import in Django Admin and save bulk data corresponding to the CSV file's rows. This is my Admin class: class EmployeeAdmin(admin.ModelAdmin): list_display = ('user', 'company', 'department', 'designation', 'is_hod', 'is_director') search_fields = ['user__email', 'user__first_name', 'user__last_name'] form = EmployeeForm This is my Form class: class EmployeeForm(forms.ModelForm): company = forms.ModelChoiceField(queryset=Companies.objects.all()) file_to_import = forms.FileField() class Meta: model = Employee fields = ("company", "file_to_import") def save(self, commit=True, *args, **kwargs): try: company = self.cleaned_data['company'] records = csv.reader(self.cleaned_data['file_to_import']) for line in records: # Get CSV Data. # Create new employee. employee = CreateEmployee(...) except Exception as e: raise forms.ValidationError('Something went wrong.') My Employee class is: class Employee(models.Model): user = models.OneToOneField(User, primary_key=True) company = models.ForeignKey(Companies) department = models.ForeignKey(Departments) mobile = models.CharField(max_length=16, default="0", blank=True) gender = models.CharField(max_length=1, default="m", choices=GENDERS) image = models.ImageField(upload_to=getImageUploadPath, null=True, blank=True) designation = models.CharField(max_length=64) is_hod = models.BooleanField(default=False) is_director = models.BooleanField(default=False) When I upload my file and click save, it shows me this error: 'NoneType' object has no attribute 'save' with exception location at: /usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py in save_model, line 1045 EDIT I understand I need to put a call to super.save, but I am unable to figure out where to put the call, because the doc says that the save method … -
Safe way to know if user is logged in client side with Django
My website project shows user specific data in almost every page (e.g. show username in topbar if logged which is existent in all pages), show liked items, etc... I use AJAX to get html fragments depending if the user is authenticated or not (e.g. show username in topbar if authenticated, otherwise signup/login buttons). My question is, the above method causes me to invoke AJAX GET request in almost all pages and subsequently at least doubles the HTTP requests & the server load, is it safe to add some cookie logged_in: true and check it so I invoke the AJAX GET request ONLY IF the user is logged in. The convention in Django and modern webdev is to add only the session id in the cookies and everything is in the server side, is there a safe way to know if the user is logged in client side? -
Django vs Flask vs Web2py
I'm planning to learn a pythonic web framework to implement my web app. I'm in a dilemma as to which framework to choose. After searching the web, I have narrowed down the frameworks to 3 (i.e Django, Flask, Web2py). from what i understand, Django: Suited for a large project which gives you the ability to control almost everything explicity. Flask: Is a micro-framework suitable for small scale applications. Web2py: Simpler learning curve and easier to start with. The project i'm working on is a medium-scale app. -
Creating Rest Api in python using JSON?
I'm new to python REST API and so facing some particular problems. I want that when I enter the input as pathlabid(primary key), I want the corresponding data assigned with that key as output. When I run the following code i only get the data corresponding to the first row of table in database even when the id i enter belong to some other row. This is the VIEWS.PY class pathlabAPI(View): @csrf_exempt def dispatch(self, *args, **kwargs): # dont worry about the CSRF here return super(pathlabAPI, self).dispatch(*args, **kwargs) def post(self, request): post_data = json.loads(request.body) Pathlabid = post_data.get('Pathlabid') or '' lablist = [] labdict = {} lab = pathlab() labs = lab.apply_filter(Pathlabid = Pathlabid) if Pathlabid : for p in labs: labdict["Pathlabid"] = p.Pathlabid labdict["name"] = p.Name labdict["email_id"] = p.Emailid labdict["contact_no"] = p.BasicContact labdict["alternate_contact_no"] = p.AlternateContact labdict["bank_account_number"] = p.Accountnumber labdict["ifsccode"] = p.IFSCcode labdict["country"] = p.Country labdict["homepickup"] = p.Homepickup lablist.append(labdict) return HttpResponse(json.dumps(lablist)) else: for p in labs: labdict["bank_account_number"] = p.Accountnumber lablist.append(labdict) return HttpResponse(json.dumps(lablist)) -
Validation error not showing on form
I'm creating a SignUp form and it displays the validation errors, such as required fields. However, using Django-Crispy-Forms, the validation errors do not appear. I'm customizing the default form from Django-allauth, which raises ValidationError. However, using Django-Crispy forms, no errors get displayed on the form. 1.template {% extends "base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block content %} <div class="big-box"> <p><h1>{% trans "Sign Up" %}</h1></p> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <div class="row"> <div class="col-md-3"> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {% crispy form %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> </div> </div> {% endblock content %} 2.forms from django import forms from .models import Profile from django.utils.translation import pgettext, ugettext_lazy as _, ugettext from django.contrib.auth import get_user_model from crispy_forms.helper import FormHelper class SignupForm(forms.ModelForm): gender = forms.CharField(max_length=1, widget=forms.TextInput(attrs={'placeholder': _('Gender')})) #first_name = forms.CharField(max_length=50, label='',widget=forms.TextInput(attrs={'placeholder': 'First Name'})) first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('First Name')})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Last Name')})) birthday = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Birthday')})) location = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Location')})) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, … -
heroku django questions about database and procfile
I'm working on my first django app and deploying it to heroku and have some questions. I am using postgres as the database, and the local database schema got pushed to heroku but there was no app specific data in the remote database, only the parts that came with django. To get my own data to be populated on the remote heroku database, i had to do heroku pg:reset and then heroku pg:push. Is that the way I'll have to do it from now on, add data locally and then to get it reflected remotely, do the reset and then the pg:push? Isn't there a way to get the data included in each git push heroku master command? Also in the heroku docs it says that having a Procfile is not necessary for django apps, since it can work it out itself. Yet it didn't work at all until I created one myself and added a web process. What's with the contradiction? Thanks for your time. -
submiting form html django
I want to send data from my html submit for to my database(mysql). On server side i use django(im begginer). Can you give me example if i use 3 rows in my table "name" "email" "message". When someone press submit i want data to be stored in DB and other users cant see them. I have read djangogirls and django tutorial 1.10 and i already made an webapp. But im stuck if i want to do something on my own. my form in index.html <form method="POST" class="post-form" action="/myapp/">{% csrf_token %}{{form}} <input class="form-control" id="ime" name="ime" placeholder="Name" type="text" required> </div> <div class="col-sm-6 form-group"> <input class="form-control" id="mail" name="mail" placeholder="mail" type="email" required> </div> </div> <textarea class="form-control" id="comm" name="comm" placeholder="Comm" rows="5"></textarea><br> <div class="row"> <div class="col-sm-12 form-group"> {{ form.as_p }} <button class="btn btn-default pull-right" type="submit">Send</button> </form> -
TypeError: relative imports require the 'package' argument [on hold]
I am a beginner in Python/Django. I have installed Python 2.7 and virtualenv. I am getting TypeError:relative imports require the 'package' argument when I am doing python manage.py runserver from my app folder.Below is the screenshot. Any help is highly appreciated. Thanks in advance. -
What is the difference render() and redirect() in Django?
What's difference between def post(self, request, *args, **kwargs): if form.is_valid(): order = form.save(commit=False) order.user = request.user order.save() return redirect('orders:success') and def post(self, request, *args, **kwargs): if form.is_valid(): order = form.save(commit=False) order.user = request.user order.save() return render( request, 'orders/success.html', {} ) I think these are totally same. Any difference? -
use .get() in child_set in django
I have model house and model members class House(model.Model): id = ... class member(model.Model): house = model.ForiegnKey(House) special = model.IntegerField(default=1) .... If I want to access all members I simply use: house.members_set.all() but what if I want to select an specific one. I use house.members_set.get(special=5) but it is not working. what is the correct statement for this situation? I use django1.8.4 -
using redis-py to bulk populate a redis list
In a Django project, I'm using redis as a fast backend. I can LPUSH multiple values in a redis list like so: lpush(list_name,"1","2","3") However, I can't do it if I try values_list = ["1","2","3"] lpush(list_name,values_list) For the record, this doesn't return an error. Instead it creates a list list_name with a single value. E.g. ['["1","2","3"]']. This is not usable if later one does AnObject.objects.filter(id__in=values_list). Nor does it work if one does AnObject.objects.filter(id__in=values_list[0]) (error: invalid literal for int() with base 10: '['). What's the best way to LPUSH numerous values in bulk into a redis list (python example is preferred). -
Django: How do I get multiple values from checkboxes in dataTable
In HTML, every form field needs a name attribute in order to be submitted to the server. But I used dataTable to display all data and pagination. The list checkbox just get the data of the current page not get data of next page or previous page. How can I get all the values of checkbox? in the template <input type="checkbox" name="orderId" value="{{ order_id }}" checked> and in the view: order_list = request.POST.getlist('orderId') -
How Can I Add Extra Input Fields in Django Form in Template
I have a Django ModelForm with some fields I would want the user should be able to add as long as the options permit them. forms.py: class MyForm(ModelForm): class Meta: model = Schedule fields = ['event_name','weekday', 'start_time', 'end_time', 'repeat_pattern', 'venue'] Right now users can be able add schedule successfully. But I want if a user submits an event and names it AfriTech and Cultures she should be able to add Saturday, start_time [9:00am], end_time [11:00am] and repeat_pattern [Weekly] and then ADD for any other day for that same event before submitting the form. When a user clicks add more day she gets another input fields for weekday, start_time, end_time, repeat_pattern. How can I achieve this?