Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Firebase python, Accessing the User datas
I am using django rest for accessing the user details from Firebase. from firebase import firebase firebase = firebase.FirebaseApplication('https://your_storage.firebaseio.com', None) result = firebase.get('/users', None) print result But I didnt get the exact details. Always None. Which of the keys do I need to take to get details. Would be great to have a proper documentation link. -
Create forms from model, save to another
I'm building a survey-type app, where the questions are entered/stored in a model (by an admin). I want to use this model to auto-create a user facging form (the response will be stored in another model. class Question(models.Model): question_text = models.CharField(max_length=150) questionnaire = models.ForeignKey(Questionnaire) # 'lump' questions together class Response(models.Model): question = models.ForeignKey(Question) response_text = models.CharField(max_length=150) user = models.IntegerField() # used to record user ID I'm not sure what's the correct approach - using a ModelForm (populating through init) or a 'regular' form - where I'm not sure how I output my results - using print or adding to a form property. Thanks. -
Django drop down menu for naming file upload
I am trying to create a Django app that allows a user to select a file name from a drop down menu and upload the file. Regardless of what the user has named their file, I will receive that file saved as whatever they selected on the drop down plus the date. I cannot seem to get my drop downs to show. Reading the documentation, multiple stack overflow posts, and trial and error have not helped. Can anyone see where I am going wrong? models.py from django.db import models def update_filename(instance, filename): path = "documents/" format = str(vc) + '_' + '%Y%m%d' #+ str(instance.act) + '_' return os.path.join(path, format) class Document(models.Model): docfile = models.FileField(upload_to= update_filename) #/%Y/%m/%d') #value_chains = (('coffee', 'coffee'),('tea', 'tea'),) dropdown = models.CharField(max_length=20, choices=(('coffee', 'coffee'),('tea', 'tea'),)) forms.py from django import forms from .models import Document def validate_file_extension(value): if not value.name.endswith('.csv'): raise forms.ValidationError("Only CSV file is accepted") class DocumentForm(forms.ModelForm): docfile = forms.FileField(label='Select a file', validators=[validate_file_extension]) value_chains = (('coffee', 'coffee'),('tea', 'tea'),) dropdown = forms.ChoiceField(choices=value_chains, required=True) class Meta: model = Document fields = ['dropdown'] views.py from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.views.generic.edit import CreateView from .models import Document from .forms import … -
Using neomodel to generate JSON for graph visualisation in Javascript
I'm using neomodel in a django app to query Neo4j. Everything is fine but I can't figure out how to get a full path to be generated so that I can use d3 to visualise part of the graph in javascript - so ideally I need this in JSON. I can get a list of nodes from a CYPHER query in neomodel but how do I inflate nodes and relationships? I have found some examples of how to use the REST interface directly which suggests using "resultDataContents":["graph"] at the end of the request but there doesn't appear to be anything within neomodel to duplicate this functionality. Is there something I should add to the end of my cypher or something in neomodel I haven't found yet? -
Customize ListView queryset [duplicate]
This question already has an answer here: Django - how to get user logged in (get_queryset in ListView) 1 answer By this view I want show only the posts written by the account. class PostList(ListView): template_name = 'post_list.html' def get_queryset(self, *args, **kwargs): return Post.objects.filter(owner=self.kwargs['user']) I can do this by a custom view, but i want use generic view: class PostList(request): post_list = [] for post in Post.objects.filter(owner=request.user): post_dict = {} post_dict['title']=post.title post_dict['description']=post.description post_list.append(post_dict) return render(request,'post_lists.html', locals()) This is the model: class Post(models.Model): title = models.CharField(max_length=30) description=models.TextField(blank=True, null=True) owner=models.ForeginKey(User) -
Django project - two app's two views in one url how to solve
In my django project i have created one app for log-in users. And another app for sign-up user. But in my .html template both sign-up and log-in function are given on the same page means in one url. Show basically what it means i have to use two apps two different view in one url. How is it possible Cannot combine them in one app cause both of the app has lots of other related functionalities also. -
How to get map from jupyter using django and display it on site?
I want to show map(processed one with all the heatmap and stuff) on a site. I have done it using jupyter and gmaps, like this: import gmaps gmaps.configure(api_key="AI...") fig = gmaps.figure() fig right now i am getting something like this: https://stackoverflow.com/a/43797122/7584043 and i am wondering if i can show that map on a site using django. Can somebody tell me if it's possible, it'll be greatly appreciated. Thanks! -
Django 'Library' object has no attribute 'simple'
I am following the book "Django by Example", and right at the beginning of Chapter 3: Extending your blog application, I am trying to load my blog_tags file, however I get this AttributeError: In template /home/ahmad/Documents/Coding/Django By Example/Excercises/djangoblogapp/mysite/blog/templates/blog/post/list.html, error at line 1 'Library' object has no attribute 'simple' Here is my base.html: {% load blog_tags %} {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %} {% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id = "content"> {% block content %} {% endblock %} </div> <div id = "sidebar"> <h2> My Blog</h2> <p> This is my blog. I've written {% total_posts %} posts so far. </p> </div> </body> </html> and my post/list.html: {% extends "blog/base.html" %} {% block title %}My Blog {% endblock %} {% block content %} <h1> My Blog </h1> {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url "blog:post_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> <p class="date"> … -
How to Stream VOD on Django with Nginx-rtmp
I have a problem when I try to stream VOD on Django. I have been follow this link for streaming VOD with nginx-rtmp-module and I succeeded: https://helping-squad.com/setup-a-simple-video-on-demand-server-with-nginx-rtmp/ So after that, I install Django follow this: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 and my problem is JWplayer has notified me "Error loading stream: Could not connect to server" Im fresher so I don't know what should I do. -
ModelMultipleChoiceField "Enter a list of values." error when updating
In a Django form, I have a field where a user can select other users, or let it blank. In the model, this is a models.ManyToManyField. To be able to show the user name, I have: class UserModelChoiceField(ModelMultipleChoiceField): def label_from_instance(self, obj): return "%s" % obj.get_full_name() class ExampleForm(models.Model): user_involved = UserModelChoiceField(queryset=User.objects.all(), required=False) (...) I use this form for both create and update purposes. However, when the action is updating and the user doesn't select anything I get, in self.errors: <ul class="errorlist"><li>user_involved<ul class="errorlist"><li>Enter a list of values.</li></ul></li></ul> To debug I printed the cleaned_data in the clean() method and I got: When I'm doing create: <QuerySet []> When I'm doing update: None If the field is not required, why is None a problem? What can I do to resolve the problem, besides the obvious: if not cleaned_data['user_involved'] and self.errors['user_involved']: del self.errors['user_involved '] -
override python-social-auth built-in urls?
I am using python-social-auth for Google authentication in my Django application. Can I override the python-social-auth URLs ? By default, it's http://mydomain/login/google-oauth2/ and I need to change the URL as part of my view (get request) ; which has the end-point as http://mydomain/login/. -
How to add custom permission in viewset
How to add custom permission in viewset in django rest framework other than the default permission while creating a module? I have a permission "fix_an_appointment". In the below viewset, how to include this permission? Those who have this permission has only able to create. My views.py file: class settingsViewSet(viewsets.ModelViewSet): serializer_class = SettingsSerializer queryset = Setting.objects.all() Can anyone help? -
Request Http Post from postmarkapp and csrf exemption
Hello so i have trying to obtain data from http request forwarded from an inbound email from postmarkapp and trying to save via forms. When i use CSRF exempt and try to post data the data doesn't save and database shows blank. when i try to use without csrf it shows 403 error. def on_incoming_message(request): if request.method == 'POST': form_class=enquiriessampleForm form=form_class(request.POST) if form.is_valid(): callback_body = request.body.decode('utf-8') callback = json.dumps(callback_body) enquiriess = enquiries.objects.all() enquiriess.mobile = "00908080879" enquiriess.body_plain = callback form.save() return HttpResponse(enquiriess.mobile) else: return HttpResponse(nothing) else: form=enquiriessampleForm() enquiriessample = enquiries.objects.all() return render(request,'vendors/fetchdata.html',{'enquriessample':enquiriessample,'form':form,}) -
Django-graphos SimpleDataSource extension issue
I'm building a django web app where I use graphos to add google charts to my app. I have a class CustomDataSource that is extending SimpleDataSource and I'm overriding the get_data() method and everything is working super fine and the charts were showing up. Now I added an __init__ constructor to my custom class to pass an extra variable that I need in get_data(). The constructor is being called fine and the variable is passed but for some weird reason, the get_data() method is never called and I cannot show the chart. class CustomDataSource(SimpleDataSource): def __init__(self, data, wcs): super(CustomDataSource, self).__init__(data) self.wcs = wcs print self.wcs def get_data(self): data = super(CustomDataSource, self).get_data() print 'get data ' # Build data to be returned and return it Any ideas? -
Django signals: how is it implemented
I would like to understand how Django implements signals. The only way I can imagine that it would work is that every Django application lives in an event loop and that signals trigger callbacks into action. I've done quite a number of searches online and on SO but nothing comes up. Could someone please give a detailed explanation on this? I've learned more Python from Django and I'm sure this is another opportunity. Thanks. polarise -
'RadioSelect' object has no attribute 'renderer'
I have made a web site by seeing django tutorial. https://docs.djangoproject.com/en/1.11/intro/ I got an error, AttributeError at /polls/1/ 'RadioSelect' object has no attribute 'renderer' It happens in line 21 of forms.py,which is init. I wrote in forms.py like from django import forms class MyForm(forms.Form): text = forms.CharField(max_length=100,required=False,label='テキスト') class VoteForm(forms.Form): choice = forms.ModelChoiceField( queryset=None, label='選択', widget=forms.RadioSelect(), empty_label=None, error_messages={ 'required':"You didn't select a choice.", 'invalid_choice':"invalid choice.", }, ) def __init__(self,question,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['choice'].queryset = question.choice_set.all() self.fields['choice'].widget.renderer.inner_html = '{choice_value}{sub_widgets}<br>' Setting of radio button is written in detail.html,like <!DOCTYPE html> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'poll_vote' question.id %}" method="post"> <!--<form action="" method="post">--> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <!--{{ form }}--> <input type="submit" value="Vote" /> </form> </html> views.py is from django.shortcuts import render from django.utils.html import mark_safe from .models import Question from django.http import HttpResponse from django.shortcuts import Http404 from django.shortcuts import get_object_or_404,redirect from .models import Choice from django.views.generic import TemplateView from django.views.generic import DetailView from django.views.generic import ListView from .forms import MyForm from .forms import VoteForm # Create your views here. def … -
Django missing Vary:Cookie header for cached views
I've got a pretty complex webapp based on Django 1.11. Some time ago users started reporting that they are getting 'someone else's views' - memcached provided them with html cached by decorator @cache_page(xx) without distinguishing between sessions within the cache grace period. Upon further investigation, I discovered that in some cases Vary: Cookie header was missing and wrong 'session' was served. What's strange, it only showed when querying backend with curl (which has no session, user etc -> backend served logged in cached view). Unfortunately, this issue is really hard to reproduce, sometimes it occures, sometimes it doesn't. I even build a simple Django app from scratch to see if I could check what is the cause. What was observed, is that the issue does not occur when @cache_page is removed or login_required is added . I ended up removing all @cache_page decorators from views and the issue was not observed on production since but it's a workaround and I would like to know what is the cause. If anyone has any hint what could be the cause, it would be greatly appreciated! -
Django: use AdminLTE as template in views
I have to start a project in Django which will be used internally in our company so no need to use a custom layout, adminLTE2 template or similar should be just fine. The project is used to manage internal stuff, this project could get bigger as it evolves and we need to add new features. My doubt is that I don't know where and how to use it, if in the Django admin part or integrate and use it as app template. From what I understand, working with django admin it's not fully customizable as working with app template, this makes me a little bit confused. In short: should I use the Django admin or app template? how can I integrate AdminLTE or similar as django app template? thank you -
Django 1.11 - forms.Models: change default form widget for DateTimeField
I have a data field missing_date = models.DateTimeField(null=True, blank=False). The default django form widget is to use TextInput, and it is not displaying as Calendar Date/Time select as in the admin page. Can you please advise how can I display the Calendar Date/Time like below: It is really appreciated with your help. Thanks Henry -
Couldn't import django in docker image on GitLab CI
I tried running my django tests python manage.py test in gitlab ci. Therefore I'm using a docker image. The docker image builds fine, but when it runs the tests on gitlab i get ImportError: No module named 'django' and 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? See my .gitlab-ci.yml image: registry.gitlab.com/app/core:latest services: - postgres:latest stages: - test variables: SECRET_KEY: test-secret POSTGRES_DB: ... POSTGRES_USER: ... POSTGRES_PASSWORD: ... python_tests: stage: test before_script: - export DATABASE_NAME=... - export DATABASE_USER=... - export DATABASE_PASSWORD=... - export DATABASE_HOST=postgres - source /app/venv/bin/activate script: - python manage.py test and Dockerfile FROM ubuntu:16.04 RUN apt-get update -y -qq RUN apt-get install -y -qq build-essential libffi-dev libpq-dev libfontconfig1 RUN apt-get install -y -qq python3 python3-dev python3-pip RUN apt-get install -y -qq libpq-dev RUN apt-get install -y -qq nodejs npm WORKDIR /app # pip COPY requirements.txt /app RUN pip3 install --upgrade pip RUN pip3 install virtualenv RUN virtualenv --no-site-packages venv RUN . venv/bin/activate RUN pip3 install -r /app/requirements.txt # npm RUN ln -s `which nodejs` /usr/bin/node COPY web/vueapp/package.json /app RUN npm install -
ImportError: No module named system_admin
When I run server use : $ python manage.py runserver But get the bellow error: Unhandled exception in thread started by <function wrapper at 0x1015d0320> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/config.py", line 127, in create import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named system_admin This is my project directory: My project(officialWeb) has a APP(frontend), and in the future I will create systemAdmin and userAdmin APP. Why there gets the ImportError: No module named system_admin error? -
Django Operational Error
when I add a new column in a database table and migrate model at that time operational error occurs ERROR: django.db.utils.OperationalError: (1067, "Invalid default value for 'calling_code'") -
Django error creating new contenttypes when running tests
I noticed that when running my tests, it would immediately output the following, and stop the test: "Error creating new content types. Please make sure contenttypes " RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually. I have a model with a field that is restricted to only two choices of contenttypes, let's say type A and B. CONTENT_TYPES = ( ContentType.objects.get_for_model(A).id, ContentType.objects.get_for_model(B).id, ) content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE, limit_choices_to={'id__in': CONTENT_TYPES}) However, I won't be able to run any tests, as this seems to block it. Is there any way to not evaluate these contenttypes on startup/when running tests? I tried it using the django.utils.functional.lazy, which someone recommended but it did not seem to work. -
How to import model in Django
I want to execute a python file where I want to check if there are new rows in a csv file. If there are new rows, I want to add them to a database. The project tree is as follows: Thus, the file which I want to execute is check_relations.py inside relations folder. check_relations.py is as follows: from master.models import TraxioRelations with open('AUTOI_Relaties.csv', 'rb') as tr: traxio_relations = tr.readlines() for line in traxio_relations: number = line.split(';')[0] number_exists = TraxioRelations.objects.filter(number=number) print(number_exists) The model TraxioRelations is inside models.py in master folder. When I run python check_relations.py I get an error Traceback (most recent call last): File "check_relations.py", line 3, in <module> from master.models import TraxioRelations ImportError: No module named master.models What am I doing wrong? How can I import model inside check_relations.py file? -
Admin filter for groups not worked
I have created a filter for the admin page, to display the users that are in a group and that are not. Using django 1.8 there is no problem with the class. But after upgrading django, The error is : AttributeError at /admin/main/profile/ can't set attribute The code is : class ProfileAdminListFilter(admin.RelatedFieldListFilter): def __init__(self, *a, **kw): super(ProfileAdminListFilter, self).__init__(*a, **kw) def has_output(self): return True @property def include_empty_choice(self): return True @property def empty_value_display(self): return "No group" def choices(self, cl): for c in super(ProfileAdminListFilter, self).choices(cl): yield c if self.include_empty_choice: yield { 'selected': bool(self.lookup_val_isnull), 'query_string': cl.get_query_string({ self.lookup_kwarg_isnull: 'True', }, [self.lookup_kwarg]), 'display': self.empty_value_display, } class ProfileAdmin(admin.ModelAdmin): list_filter = (('user__groups', ProfileAdminListFilter),)