Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 is not loading css files
I have the next configuration: urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^manager/', include('manager.urls')), #Static pages url(r'^index', TemplateView.as_view(template_name='index.html'), name='index'), url(r'^', TemplateView.as_view(template_name='index.html'), name='index'), url(r'^contact', TemplateView.as_view(template_name='contact.html'), name='contact'), url(r'^services', TemplateView.as_view(template_name='services.html'), name='services'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'pf.app.pfs', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets"), #'/var/www/static/', ] I executed the command: python manage.py collectstatic And the files are generated, also I added a css file with a single rule but and executed the command again. But, in the momento to add it to my html file <head> {% load static %} <link rel="stylesheet" href="{% static '/css/style.css' %}" /> </head> in the html I get: <link rel="stylesheet" href="/static/css/style.css"> And in the terminal: "GET /static/css/style.css HTTP/1.1" 404 1766 What I have wrong in my static files configuration? -
django channels send many in single function
I am new in django channels. It is a image uploads app. Since it takes a long time. I am trying to print log onto front end. My code is like: def upload(m): m.reply_channel.send({ 'accept': True, }) socket_handler = SocketHandler(m) inst = ImageUpload(socket_handler=socket_handler) inst.newPic(m) m.reply_channel.send({ 'close': True, }) return And SocketHandler is like: class SocketHandler(logging.Handler): def __init__(self, message, *args, **kwargs): super().__init__(*args, **kwargs) self.message = message def emit(self, content, *args, **kwargs): self.message.reply_channel.send({ 'text': '['+datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')+'] '+content.name+' '+content.msg, }) But not like my expectation, the logging only shows up on front end after the upload function returned. I would like to list the logs one by one. So what can I do? -
Is it possible for me to install django-cors-headers version 1.1.0? If so, how?
When I try to install django-cors-headers v1.1.0 on Django 1.7, I'm getting the pip error "No matching distribution found for django-cors-headers-1.1.0" Is it possible for me to install version 1.1.0? If so, how? -
geodjango with mysql getting error django.db.utils.OperationalError: (1045, "Access denied for user
seetings.py DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql','django.contrib.gis.db.backends.mysql' 'OPTIONS': { 'read_default_file': os.path.join(PROJECT_ROOT,"my.cnf"), }, }, } without 'django.contrib.gis.db.backends.mysql' the code is working fine but since i want to use django geolocation using mysql i added this (if I don't add I get "'databaseoperations' object has no attribute 'geo_db_type'" error), and now I am getting "django.db.utils.OperationalError: (1045, "Access denied for user ---" error although the user has full privileges. Please help I am new to django Thank you -
Python/Django : form data validation in TemplateView
I'm beginner in Django and have a little trouble with TemplateView and Forms and trying to write something similar to StackOverflow. So I have a section with question and a section with answers. views.py class QuestionPageView(TemplateView): question_form = QuestionCreationForm(prefix = 'question_form') AnswerFormSet = formset_factory(AnswerCreationForm, extra = 2) answer_form = AnswerFormSet(prefix = 'answer_form') template_name = 'app/ask_question.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['question_form'] = self.question_form context['answer_form'] = self.answer_form return self.render_to_response(context) def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['question_form'] = QuestionCreationForm(request.POST) context['answer_form'] = self.AnswerFormSet(request.POST) if context['question_form'].is_valid(): context['question_form'].save() return self.render_to_response(context) And forms.py class QuestionCreationForm(forms.ModelForm): title = forms.CharField(widget = forms.TextInput({ 'class': 'form-group', 'placeholder': 'Title of your question' }), required = False ) text = forms.CharField(widget = forms.TextInput({ 'class': 'form-group', 'placeholder': 'Text of your question' }), required = False ) language = forms.ModelChoiceField(queryset = Language.objects.all()) class Meta: model = Question fields = ('title', 'text', 'language') def save(self, commit = False): return super(QuestionCreationForm, self).save(False) def clean(self): results = super(QuestionCreationForm, self).clean() return results class AnswerCreationForm(forms.ModelForm): text = forms.CharField(widget = forms.TextInput({ 'class': 'form-group', 'placeholder': 'Text of your answer' }), required = False ) correct_answer = forms.BooleanField(widget = forms.CheckboxInput, label = _('Is answer correct?'), required = False) class Meta: model = Answer fields = ('text', 'correct_answer') … -
Progress bar for back end python programs on Django or other web frameworks
I've been searching and iterating a lot recently trying to figure out how to have a real time progress bar on the webpage to show the progress of programs running at the backend at the server. Right now I'm using Django for building the website as I need to run python programs on the server. So far when the web user click "submit" button, it will take the python program (written in views.py) about one minute to present the result and having a progress bar can really help here. Hope I provided enough detail about my question and thank you in advance for any one who can help. -
django execute collectstatic command
I'm trying to execute the command: $ python manage.py collectstatic ** settings.py ** import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets"), #'/var/www/static/', ] And my ** manage.py ** #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "piefinance.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise 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?" ) raise execute_from_command_line(sys.argv) But, when I execute the command $ python manage.py collectstatic I get this error: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/init.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect for path, storage in finder.list(self.ignore_patterns): File "/Users/myuser/Documents/Projects/myproject/venv/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", … -
form is not populated with data
I have a form for user profile. I am trying to update the profile. The form is shown but the form is not popluated with the data even when passing instance from the view. Here is my view def post(self, request, token=None, format=None): """ update a profile when token is provided """ profile=None if not token is None: try: profile = Profile.objects.filter(user=request.user).get(token=token) print ('profile', profile) serialized_data = self.serializer_class(instance=profile, data=request.data, partial=True) except Profile.DoesNotExist: return error.RequestedResourceNotFound().as_response() except: return error.UnknownError().as_response() reply={} if not serialized_data.is_valid(): return error.ValidationError(serialized_data.errors).as_response() profile = serialized_data.save(user=request.user) reply['data']=self.serializer_class(instance=profile, many=False).data return Response(reply, status.HTTP_200_OK) Here is my serializer class ProfileSerializer(serializers.ModelSerializer): # url = serializers.HyperlinkedRelatedField(source="user", view_name="user_profile") class Meta: model = Profile fields = ('token', 'user','current_location', 'permanent_location', 'dob', 'about_me', 'gender_status', 'create_profile_for', 'marital_status', 'height', 'weight', 'body_type', 'complexion',) -
How to track the time Django takes to run migrations?
I have multiple Django apps with loads of migrations, and they can take a long time to run when building on a VM. For logistic reasons, and to identify areas where we can increase speed I'd like to be able to view the time it took for all migrations to run. What would be the preferred way of doing so? Maybe a management command that kicks off when you run migrate? Can't seem to find much on the topic. -
Access Gunicorn worker from django request
From a Django request, how do I access the Gunicorn worker that is running that request? -
Block malicious user creation with Django?
I have an issue with a user who is creating many malicious accounts with the intent of spamming our service. I'd like to block this user from creating additional accounts. My first thought is to store users' IPs, identify the IP this user is posting from, and then require all users posting from the user's IP to go through additional verification (some kind of real ID, tax ID, phone number, etc. -- something that isn't as easily duplicated as an email address) (along the lines of this question How can I track IPs to block malicious users?). Are there other ways that are recommended for preventing the creation of malicious accounts, more generally? Is there a specific Django best practice to avoid this problem? I am thinking that I will save the IP in an associated Profile model, but wanted to make sure that there wasn't another, accepted way of preventing this issue, since it must be a fairly common problem. -
Django url disspatcher matches the wrong regex
I have created the following urlpatters urlpatterns=[ url(r'(?P<user_name>[a-zA-Z]+)/$', views.profile_view, kwargs=None, name='userprofile'), url(r'(?P<user_name>[a-zA-Z]+)/interests/$',views.interest,name='interests') ] But when I enter the url localhost:8000/mainuser/interest/ it treat it as first url and opens profile_view. It is clearly matching '/'. Help me with this. -
Django Material navbar issue
We're using Django Material (MaterializeCSS as CSS framework) on a new project we are building, and we got an issue with a language selector in the admin navbar. The issue is happening on Firefox, not on Chrome, and I couldn't find what's causing this. Can you check it please? The URL is: https://accountant.swapps.io. Here is how it looks for reference. The templates doesn't have a lot, and the CSS for this is minimal but I can provide code if needed. Thanks! -
Can't connect Ngxin reverse proxy to Gunicorn on Django container (Docker)
I've being trying to make a stack with a Nginx container receiving requests as a reverse proxy to my Django container with Gunicorn (not worrying about static files or DB for now), but I keep getting a 502 Bad Gateway error on Nginx. Nginx logs: 2017/04/28 12:10:10 [notice] 1#1: using the "epoll" event method 2017/04/28 12:10:10 [notice] 1#1: nginx/1.12.0 2017/04/28 12:10:10 [notice] 1#1: built by gcc 6.3.0 20170205 (Debian 6.3.0-6) 2017/04/28 12:10:10 [notice] 1#1: OS: Linux 4.4.0-63-generic 2017/04/28 12:10:10 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576 2017/04/28 12:10:10 [notice] 1#1: start worker processes 2017/04/28 12:10:10 [notice] 1#1: start worker process 7 2017/04/28 12:10:10 [notice] 1#1: start worker process 8 2017/04/28 12:10:10 [notice] 1#1: start worker process 9 172.19.0.1 - - [28/Apr/2017:12:10:17 +0000] "GET / HTTP/1.1" 502 575 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" 2017/04/28 12:10:17 [error] 7#7: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 172.19.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.53.53:8000/", host: "localhost" 2017/04/28 12:10:28 [info] 7#7: *1 client closed connection while waiting for request, client: 172.19.0.1, server: 0.0.0.0:80 2017/04/28 12:10:28 [info] 7#7: *4 client closed connection while waiting for request, client: 172.19.0.1, server: 0.0.0.0:80 2017/04/28 12:10:28 [info] 7#7: *3 client closed … -
how can i log out from app like a facebook log out?
I have this log out function: def logout_view (request): logout (request) return redirect ("/") But, by this function I can go back on my app by clicking on button "GO Back one page" (left above) on a web browser. Then how I can log out like a Facebook, means that I don't have permission to access the page after log out. -
Get next work-item in Django with PostgreSQL
Imagine you have a simple table with work-items: |ID |OWNER|... +---+-----+--- |123| |... |456| |... |789| |... We want to provide a http API to get the next work-item which does not have an owner yet. We use PostgreSQL. We access the table with Django-ORM. I guess there are several race-conditions if the API gets access simultaneously by many users. How can I ensure with the given tools (PostgreSQL, Django) that all race conditions are solved (it is a major fault if a work-item is given to two ore more users). -
Change shown fields in the "Select ___ to change" page on Django's admin site
Django's admin site has a page that lets you choose which object of a certain model to edit. When you click on that object, it goes to the edit page. On that selection page, there is a table with the list of objects. How can I change the columns displayed on that table? Basically, how can I select the attributes which are shown for each object on that page? -
handle multiple form of same model in django rest framework
I have a user profile model which is a little big. I want to show the form in a category basis instead of single form to fill all the profile fields. I mean BasicProfileForm, AboutMeProfileForm, ReligionProfileForm, FamilyProfileForm QualificationWorkProfileForm and etc. Using just django, i created the profile model as below class Profile(models.Model): token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False) user = models.OneToOneField(User) current_location = models.CharField(_('Current Location'), blank=True, max_length=200) dob = models.DateField(_('Date of Birth'), null=True) about_me = models.TextField(null=True) gender_status = models.CharField(choices=gender_choice, default="M", null=True, max_length=1) create_profile_for = models.IntegerField(choices=profile_choice, default=0, null=True) marital_status = models.IntegerField(choices=marital_status_choice, null=True) height = models.IntegerField(choices=height_choice, null=True) body_type = models.IntegerField(choices=body_type_choice, null=True) complexion = models.IntegerField(choices=complexion_choice, null=True) is_inter_cast = models.BooleanField(default=True) #Qualification and Work qualification = models.IntegerField(choices=qualification_choice, null=True) occupation = models.IntegerField(choices=occupation_choice, null=True) income = models.IntegerField(choices=income_choice, null=True) #Cast cast = models.CharField(_('Cast'), max_length=120, blank=True) #Family Background father_name = models.CharField(_('Father name'),blank=True,max_length=255) And i have divided the form in category as follow(just 1 form is shown to make my question clear) class QualificationWorkProfileForm(forms.ModelForm): qualification = forms.ChoiceField(choices = qualification_choice, widget=forms.Select(attrs={'class': 'ui search dropdown'})) occupation = forms.ChoiceField(choices = occupation_choice, widget=forms.Select(attrs={'class': 'ui search dropdown'})) income = forms.ChoiceField(choices = income_choice, widget=forms.Select(attrs={'class': 'ui search dropdown'})) Now if i want to do the same in rest framework, how should i do that? class ProfileSerializer(serializers.ModelSerializer): class … -
How to add django filter for restframework GIS extensions for geopoints?
This is what I have in my filters.py class PropertyFilter(filters.FilterSet): #What's commented out below is what I use in a route to actually do the search queryset. #geom = GEOSGeometry(request.query_params['poly']) #poly_properties = Property.objects.filter(location_point__coveredby=geom) class Meta: model = Property fields = { 'current_price': '__all__', 'beds_total': '__all__', 'pets_allowed_yn': '__all__', 'status': '__all__', 'city': '__all__', 'location_point': ['coveredby'] } filter_overrides = { gis_models.PointField: { 'filter_class': GeometryFilter, 'extra': lambda f: { 'lookup_expr': 'coveredby', }, }, } In the models.py for the property model I have location_point = gis_models.PointField( null=True ) In my views.py I have this class PropertyViewSet(AllowPUTAsCreateMixin, viewsets.ModelViewSet): queryset = Property.objects.all() serializer_class = PropertySerializer ordering_fields = '__all__' filter_class = PropertyFilter """ Takes a polygon with longitude and then latitude """ @list_route() def poly_properties(self, request): #geom = GEOSGeometry('POLYGON(( -80.3653335571289 25.743003105825977, -80.23761749267578 25.743003105825977,-80.23761749267578 25.82523468800373,-80.3653335571289 25.82523468800373,-80.3653335571289 25.743003105825977))') geom = GEOSGeometry(request.query_params['poly']) #poly_properties = PropertyLocation.objects.filter(point__coveredby=geom) poly_properties = Property.objects.filter(location_point__coveredby=geom) #serializer = PropertyLocationSerializer(poly_properties, many=True) serializer = PropertySerializer(poly_properties, many=True) page = self.paginate_queryset(poly_properties) if page is not None: #serializer = PropertyLocationSerializer(page, many=True) serializer = PropertySerializer(page, many=True) return self.get_paginated_response(serializer.data) return response.Response(serializer.data) and when I try to do a GET request with a query string and making location_point={insert geojson polygon here} it doesn't actually filter any properties based on the polygon area. Any idea what could … -
Django. How display only authenticated user comments?
I want display comments from loggedin user, I tried this: {% for c in request.user.game.comment_set.all %} .... {% endfor %} but doesn't work. -
How to implement FirebaseDB with a Django Web Application
Am trying to implement Firebase Realtime Database with my Django Web Application. After properly setting up the configuration with Firebase, I got confused about how data will write into my Firebase Database from my Django website instead of using Sqlite, or Postgres. Under settings.py, do I need to set my engine to Firebase? Am totally confused here. I do not want to use the normal ORM such as Sqlite, Postgres etc. I want my app to use Firebase. Is there something else I need to understand about Firebase? settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } pyrebase_settings file import pyrebase config = { "apiKey": "my_api_key_is_here", "authDomain": "my_auth_domain_is_here", "databaseURL": "my_firebase_database_url_is_here", "projectId": "my_firebase_project_id_is_here", "storageBucket": "my_firebase_storageBucket_is_here", "serviceAccount": "my_serviceAccount.json_file_path_is_here", "messagingSenderId": "messagingSenderId_is_here" } # initialize app with config firebase = pyrebase.initialize_app(config) # authenticate a user auth = firebase.auth() user = auth.sign_in_with_email_and_password("email@usedforauthentication.com", "FstrongPasswordHere") db = firebase.database() -
How to render multiple forms with different data in django view
I have an attendance model using which I want to mark attendance of a list of users for a particular day. But I can't figure out how should I build the view that allows me to render a html table of users with their corresponding attendance form in one column of table in the template. My model for attendance: class Attendance(models.Model): ATTENDANCE_TYPES = ( ('present', 'Present'), ('absent', 'Absent'), ) date = models.DateField("Date") author = models.ForeignKey(User,related_name='attendances_taken') is_present = models.BooleanField(default='True') student = models.ForeignKey(User,related_name='course_attendances') classroom = models.ForeignKey(Classroom,related_name='student_attendance') -
Form overriding: is it the good "Python-way" of doing this?
Form and ModelForm are two different things, but they both inherit BaseForm. I need to have both my own custom ModelForm and my own custom Form that share the same constructor. I've done this: class BaseFormForceLocalizedDateFields(forms.BaseForm): def __init__(self, *args, **kwargs): super(BaseFormForceLocalizedDateFields, self).__init__(*args, **kwargs) pass # some personal code here that overrides behavior of BaseForm # same of the above class, only for Form : class FormForceLocalizedDateFields(forms.Form, BaseFormForceLocalizedDateFields,): pass # same of the above class, only for ModelForm : class ModelFormForceLocalizedDateFields(forms.ModelForm, FormForceLocalizedDateFields,): pass Is my code correct? Is there a better way to do this? -
Django Unknown column
I have a model with the following fields class UserProfile(models.Model): user = models.OneToOneField(User, unique=True, db_index=True, related_name='profile') Email = models.EmailField(max_length=255, db_index=True, null=True) name = models.CharField(blank=True, max_length=255, db_index=True) class Meta(object): db_table = "auth_userprofile" in my Users panel inside the Django Adminsitration i have multiple users, when i try to acces one of them i get this following error (1054, "Unknown column 'auth_userprofile.user_id' in 'field list'") should i drop the table to fix this issue or there is another solution for this -
Django let me log in in Firefox but not in chrome
I recently started playing with Django. When I try to log in into the admin panel, it succeeds in Firefox but doesn't in Google Chrome. This is the error i get : Forbidden (CSRF cookie not set.): /admin/login/ My cookies are enabled in Chrome for every website. Is there a specific reason why it would work in Firefox but not in Chrome? Thanks!