Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create sqlite db by provided .xlsx sample data file using django
I am newcomer to dJango and i am creating a tool which require some sample data to be uploaded which is in .xlsx file. I am worried if i need to creates model and then there is way to import .xlsx data or there is a way to create models by .xlsx file itself. Any help would be helpful. -
How do I rollback transaction in django-rest-framework APIView?
From above view. I try to force transaction to rollback. But no work. The data still inserted to database. Can someone give me the right way? class DocumentDetailView(APIView): def post(self, request): sid = transaction.savepoint() serializer = DocumentSerializer(Documents(), data=request.data) if serializer.is_valid(): serializer.save() transaction.savepoint_rollback(sid) return HttpResponse(JSONRenderer().render(serializer.data), status=201) else: return HttpResponse(JSONRenderer().render(serializer.errors), status=400) -
Send XML to activeMQ using Django
I am trying to send a XML file generated using 'ElementTree' to activeMQ server using python django 'requests' library .My views.py code is : from django.shortcuts import render import requests import xml.etree.cElementTree as ET # Create your views here. def index(request): return render(request,"indexer.html") def xml(request): root = ET.Element("root") doc = ET.SubElement(root, "doc") field1 = ET.SubElement(doc,"field1") ET.SubElement(doc, "field2", fame="yeah", name="asdfasd").text = "some vlaue2" ET.SubElement(field1,"fielder", name="ksd").text = "valer" tree = ET.ElementTree(root) headers = {} tree.write("filename.xml", encoding = "us-ascii", xml_declaration = 'utf-8', default_namespace = xml, method = "xml") url = 'http://localhost:8082/testurl/' headers = {'Content-Type': 'application/xml'} files = {'file': open('filename.xml', 'rb')} requests.post(url, files=files, headers = headers) return render(request,"indexer.html") and there is a simple submit button on indexer.html page. <html> <head> </head> <body> <form method="post" action="/xml/">{% csrf_token %} <input type="submit" value="submit"> </form> </body> </html> When I click submit button it's generating filename.xml file and then sending it successfully to activeMQ server, but at activeMQ i am getting XML message which contains header information also . So ,is it possible to send only body part without header or how to omit header at activeMQ side and keep only body/data part ? At activeMQ I'm getting following message: --6dc760762ba245eb8e4c3d72aa38062b Content-Disposition: form-data; name="file"; filename="filename.xml" <root><doc><field1><fielder name="ksd">valer</fielder></field1><field2 fame="yeah" name="asdfasd">some … -
pycharm can't find haystack but terminal can
Trying to install Haystack following django-haystack documentation the basic tutorial for installation and configuration but a problem faces me as I can't import haystack in Search-Indexes py file Haystack is installed the env and in the root Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'haystack', 'products', ] HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr' }, } Search_Indexes.py import datetime from haystack import indexes <<error can't find indexes yet in --> >>Terminal in my env (amirshop) amir@amir-In######:~/####/#####$ python manage.py shell Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from haystack import indexes >>> indexes. indexes.BasicSearchIndex( indexes.FacetDateField( indexes.NgramField( indexes.__package__ indexes.get_identifier( indexes.BooleanField( indexes.FacetDateTimeField( indexes.SearchField( indexes.__reduce__( indexes.get_model_ct( What is the problem or precisely where? -
'CsrfViewMiddleware' object is not iterable
I am new to Django, and I just took over from another developer on this project. All I have done so far is clone the code from git and install the dependencies. Immediately after setting up the project, and running python manager.py runserver and going to localhost:8000/admin I get an error stating the TypeError at /admin/login/, 'CsrfViewMiddleware' object is not iterable: Traceback: File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/template/response.py" in render 109. self.content = self.rendered_content File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/template/response.py" in rendered_content 86. content = template.render(context, self._request) File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/template/base.py" in render 206. with context.bind_template(self): File "/usr/lib/python3.5/contextlib.py" in __enter__ 59. return next(self.gen) File "/home/abhay/code/virtualenvironments/leaguesx/lib/python3.5/site-packages/django/template/context.py" in bind_template 236. updates.update(processor(self.request)) Exception Type: TypeError at /admin/login/ Exception Value: 'CsrfViewMiddleware' object is not iterable I would post code from the source code but I can't figure where in the source the cause of this might possibly be. The error gets thrown in Django's context.py file, from the bind_template function of the RequestContext class: class RequestContext(Context): """ This subclass of template.Context automatically populates itself … -
How to implement Facebook AccountKit based login system with custom django User Model
Facebook introduced AccountKit that helps you quickly register for apps using just your phone number or email address — no password needed. It's reliable, easy to use and gives you a choice about how you sign up for apps. I have read the docs but have no idea how to integrate the AccountKit user with custom django user model. And how session will be maintained. If someone explain the flow, It would be great help ? Thanks -
Insert values in related models based on foreign key
I'm trying to insert values for related one to many models through a form. I'm having some difficulties. I have three related models: class Member(models.Model): member_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50, default='test first name') last_name = models.CharField(max_length=50, default='test last name') class Loans (models.Model): loan_id = models.AutoField(primary_key = True) member = models.ForeignKey('Member',related_name='loans') class Transactions (models.Model): transaction_id = models.AutoField(primary_key=True) amount = models.DecimalField(max_digits = 10, decimal_places = 2) loans = models.ForeignKey('Loans', related_name='transactions') Basically, one Member can have one to many Loans, one Loan can have one to many Transactions (although it should be 0 to many, but I'm just testing at the moment). I have a form that asks for member's full name, loan id and amount. Basically I'm trying to find the Member based on the full name, then get the loan based on the id provided, and then create a new transaction for that loan. What I have done in my view: fullName = request.GET.get('full_name') loanID = request.GET.get('loan_id') amount = request.GET.get('amount') #to get first name firstName = fullName.partition(' ')[0] #to get last name lastName = fullName.rsplit(None, 1)[-1] #to get the member member = Member.objects.filter(first_name=firstName, last_name = lastName) #get member's loan based on loanID l = Loans(loan_id = loanID) t = Transactions.objects.create(amount … -
Does cokkie path matter for deleting cookie
I have a cookie: Name: trace Value: True Path: / Expires: until of browser session end I send a response from django server with a cookie I set this way: response.set_cookie('trace', max_age=0, path=/some/path/). I suppose this way will make browser to delete cookie. The question is: should it affect initial cookie with path=/? Or if the path is different, initial cookie should stay alive? -
Gunicorn logstash log handler
my log config file [loggers] keys=root, logstash [handlers] keys=console , logstash [formatters] keys=generic, access [logger_root] level=INFO handlers=console [logger_logstash] level=DEBUG handlers=logstash propagate=1 qualname=logstash [handler_console] class=StreamHandler formatter=generic args=(sys.stdout, ) [handler_logstash] class=logstash.TCPLogstashHandler formatter=generic args=('localhost',5959) [formatter_generic] format=%(asctime)s [%(process)d] [%(levelname)s] %(message)s datefmt=%Y-%m-%d %H:%M:%S class=logging.Formatter [formatter_access] format=%(message)s class=logging.Formatter my command to execute gunicorn --env DJANGO_SETTINGS_MODULE=myproject.settings myproject.wsgi --log-level debug --log-file=- --log-config gunicorn_log.conf I am not getting any error but logstash is not receiving access logs. This handler worked with DJango and celery but I am helpless with gunicorn -
Django floppyforms setting PointField from (lat,lon) and vice versa
Im trying to use floppyforms with some changes: models.py: class LocationPoint(models.Model): title = models.CharField(max_length=30, null=False, blank=False) radius = models.DecimalField(max_digits=5, decimal_places=2, null=False, blank=False) point = models.PointField(srid=4326, null=False, blank=False) objects = models.GeoManager() views.py: def location_point_new(request): if request.method == "POST": form = LocationPointForm(request.POST) if form.is_valid(): form.save() return redirect('ui:population-constraint-add') else: form = LocationPointForm() template = 'api/location_point_template.html' context = RequestContext(request, {'form': form}) return render_to_response(template, context) forms.py: class GMapPointWidget(floppyforms.gis.BaseGMapWidget, floppyforms.gis.PointWidget): google_maps_api_key = 'AIzaSyAkNJVjV_xKR3jkmut3knAhEPHxQg5VNaI' class LocationPointForm(forms.ModelForm): latitude = forms.DecimalField( min_value=-90, max_value=90, required=True, ) longitude = forms.DecimalField( min_value=-180, max_value=180, required=True, ) class Meta: model = LocationPoint exclude = [] widgets = {'point': GMapPointWidget(attrs={'map_width': 1000, 'map_height': 500})} def __init__(self, *args, **kwargs): super(LocationPointForm, self).__init__(*args, **kwargs) if args: # If args exist data = args[0] if data['latitude'] and data['longitude']: # If lat/lng exist latitude = float(data['latitude']) longitude = float(data['longitude']) data['point'] = Point(longitude, latitude) # Set PointField try: coordinates = kwargs['instance'].point.tuple # If PointField exists initial = kwargs.get('initial', {}) initial['latitude'] = coordinates[0] # Set Latitude from coordinates initial['longitude'] = coordinates[1] # Set Longitude from coordinates kwargs['initial'] = initial except (KeyError, AttributeError): pass I have three problems with this code: The default zoom is way too close... the widget settings point_zoomm in GMapPointWidget doesnt do anything. As you can see in the screenshot … -
Change plugin model and migrate data
During implementation of one of our projects, we have made the mistake of subclassing Link class instead of using the CMSPlugin parent and some form of abstract class mix-in. One solution may be to do a migration and change the model's fields (as described in https://github.com/divio/django-cms/issues/5237#issuecomment-217426949), however, it seems to me that simple(r) solution may be to just create new models and upgrade the plugins accordingly. My proposed workflow is: create new models for each of the existing models, copy over all of the fields to the new models What I am not sure is how to set up the Django CMS plugins - at which point should I change the plugin's model? And how to ensure that the newly created models are also linked properly to the previous plugins? -
Django REST Framework how to add context to a ViewSet
The ViewSets do everything that I want, but I am finding that if I want to pass extra context to a template (with TemplateHTMLRenderer) then I will have to get at the functions that give responses.. (like list(), create(), etc) The only way I can see to get into these is to completely redefine them in my ViewSet, but it seems that there should be an easy way to add a bit of context to the Template without having to redefine a whole set of methods... class LanguageViewSet(viewsets.ModelViewSet): """Viewset for Language objects, use the proper HTTP methods to modify them""" # TODO: add permissions for this view? queryset = Language.objects.all() serializer_class = LanguageSerializer filter_backends = (filters.DjangoFilterBackend, ) filter_fields = ('name', 'active') Right now my code is looking like this but I will be wanting to add different context to the responses and I am trying to avoid redefining an entire method for such a small change. like this... class LanguageViewSet(viewsets.ModelViewSet): """Viewset for Language objects, use the proper HTTP methods to modify them""" # TODO: add permissions for this view? queryset = Language.objects.all() serializer_class = LanguageSerializer filter_backends = (filters.DjangoFilterBackend, ) filter_fields = ('name', 'active') def list(self, **kwargs): """Redefinition of list""" ..blah … -
Creating a log of all pages visited by the user
I am creating this functionality with a Django application I have. I want to log all pages the user visits and display it to him. I am using a middleware to achieve it. class LoggingMiddleware: """ Class used to register and fetch pages where the user has been visiting. """ def process_template_response(self, request, response): if request.user.is_authenticated(): UserHistory.objects.create(user=request.user, page_name=request.path, url=request.path) if response.context_data: response.context_data['user_history'] = UserHistory.objects.filter(user=request.user) return response I want to name these UserHistory entries in the database, instead of just set the url as the name (as it i s now). I have though of adding a variable to all views I have, in a way that the request object has something like request.page_name. Can someone think of a better way to do it? -
Django display data in a table -- Sort of a table within a table (nested forloop?). Data needs to link as well
I'm not sure the best way to explain it so I created an example picture and made up some data: I looked at this post and know I need to use some forloop template stuff: Displaying a Table in Django from Database The parts that are throwing me off are how to have a table within a table. For example, the doctor 'Bob" has 3 different patients. Bob has one row but Bob's patient column has 3 rows within it. <table class="table table-striped table-bordered"> <thead> <th>Name</th> <th>Total Patient Meetings</th> <th>Patient</th> <th>Meetings for Patient</th> </thread> <tbody> {% for doctor in query_results %} <tr> <td> {{ doctor.name }} </td> <td> {{ doctor.total_meetings }}</td> //*Would I have a nested forloop in here?*// {% for patient in query_results2 %} <td> {{patient.name }} </td> <td> {{patient.meeting_number }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> I'm having trouble finding an example like this to work off of and am not sure how to approach it. I also need those patients to link to the individual patient pages. So if I click on Bob's patient 'C755' I will be directed to that patient's page. I was thinking something like: `<p><a href="patient/{{patient.name}}">{{patient.name}}:</a></p>` Thanks for any help. … -
Override STATICFILES_DIRS for one app
I have my global static files (CSS, ...) declared in STATICFILES_DIRS. Can I somehow override a single CSS file for an app of my project? I tried creating a static folder and putting the respective CSS inside /css of the app, but it won't work. -
How do I get Image from parent model to the child model related with foreign key
I have design a parent model which works fine. Parent model: class Person(models.Model): name = models.CharField(max_length=128) present_position=models.CharField(max_length=100) organization= models.CharField(max_length=150,blank=True) address = models.CharField(max_length=150, blank=True) email = models.EmailField(max_length=70, blank=True, null=True, unique=True) photo= ResizedImageField(size=[100, 100],crop=['middle', 'center'],upload_to='persons/%Y/%m/%d/',null=True, blank=True, editable=True, help_text="Person Picture") I have child model which produce executive committee members: class ExecMember(models.Model): name = models.ForeignKey(Person, on_delete=models.CASCADE ) committee_position = models.CharField(max_length=100) rank = models.IntegerField(blank=True) member_start_date = models.DateField(blank=True) member_end_date = models.DateField(null=True, blank=True) is_active = models.BooleanField(default=True) From child model I want to produce Executive Committee members list containing their related photo from Person model. So far I tried: In template: {% for execomember in object_list %} <tr> <td>{{forloop.counter}}.</td> <td>{{execomember.name}}<br> {{execomember.committee_position}}</td> <td><a href="{% url 'member:person-list' %}"> <img src="{{ person.photo_url|default_if_none:'#'}}" class="img-responsive"> </a></td> <td> {{execomember.member_start_date }}<br> {{execomember.member_end_date}} </td> <td> {{execomember.is_active}}<br> </td> </tr> {% endfor %} In views: class ExeCommListView(generic.ListView): model = ExecMember context_object_name = 'execomembers' In urls: url(r'^execomember/$', views.ExeCommListView.as_view(), name='execomember-list'), But this gives all the fields values of child model correctly. Only photo not shown. How do I get photo from parent model to ExecMember model? Thanks. -
Refresh page with custom headers
I have a tracing utility and here is how it works: - User press "Trace" button on the web page - Javascript sets custom cookie for tracing (like 'trace=true') - Javascript reloads current page - Server django request middlewre gets this cookie and sets headers to the request object - After that tracing engine finds that headers and wraps inner function calls with tracing functions - Response django middleware sets cookie ('trace', max_age=0) so it will be "deleted" by browser and renders some trace token to the html element attr - Angular finds this token, handles it and uses this token for all ajax requests Since I have problem with cookies (looks like Chrome ignores "deleting" of that ciikie until page will not fully rendered so I cannot maniulate cookies between ajax requests) I thinking about rewrting it to the some custom headers. So the question(finally!) is: is there a way to make angular send custom headers on refreshing page? I'm not sure it is possible because looks like angular uses wrapped js object window and it has no headers param on window.location.reload() method. -
Django - POST get options from select
I have a html form that looks like this. {% url 'myapp:myapp_submit' as submit %} <form name='main' method="POST" action={{submit}}> {% csrf_token %} <select class='form-control' size=10 id="test" name='test' multiple> <option>Test</option> </select> <input type="submit"/> </form> and url.py from . import views app_name = 'myapp' urlpatterns = [ url(r'^$', views.myapp, name='myapp'), url(r'results/$', views.myapp_submit, name='myapp_submit') ] and views.py def myapp_submit(request): print request.POST The only thing I get back is <QueryDict: {u'csrfmiddlewaretoken'...]}> How do I get back the options held in the select tag? I would use the model/view form here but I'm doing some very crazy things with JS to constantly update the options available. -
Vanity URLs with cookies
I would like to create vanity URL just like facebook.com i.e. https://www.facebook.com/xyz. The problem i am facing are the cookies, basically i store the unique ID of user in cookies and fetch/save the profile data on the basis of that particular cookie. The users that don't have that cookie are not able to get/save data. In my case the cookies are clashing, user viewing the profile of other users profile can actually modify their data. I am stuck many issues are coming because my development approach is not right. Can any one suggest me the right method/approach to do that in express(node.js) or django(Python). -
Can't access the languages in django admin template
According to djangosnippets i create a change_language.html and also a copy of base.html and base_Site.html in my templates directory. Now i can see the select in my admin page, But the problem is that it dosent have any options , it means that LANGUAGES is empty. why is that ? how can i access the LANGUAGES sets setting.py in my template(change_language.html) ? Here is some parts of my code : seeting.py: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) ugettext = lambda s: s LANGUAGE_CODE = 'fa' LANGUAGES = ( ('fa', ugettext('Farsi')), ('en', ugettext('English')), ) -
Django collectstatic is copying files to another directory on apache
My Django project path is /home/project_name/app_name/app_name When running python manage.py collectstatic on server static files are copied to /home/project_name/app_name directory but I want it to copy files to /srv/www/vhosts/project_name . here is my configuration <VirtualHost *:80> DocumentRoot /srv/www/vhosts/project_name/ Alias /static/ /srv/www/vhosts/project_name/static/ Options Indexes FollowSymLinks MultiViews ExecCGI AddHandler cgi-script .cgi AddHandler wsgi-script .wsgi AllowOverride None Require all granted </Directory> <Directory /home/project_name/app_name/> Require all granted </Directory> If Anybody can help please. Thank you -
Creating a shortcut - Atom
I need to use shortcut witch creates '{% %}' in html file. I use emmet but it doesn't support this kind of syntax. Do you know any other packeges witch allows to do this or how to create shortcut like this. -
Issue while working on Interdependent drop-down in django application
I am having a problem while fetching data from the database using interdependent drop down option. as the code segment shows. if i select brand_id/brand_name from first drop-down option's list, it should show me all the sub-models related to selected brand_id/brand_name and same goes to get sub-models list by selecting model from model drop-down options. so basically i have three related drop down in my template. <label>Select Brand</label> <select class="form-control" name="brand_id" id="brand_id"> <option value=""> Select a Brand </option> {% for brand in brands %} <option value="{{ brand.brand_id }}">{{ brand.brand_name }}</option> {% endfor %} </select> <label>Select Model</label> <select class="form-control" name="model_id" id="model_id"> <option value="">Select Brand First</option> </select> <label>Select Submodel </label> <select class="form-control" name="submodel_id" id="submodel_id"> <option value="">Select Model First</option> </select> Here is my ajax code to get data dynamically. {% block ajax %} <script> $("#brand_id").change(function(){ get_model(); }); $("#model_id").change(function(){ get_submodel(); }); function get_model(){ jQuery.ajax({ async: false, type: "POST", url: "/get_model/", data: "brand_id=" + $('#brand_id').val(), success: function(response) { result = JSON.parse(response); if (result) { $('#model_id').empty() for(var i=0;i < result.models.length;i++){ $('#model_id').append($('<option>', { value: result.models[i]['model_id'], text: result.models[i]['model_name'] })); } } else { console.log('error'); } } }); } function get_submodel(){ jQuery.ajax({ async: false, type: "POST", url: "/ims/get_submodel/", data: "model_id=" + $('#model_id').val(), success: function(response) { result = JSON.parse(response); if … -
Django. Caching a list of data
Good day. I parsing an XML file to user class and stores items in the list. Also Im trying to cache it by Django's memcache like this: cache.add('goodsList', myList) but when i read from cache it returns me first item only. myList=cache.get('goodList') What am I doing wrong? -
Error with two same views in different apps in django project
Working on django project. There are two apps in my project one is custom defined "admin", and another is "home". I am using some views same in both app for eg:- My admin app urls.py file is from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^logout$', views.logout, name='logout'), url(r'^dashboard$', views.dashboard, name='dashboard'), url(r'^profile$', views.profile, name='profile'), url(r'^edit-profile$', views.edit_profile, name='edit-profile'), url(r'^check-password$', views.check_password, name='check-password'), url(r'^testing$', views.testing_database, name='testing'), ] and my home's app urls.py file is:- from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^sport$', views.sport, name='sport'), url(r'^register$', views.signup_signin, name='register'), url(r'^logout$', views.logout_view, name='logout'), url(r'^dashboard$', views.dashboard, name='dashboard'), url(r'^create-new-event$', views.create_new_event, name='create-new-event') ] So you can check that some views are same in both of views.py file, That why whenever I am trying to login into the admin panel it's redirectingme to the home app's dashboard, and when I try to logout from admin panel it's redirecting me on home's app index page. I think that this is the problem of same views in both apps. I also tried to import views of particular app in respective urls.py file. for example:- from home import views in home's urls.py file and for admin from admin import views …