Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
How can I create UpdateView with Django formsets?
I have a couple of models with ForeignKey relation. File and FileRows. One File entry can have multiple FileRows connected to it. I am trying to create and inline form so that I can update and add multiple FileRows to a File entry. I have successfully created the form to add a File with FileRows. Now I am trying to create the UpdateView to update it. But I can't seem to do it. It shows the following error: TypeError at /file/edit/3/ 'File' object does not support indexing The following line from the template is highlighted red: {% for filerow in filerows %} I think this has something to do with my lack of understanding. What am I missing in the following code? models.py class File(TimeStamped): name = models.CharField(max_length=100) def __str__(self): return self.name class FileRow(TimeStamped): file = models.ForeignKey(File) part_no = models.CharField(max_length=30) description = models.CharField(max_length=100, blank=True) quantity = models.PositiveIntegerField() def __str__(self): return "{file} => {part_no}".format(file=self.file.name, part_no=self.part_no) class Meta: unique_together = ('part_no', 'file') forms.py class FileForm(forms.ModelForm): class Meta: model = File fields = ['name'] class FileRowForm(forms.ModelForm): class Meta: model = FileRow fields = ['part_no', 'description', 'quantity'] FileRowFormSet = inlineformset_factory(File, FileRow, form=FileRowForm, extra=2) views.py class FileUpdateView(generic.UpdateView): model = File form_class = FileForm template_name = … -
Deploying a React app on Heroku
I've a React.js application which depends on an API (based on Django Rest Framework). The React and Django applications are decoupled i.e in my local development environment, I run two servers (each using a different port), one for Django and the other for the React. Is it possible to deploy this to a single heroku application or will I need two separate applications? -
Django CMS simple placeholders outside of cms
I have a fully developed Django app and decided to add DjangoCMS to give a content developers a quick way to prototype landing pages etc. It now lives under myurl.com/cms and works quite well. The guys can create new pages, choose a template and add plugins there. When i saw the placeholder template tag I immediately thought about placing it all over the project, outside the cms, everywhere I want the product team to be able to quickly add and change content. I don't want them to create a new page for this from the cms because maybe the site has complex functionality which is only used once in this context (i.e. the search page). So basically I expect to have static placeholders that I can place in the html part of the page using the cms plugins template tags. I already found Placeholders outside the CMS in the DjangoCMS docs. But for this to work I have to grab the related placeholder object for every view that renders a page, which would increase the amount of work to "quickly add a placeholder for this text" considerably. Is there an easy way to do this? I kind of expect to … -
How to display the database value based on categories using Django
I have Column fields are Task Type,Date,Schedule .I need to display the values in templates like Task type and their date, schedule.I have number of date and Schedule for one Task Type. Like this way i need to filter and check condition : I Know the Design to display like this format.But,I need to display data's by Categories wise. Meeting: 1.Date:2017/28/4 -Schedule:With Client 2.Date:2017/29/4 -Schedule:With Team Demo: 1.Date:2017/28/4 -Schedule:demo to Client -
I want to save some values from JS file to database and again retrieve from views
I have a JS file from which I want to save data in database . And after that in a new JS I want to retrieve data again.My JS file is : var geom, strGeom, input, buffer, radius = this.get_radius(), features = mapport.panels.info.current.selection.features.mem; for (var i in features){ geom = features[i].geometry; strGeom = new OpenLayers.Format.WKT(geom); input = reader.read(strGeom.toString()); buffer = input.buffer(radius); buffers[i] = parser.write(buffer); id = models.AutoField(primary_key=True) map = models.ForeignKey(Map, blank=True, null=True) parcel = models.TextField('Parcel') overlay = models.TextField('overlay', default=0) I will make new field in data base buffer_line = models.TextField('buffer_line') And my view is def get_share_permissions(self): privilege = {'map_acl': self.acl.PUBLIC, 'site_acl': self.acl.PUBLIC, 'pro': 'Off'} share = self.request.REQUEST['share'] validate_until = datetime.utcnow()-timedelta(days=30) share = Share.objects.filter(share_id=share, created_at__gte=validate_until).order_by('-id').get() pro_validate = datetime.utcnow() - timedelta(hours=share.expiry_time) if share: pro_share = share.proshare_set.all() if share.snapshot or pro_share.count() == 0: privilege['map_acl'] = share.map_acl privilege['site_acl'] = share.site_acl privilege['pro'] = 'On' # Activate Pro Share if pro_share.count() == 0: share.proshare_set.create(ip=self.get_client_ip(), activated_at=datetime.utcnow()) else: activated = share.proshare_set.filter(activated_at__gte=pro_validate).all() if activated: privilege['map_acl'] = share.map_acl privilege['site_acl'] = share.site_acl privilege['pro'] = 'On' return privilege Now problem is every link on web saying I have to use form to send data back. So I cant do it without using templates ? -
I fail to organize an initialization of my project (python manage.py shell < initialize_project.py)
Django 1.11 Python 3.6.1 In a perfectly flat place (on a billiard table), I have found a pool and drowned in it. Please,have a look at initialize_project.py below and how I run it. And what traceback looks like. If I run it without Django, no exception is risen (below is seen how). Could you give me a kick here? Command and path where it is run: (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive$ python manage.py shell < deployment/initialize_project.py --settings=config.settings.local Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/michael/workspace/venv/photoarchive/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 101, in handle exec(sys.stdin.read()) File "<string>", line 23, in <module> File "<string>", line 17, in initialize NameError: name 'create_users' is not defined This runs perfectly: (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive/deployment$ python initialize_project.py (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project/photoarchive/deployment$ Tree (photoarchive) michael@ThinkPad:~/workspace/photoarchive_project$ tree . └── photoarchive ├── config │ ├── __init__.py │ ├── settings │ │ ├── base.py │ │ ├── __init__.py │ │ ├── local.py │ │ ├── production.py │ │ ├── secrets.json │ ├── urls.py │ └── wsgi.py ├── deployment │ ├── initialize_project.py │ ├── … -
GUI for Django migrations
Is there a web decision to manage django migrations? I couldn't find any. It's a pain even to ssh and run manage.py migrate every time I want to migrate. It would be really nice if at least a part of the migration mechanism would be integrated to django-admin and there would be a web-page with all the pending migrations, an ability to run and rollback them and see the corresponding logs if something goes wrong. -
Django Rest Framework Auth
I'm working on a web application project that uses Django rest framework for its backend and angular 2 for the front end, I want to know if it's recommended to use Django User model for the authentification of my login form (I mean save all user in Django admin), or should I make another User model specifically for the app ? P.S: The application will be using the JWT token for authentification. -
Python Mobile App
I want to develop services or method to send the data over web and to mobile app as well. For now I am using Django Framework (Python code on server side) to get data on web page. I have developed web pages as well. Now I want to send same server data over Mobile App. My mobile app will be developed in Android and iOS. -
Adding a parameter to the fields of a django form which is accessible from the templates
i' ve a Django form which is passed to the templates through the view. In the form' s init i' m trying to add a parameter to each field, which is accessible from code, but not from the template. #forms.py class GenForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(GenForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].dest = 'test_value' help_text = self.fields[field].help_text #template {% for field in form %} {{ field.help_text }} || {{ field.dest }} {% endfor %} #views.py ret_dic['form'] = GenForm(request = request) return render(request, 'template_file', ret_dic) . My goal would be to reach the dest value for the fields from the template, but it' s not displayed at all. What is strange / interesting, is that i can reach the dest value from code: #ipython gen = GenForm() gen.fields['name'].dest #results: test_value . My questions are: how could i reach the dest variable from the template? why is the dest value reachable from code, but not from template? The help_text i can reach from the code and also from the template. Should i somehow register it maybe? Python: 3.4 Django: 1.9 . -
What happens if JSONField has reached maximum storage limit?
This might be a simple question for an experienced (Django) developer. My project's database is PostgreSQL. I intend to use a single protected model instance as a centralised storage for certain data. That instance will have a JSONField which will, in turn, store a dynamic collection of key-value pairs (both are strings). By "dynamic" I mean that new key-value pairs will be added to the collection from time to time, and hence the collection will constantly grow in size. As far as I have read (e.g. Size limit of JSON data type in PostgreSQL), the size limit of JSONField is approximately 1GB. That is quite a lot, but still not infinite. My question is: what exactly will happen if I manage to exhaust the storage capacity of JSONField? And are there any recommendations on how to forecast this kind of situation before it happens (e.g. monitor the instance's storage size)? -
django-autocomplete-light with django-gm2m : how can i do for applying filter for qs?
For applying the filter on all the querysets : qs = qs.filter(EMP-FIRST-NAME__icontain=self.q) My models have a different fields: ** EMP-FIRST-NAME for models Employees. ** FIRST-NAME for models Freecontracts. ** AG_NAME for models Freeagencies. ** FRE_FIRST_NAME for models Freelancers How can i do for applying filter for all models (qs)?? Thanks! Views.py : class RessourceAutocompleteView(Select2QuerySetSequenceView): def get_queryset(self): employees = Employees.objects.all() freecontracts = Frecontract.objects.filter(IS_ACTIVE=True) freeagencies = Freagencies.objects.filter(IS_ACTIVE=True) freelancers = Freelancers.objects.filter(IS_ACTIVE=True) if self.q: employees = Employees.objects.filter(EMP_FIRST_NAME__icontains=self.q) freecontracts = Frecontract.objects.filter(FIRST_NAME__icontains=self.q) freeagencies = Freagencies.objects.filter(AG_NAME__icontains=self.q) freelancers = Freelancers.objects.filter(FRE_FIRST_NAME__icontains=self.q) qs = QuerySetSequence(employees, freecontracts, freeagencies, freelancers) if self.q: # This would apply the filter on all the querysets # this tuple how can i do for apllying filter in all models qs??!!! qs = qs.filter(EMP_FIRST_NAME__icontains=self.q)