Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
parent class __init__ is not invoking multiple inheritance
I have created a connexion app using swagger generator, and I'm using flask-mongoengine to connect and configure backend. But the problem is I'm getting AttributeError from the mongoengine. My base_model_.py have the following ... from flask_mongoengine import MongoEngine ... db = MongoEngine() class Model(object): """Class definitions""" And the __main__.py import connexion from my_app.models.base_model_ import db if __name__ == '__main__': app = connexion.App(__name__, specification_dir='./swagger/', server='gevent') app.app.config['MONGODB_SETTINGS'] = { .... } ..... """ other configs """ db.init_app(app.app) # Create a user to test with @app.app.before_first_request def create_user(): user_datastore.create_user(email='test@test.com', password='password', phone='1234567890', country="IN") And the User.py from __future__ import absolute_import from my_app.models.role import Role from my_app.models.location import Location from flask_security import UserMixin from .base_model_ import Model, db from datetime import date, datetime from typing import List, Dict from ..util import deserialize_model class User(db.Document, UserMixin, Model): def __init__(self, name: str=None, email: str=None, phone: int=None, password: str=None, country: str=None, os: str=None, location: List[Location]=None, device_id: str=None, active: bool=False, roles: List[Role]=None, created: int=None, updated: int=None): self.swagger_types = { 'name': str, 'email': str, 'phone': int, 'password': str, 'country': str, 'os': str, 'location': List[Location], 'device_id': str, 'active': bool, 'created': int, 'updated': int, 'roles': List[Role] } """ other swagger declarations""" name = db.StringField(max_length=75) email = db.StringField(max_length=255) phone = db.IntField(max_length=10) password = … -
Django User model -override, how to use login
I override Django User,and it worked, but i cannot use auth.authenticate to login username = 'test' password = '123' user = auth.authenticate(username = username, password = password) result = '' if user: results = 'success' auth.login(request,user) else: result = 'fail' return render(request, 'login.html', locals()) this is my modle.py class User(AbstractUser): qq = models.CharField(max_length=20) class Meta: verbose_name = 'Myuser' def __str__(self): return self.username and it return fail,how can i use login -
Gunicorn gock file not appear
I have a web server created with Django, but from one moment to another my server is down and nginx return error 502, before I create my sock file, but when I try again I can't create this. pkill gunicorn sudo systemctl daemon-reload sudo systemctl start gunicorn sudo systemctl enable gunicorn I read something about web permissions for folders but I think the folder that contains my server has all the possible permissions. drwxrwxr-x 8 ubuntu ubuntu 4096 Sep 8 02:17 trackerServer On the other hand this is my /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/tracker-web/trackerServer ExecStart=/home/ubuntu/tracker-web/trackerServer/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/tracker-web/trackerServer/trackerServer.sock trackerServer.wsgi:application [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/django_joya/ ExecStart=gunicorn --workers 3 --bind unix:/home/ubuntu/django_joya/joyas.sock joyas.wsgi:application [Install] WantedBy=multi-user.target In the server there are 2 projects, but only tracker-web/trackerServer are mine, django_joya is the other person. Any help please, I can not generate my sock file -
Getting objects of many to many to one to many
I have a User model, with a ManyToMany relation with a Department model (so, 1 user can be in multiple departments and 1 department can have multiple users). I also have another model, let's call it "Object". 1 department can have multiple objects, but 1 object can belong only to 1 department. What is the optimal way of getting a list of all object IDs from all the departments that a user belongs to? I mean, sure, I can fetch all departments of the user, and then iterate over each department and fetch all the objects, but I really don't think that is optimal. -
I want to make a dictionary in good order
I want to parse excel and put data in the model(User).Now I want to make a dictionary which has excel data. Excel is I wrote in views.py #coding:utf-8 from django.shortcuts import render import xlrd def try_to_int(arg): try: return int(arg) except: return arg def main(): book3 = xlrd.open_workbook('./data/excel1.xlsx') sheet3 = book3.sheet_by_index(0) data_dict = {} tag_list = sheet3.row_values(0)[1:] for row_index in range(1, sheet3.nrows): row = sheet3.row_values(row_index)[1:] row = list(map(try_to_int, row)) data_dict[row_index] = dict(zip(tag_list, row)) print(data_dict) main() and it printed out {1: {'A': '', 'area': 'New York', 'C': 0, 'name': 'Blear', 'B': ''}, 2: {'A': '', 'area': 'Chicago', 'C': '', 'name': '', 'B': 0}, 3: {'A': 0, 'area': 'London', 'C': '', 'name': '', 'B': ''}, 4: {'A': '', 'area': 'Singapore', 'C': '', 'name': 'Tom', 'B': ''}, 5: {'A': 0, 'area': 'Delhi', 'C': '', 'name': '', 'B': ''}, 6: {'A': '', 'area': 'Beijing', 'C': 1, 'name': '', 'B': ''}} But I cannot understand why output dictionary is mess.I want to get a dictionary like {1: {'name': 'Blear', 'area': 'New York', 'A': '', 'B': '', 'C': 0}, 1: {'name': 'Blear', 'area': 'Chicago', 'A': '', 'B': 0, 'C': ''}, 1: {'name': 'Blear', 'area': 'London', 'A': 50, 'B': 0, 'C': ''}, 2: {'name': 'Tom', 'area': 'Singapore', 'A': … -
Django - passing variable to javascript file within same script tag
I am trying to pass my variable from Django's view to a javascript file. I read the stack question here (How can I pass my context variables to a javascript file in Django?) to get a few guidance but I am trying something a little bit different. I want to pass variable to the javascript file within that particular javascript reference script tag or changing the order of variable declaration. It is easier to show by example: My somerandom.js: console.log(variable); What works: {% extends base.html %} {% load static %} {% block body %} <h1> Hello, World! </h1> {% endblock body %} {% block javascript %} <script> var variable = {{ my_var }}; </script> <script src="{% static "app1/bootstrap/js/somerandom.js" %}"></script> {% endblock javascript %} What doesn't work: 1: {% extends base.html %} {% load static %} {% block body %} <h1> Hello, World! </h1> {% endblock body %} {% block javascript %} <script src="{% static "app1/bootstrap/js/somerandom.js" %}"></script> <script> var variable = {{ my_var }}; </script> {% endblock javascript %} 2: {% extends base.html %} {% load static %} {% block body %} <h1> Hello, World! </h1> {% endblock body %} {% block javascript %} <script src="{% static "app1/bootstrap/js/somerandom.js" %}"> var variable … -
Django admin inline table not posting values to one to one relationship
sorry for the convoluted question but I am a uni student who has been thrown into the Django framework without any training and I'm doing my best to understand all this in a short time. I really enjoy Django but just can't figure out one problem I'm having. So for the assignment, I need to extend the default admin users table to include more fields. This is what i've done: models: class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) userTypeID = models.ForeignKey(UserType) dob = models.DateField() contactNumber = models.IntegerField() address = models.CharField(max_length=50) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: UserInfo.objects.create(user=instance) UserInfo.save(instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userinfo.save() def __str__(self): return str(self.user) admin: class UserInfoInline(admin.StackedInline): model = UserInfo class UserAdmin(UserAdmin): inlines = (UserInfoInline, ) admin.site.register(UserType) admin.site.register(City) admin.site.unregister(User) admin.site.register(User, UserAdmin) This brings up the extra fields in the admin panel which is what i was looking for. However, when i try to add a new user and I select one of the userTypes (the OneToOneField), I get: IntegrityError at /admin/auth/user/add/ (1048, "Column 'userTypeID_id' cannot be null") Now I understand my 'Signal receivers' (as I understand them to be) are missing something to handle this but I am unsure as to what. Any … -
How do I pre join data for django web application
On my iOS app, when a user logs in I start a series of firebase listeners for my users data... Profile, Accounts, Campaigns, etc.. How and where would I do something like this is django/python? I have a firebase db. I configure it in the top of my views.py, I log the user in on my login view. At this point in the iOS app, I add it to an AppState File and can call it from any view. In django, I ended up calling the data and creating my "joins" in the actual view like so: campaign_list = [] results = db.child('campaigns').get(refresh_token) for campaign in results.each(): campaign = models.Campaign().db_snapshot(campaign) result = db.child('accounts').child(campaign.userUUID).get(refresh_token) campaign.account = models.Account().db_snapshot(result) Now I have my campaign object and attached the account object. db is set from the config at the top of my views.py. I believe this the correct way? I know its weird to use firebase and django, and I'm slowly switching to postgresql, but in the mean time, I have to continue to use firebase. So how do I create a so called snapshot of my user, then access the data when they visit specific views. Aka, create a list of accounts, then … -
Getting Exception when download Wagtail
an exception is displayed on my terminal when attempting to install wagtail using command "pip install wagtail" This is returned: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip/wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/OleFileIO_PL.py' -
Including Django template from one app in another app template
I'm trying to include a template that show user posts on the user's profile. I have used an inclusion tag however it the posts are not displaying on the user's profile. It does, however, work on the home page, which is set to be the PostListView from that app. Inclusion tag in userprofile_detail.html: <div class="content-right"> {% include 'feed/userpost_list_inner.html' %} </div> The actual list of post (the feed) in userpost_list.html: {% for post in userpost_list %} <div class="post"> <h2 class="post-title">{{ userpost.post.title }}</h2> <p class="accent">{{ post.author }}</p> <p class="accent">{{ post.post_date }}</p> <p class="body">{{ post.post_body }}</p> </div> {% endfor %} I'm not getting any errors, however the posts are not displaying on the user's profile page. -
Cache-Control not being set in response header
I am trying to optimize my Django web application by leveraging browser caching. I set a Cache-Control header for max-age equal to a year in my home view function returned response. When I load up my site however, and check the response header of some of the images on my home page, the cache-control header isn't there. I tried two different methods of setting the response header. First I tried using Django's built in cache-control decorator. I also tried simply taking the rendered response, and setting the header in my view function before its return statement. Are static images cached differently ? View Function def view_home(request, page=None): # FIND THE HOME PAGE IF WE DO NOT HAVE ONE # IF NOT FOUND RETURN 404 if not page: try: page = WebPage.objects.get(template='home') except WebPage.DoesNotExist: raise Http404 try: billboards = Billboard.get_published_objects() except Exception as e: logging.error(e) billboards = None project_types = ProjectType.get_published_objects() budgets = Budget.get_published_objects() deadlines = Deadline.get_published_objects() contact_descriptions = ContactDescription.get_published_objects() contact_form = ContactForm(type_list=project_types, budget_list=budgets, deadline_list=deadlines, description_list=contact_descriptions) context = {'page': page, 'billboards': billboards, 'contact_form': contact_form} set_detail_context(request, context) template = 'home.html' # Add Cache control to response header expiry_date = datetime.datetime.now() + datetime.timedelta(days=7) response = render(request, template, context) response['Cache-Control'] = 'max-age=602000' response['Expires'] = … -
IndexError: list index out of range ,I do not use out list index
I wanna parse excel and put data in the model(User). I wrote in views.py import xlrd book = xlrd.open_workbook('excel1.xlsx') sheet = book.sheet_by_index(0) cells = [ ('user_id', 0, 5), ('name', 3, 1), ('nationality', 3, 2), ('domitory', 3, 3), ('group', 3, 4)] user1 = {key:sheet.cell_value(rowy, colx) for key, rowy, colx in cells} print(user1) Excel is In this case,domitory is empty.I run this code,so error happens IndexError: list index out of range Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/XXX/testapp/app/views.py", line 112, in <module> user1 = {key:sheet3.cell_value(rowy, colx) for key, rowy, colx in cells} File "/Users/XXX/testapp/app/views.py", line 112, in <dictcomp> user1 = {key:sheet3.cell_value(rowy, colx) for key, rowy, colx in cells} File "/Users/XXX/myenv/lib/python3.5/site-packages/xlrd/sheet.py", line 415, in cell_value return self._cell_values[rowx][colx] I cannot understand why this error happens because I did not write codes was accessed to out of index list.But how can I fix this?What should I write it? -
Django: how to give 'pending-authorization status' and manually authorize user through admin after signup
I'm building a service that targets specific group of people. So I need to evaluate user's signup form and allow only qualified users to login to our website. I first thought about using is_active field in default user model, but then again this field is normally used to filter deleted accounts I thought about implementing the signup process like the following: Allow user to signup Create a pending-auth group with NO permissions for the just signed-up users, who are waiting for authorization Evaluate the users qualifications If qualified, the user from the 'pending-auth' group; this should allow user to login and proceed. How do you think about this? Is this a good way to implement the signup process? I have no idea if this is the CORRECT way to handle my needs. Thanks in advance for the advance! -
Nested filters in a Django app
I have the next model in my Django App: class Value(models.Model): entity = models.ForeignKey('Entity',on_delete=models.CASCADE, related_name='entity') variable = models.ForeignKey('Variable',on_delete=models.CASCADE, related_name='variable') value = models.FloatField(default=0) Now, I need to filter all the "Value" objects where variable "A" is less than 20, and variable "B" is less than 4, for example. I'm trying to filter in this way, but is not working (and variables and values are dynamic and the user can select their combination in the View): entity_list = Value.objects.all().filter(variable__symbol='A', value__lte=20) entity_list = entity_list.objects.all.filter(variable_symbol='B', value_lte=4) Thank you in advance. -
Django: setting background image
I am making a blog with django. I want to set every posts background in admin. so this is what i want to do: background: url({{ post.photo }}); it is not working -
Geodjango, sort results by distance and show the distance explicitly in KM
I currently sort results by distance for my model using: views.py SearchPoint = Point(long, lat) res = Model.objects.filter(location__distance_lte=(SearchPoint, D(m=2000))) .annotate(distance=Distance('location', SearchPoint)).order_by('distance') This allows me to sort the results by distance which are within 2000m. Now I would like to also display the distance between the searcher which is given by SearchPoint and results of my Model. Models.py In my model class I define the following property: # @property # def distance_to_searcher(self): # distance =self.location.distance(SearchPoint) # return distance * 100 I get the following error: name 'SearchPoint' is not defined I understand that this is not defined, because it gets defined in the views.py file, which is a GET request and take long and lat parameters from the URL and puts them into Point() class. Ideally, I would round up the distance to a nice number. -
Django reverse proxy server CORS
I am looking to write a route that works exactly like this https://github.com/Rob--W/cors-anywhere in django I'm thinking it's similar like in this question Django as reverse proxy My question is how to add cors headers into it. I've also take a look of this https://github.com/ottoyiu/django-cors-headers, will the reverse proxy simply works for CORS, just by adding the django-cors-headers? -
How do you give a wagtail/django Page a custom url to serve at?
In wagtail/django how do you make a basic wagtail Page model, create the html template, and then tell that model to serve as a view for a specific url? from django.db import models from wagtail.wagtailcore.models import Page class MyPage(Page): title = models.CharField(blank=True, null=True, max_length=255) #... I want the url to register like url(r'^monkey/(?P<slug>[A-Za-z0-9]+)$', ...) But I don't have a common urls.py folder its stored outside of the project. I tried using the RoutablePageMixin, but I believe that serves for subpages. I also know where you store the html template within the structure so that is no problem. -
Django: Why am I getting a Value Error?
The variables are defined before the if statement. if (len(Item.objects.filter(owner=request.session['id'])) > 0): for x in Item.objects.filter(owner=request.session['id']): if (x.item == forageitem): x.amount = x.amount + 1 x.save() messages.success(request, "You found a " + forageitem +".") return redirect("/dashboard") else: continue The function passes through the if statement just fine, but if the item in question is not found, it will not create a new object in the Item class, instead it will give me an error. For some reason, I am getting a ValueError at this part of my code: else: Item.objects.create(item=forageitem, owner=User.objects.get(id = request.session['id']), description=item[forageitem], amount=1) messages.success(request, "You found a " + forageitem +".") return redirect("/dashboard") I am almost certain I didn't change anything here, it was working before. Ideas, anyone? Please help. -
Django, redirect issue NoReverseMatch
My panel have pages. When I delete one of pages, delete_view() should come back to panel url For example: Panel: stack, inside: coffee, book URL: /stack Using button I delete coffee and delete_view should come back to /stack and show only book page. views.py: def panel_detail(request, slug): panel = Panel .objects.get(slug=slug) pages= panel.pages context = {'panel ': panel , 'pages': pages} template = 'panel /panel_detail.html' return render(request, template, context) def delete_page(request, title_page, var): page= Page.objects.get(title_page=title_page) page.delete() # NOT WORKING return redirect('panel_detail', slug=var) HTML: for i in pages... href="{% url 'panel:delete_page' title_page=i.title_page var=i.panel.slug %}" urls.py: url(r'^(?P<slug>[-\w]+)/$', views.panel_detail, name='panel_detail'), url(r'^panel/page/delete/(?P<title_>[-\w]+)/$', views.delete_page, name='delete_page'), Debugging: delete_page(): title_page = coffee , var = stack page = coffee ( object in DB) , delete working. Django: Reverse for 'delete_page' with keyword arguments '{'title_page': 'coffee', 'var': 'stack'}' not found. 1 pattern(s) tried: -
Why is nothing being saved when trying to update objects with objects.all() and a dedicated model method?
I am writing an API to help me maintain my django db when needed. One function of my API is to update a specific field for all concerned objects thanks to a dedicated method of my model. The issue I have been facing with is the following: nothing is being saved when trying to do so! This specific model is using geoDjango. Here below is an example of my model: models.py class Location(geoModels.Model): coord_field = geoModels.PointField(blank=True, null=True) def update_coord_field(self): # function does some useful stuff self.coord_field = newValue Now here is what I am trying to do from a script being executed through python manage.py shell: script.py from MyApp import models as MyAppModels def update_all_coord_field(): for location in MyAppModels.Location.objects.all(): print(location.coord_field) # display old value location.update_coord_field() location.save() print(location.coord_field) # display new value: nice! But when trying to execute my script again (or simply just trying to use my new valued attribute), I can only observe that nothing was saved to the db. Would you have any idea why this is not working? To me, doing this is the same as doing MyAppModels.Location.objects.update(coord_field=newValue) for all concerned objects... but even doing that is not working. Thank you for the time you will take … -
Error sending a file using Django - file turns out empty
This is my views.py files: from django.http import HttpResponse def render(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' response['X-Sendfile'] = '/files/filename.pdf' # path relative to views.py return response When I run the server and request http://localhost:8080/somestring I get an empty file called somefilename.pdf. I suspect that there is some crucial part missing in render. The other parts of this app outside of views.py are correct to my understanding. -
Passing Url params from one page to another
So I have a filter form on a page that show paginated results. Currently when you apply the filter settings using a get request everything works but when you try to switch pages it resets. I have thought of passing a url from one page to another using a script like the one below. This copies the url but does not actually change the page, just copies the string. You can see in the urls below that the url does change page but the actual webpage stay on the first page regardless of the url. I am using Django and Django filters. Maybe a there is a better jQuery solution, Any suggestions? script document.querySelectorAll('.fqs') .forEach((el) => el.attributes.href.value += window.location.search); Url Without script: /relations/?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1 With Script: /relations/?page=2?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1 Next Page Link <a class="fqs" href="?page={{ relations.next_page_number }}">Next &raquo;</a> -
Celery in FATAL state, too many start retries too quickly
I am gettng FATAL state, too many start retries too quickly error in running gunicorn + celery and My supervisor.conf file looks like [supervisord] logfile=/home/ubuntu/supervisord.log logfile_maxbytes=50MB logfile_backups=10 loglevel=info pidfile=/home/ubuntu/supervisord.pid nodaemon=false minfds=1024 minprocs=200 [program:gunicorn] command=gunicorn FoodCham.wsgi:application --bind 127.0.0.1:8001 --pid /home/ubuntu/gunicorn.pid; directory=/home/ubuntu/testingfoodcham_Desktop/ autostart=true autorestart=true [program:FoodCham-celery] command=/home/ubuntu/testingfoodcham_Desktop/celery worker -A web --loglevel=INFO directory=/home/ubuntu/testingfoodcham_Desktop/ user=nobody numprocs=1 stdout_logfile=/home/ubuntu/logs/celery.log stderr_logfile=/home/ubuntu/logs/celery.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq is supervised, it will start first. priority=1000 [inet_http_server] port=127.0.0.1:9001 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=http://0.0.0.0:9001; Any helpful answer will be appreciated. -
Creating auth token for non user object django rest framework
I am looking to generate a django authtoken for a non user object. previously I had easily generated auth tokens for user objects like this email = request.data.get('email') user = User.objects.get(email=email) Token.objects.create(user=user) but if I am trying this for non user object it is not getting generated. device_id = request.data.get('device_id') tablet = Table.objects.get(device_id=device_id) Token.objects.create(user=tablet) Here Table is simple model holding various device_ids. I just want to generate an auth token for each tablet like we do for each user.