Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin queryset filter with TeacherUser using Proxy User model
I have proxy model with User model and extended to TeacherUser with Teacherprofile models.py Model:1 class TeacherUser(User): objects = UserManager() class Meta: proxy = True Model:2 class Teacherprofile(models.Model): teacheruser = models.OneToOneField(TeacherUser) mobile_no = models.PositiveIntegerField() collegename = models.CharField(max_length=20) admin.py @admin.register(TeacherUser) class TeacherUserAdmin(admin.ModelAdmin): pass def queryset(self, request): qs = super(TeacherUserAdmin, self).queryset(request) return qs.filter((query with join form TeacherUser,Teacherprofile) here all the user records are showing,but i need to display the common records from both models .. How can i make query set. Thanks in Advance. -
Django url/page displayed with development server but not apache server
I'm working on Django 1.11, the URL, http://djangoserver:8002/dj/dev/userlogin/789 works with development server, but with apache URL: http://djangoserver/dj/dev/userlogin/789 it throws Page not found (404) error. Regex used for the URL is : url(r'^[0-9]+$', views.userlogin.login , name='login'), The reset of pages are displayed properly. I have tried solution posted in the following posts which did not work for me: django application works on development server but I get 404 on Apache working on django development server but not on apache django production server: root path -
Django static files are not being loaded in Google App Engine
I've been trying out Django with Google App Engine and have been following along their official tutorial https://cloud.google.com/python/django/appengine. I then restructured my the folder structure a bit. This is the folder structure: And shown below is my app.yaml handlers: handlers: - url: /static static_dir: static-only/ - url: .* script: src.codechum.wsgi.application But for some reason I don't know (and have been researching for hours already), the static files are not loading when it is deployed. I also ran the collectstatic function by the way before I actually deployed. Can anyone please help me of where I might be missing something? Thanks! -
What changes should i need to make , to my (django-drf) project settings.py file to integrate it with VueJs frontend?
How the project structure would look like for a project with Django-DRF backend and vue frontend ? -
Django filter not working with lookup object
I have the next code using Django Rest Framework images = ImageUploaded.objects.filter(offer__end_date > date.today()) However, I got the next error: global name 'offer__end_date' is not defined The ImageUploaded model is the next: class ImageUploaded(models.Model): offer = models.ForeignKey(Offer, related_name='images', on_delete=models.DO_NOTHING) image = models.ImageField("Uploaded image") And the offer model is: class Offer(models.Model): ARGENTINA = 'ARG' URUGUAY = 'URG' COUNTRIES = ( (ARGENTINA, 'Argentina'), (URUGUAY, 'Uruguay') ) name = models.CharField(max_length=200) description = models.TextField() created = models.DateField(auto_now_add=True) end_date = models.DateField() available = models.IntegerField() current = models.IntegerField(default=0) I appreciate any help! -
django-channels/celery: how to track progress of a list of tasks?
I'm "successfully" sending a message from the view to the client with the status of a group of tasks (not an actual celery group). The problem is: This really ignores whether all tasks are actually performed. I've attempted to add a callback (task.apply_async(link=)) but that didn't help either. The tasks themselves don't really take a lot of time, but I'd really like to be able to increment the counter when the task has actually been performed: if 'selected' in request.GET: selected_as_list = request.GET.getlist('selected') print(selected_as_list) searches = list(set([s.strip() for s in selected_as_list if s.strip()])) task_group = [refresh_func.s(str(user_profile.id), search, dont_auto_add=True) for search in searches] for i,task in enumerate(task_group): task.apply_async() Group(str(request.user.id)).send({"text": json.dumps({"tasks_completed": i+1, "task_id": "fb_import", "completed": True if i == len(task_group) -1 else False, "total": len(task_group)})}) So I moved the code out of the view, and into the same block that actually calls the operation to be done. Though it meant I was passing many parameters now, this solved the initial problem. But it presents another one: A task with an index of "1" can finish after a task with an index "3", and this obviously updates the counter incorrectly. What can be done to solve this? -
Deleting the original User model in Django
I am having a bit of difficulty understanding custom User models in Django. I get how we can make a custom User model by inheriting from AbstractBaseUser and it'll provide the core implementation of the User model, however, what I don't get is shouldn't the original auth_User table be deleted? When I make migrations, I notice that I get both an implementation of myapp_User and auth_user along with all the other auth tables. Why is this? I thought we are overriding auth_User with our own implementation. Why does auth_User exist? Is there a purpose for it to exist? -
request.user returns None Django social-auth-app-django
I am a newbie in django social auth. I am using social-auth-app-django to authenticate Microsoft Azure AD user. Authentication process works well and user object is created inside the database. But request.user is returing null inside view. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', # 'social.apps.django_app.default', ] AUTHENTICATION_BACKENDS = ( 'social.backends.azuread.AzureADOAuth2', ) #settings.py SOCIAL_AUTH_PIPELINE = { 'pipeline.new_users_handler' } View def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) context = { 'title':'Home Page', 'year':datetime.now().year, 'request': request, 'user': request.user, } context_instance = RequestContext(request,context) return render( request, 'index.html',context) -
web server of airflow i not running
m configuring email scheduler in Airflow in Django but its not working. error in terminal: airflow webserver [2017-12-29 10:52:17,614] {__init__.py:57} INFO - Using executor SequentialExecutor [2017-12-29 10:52:17,734] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/Grammar.txt [2017-12-29 10:52:17,765] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/PatternGrammar.txt ____________ _____________ ____ |__( )_________ __/__ /________ __ ____ /| |_ /__ ___/_ /_ __ /_ __ \_ | /| / / ___ ___ | / _ / _ __/ _ / / /_/ /_ |/ |/ / _/_/ |_/_/ /_/ /_/ /_/ \____/____/|__/ /usr/local/lib/python3.5/dist-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead. .format(x=modname), ExtDeprecationWarning [2017-12-29 10:52:18,354] [8169] {models.py:167} INFO - Filling up the DagBag from /home/hitesh/airflow/dags Running the Gunicorn Server with: Workers: 4 sync Host: 0.0.0.0:8080 Timeout: 120 Logfiles: - - ================================================================= Error: 'airflow.www.gunicorn_config' doesn't exist -
TypeError at /create
I am making basic CRUD in Django 1.11. While saving values to the DB I am getting this error, 'breed' is an invalid keyword argument for this function. Although there is a valid field in DB, even if I remove 'breed' I get the same error with 'name'. Environment: Request Method: POST Request URL: http://e0c0a02d057f4394aa9e52d4f67c7edb.vfs.cloud9.us-east-2.amazonaws.com/create Django Version: 1.11 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.dog_app'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ec2-user/environment/dogs/apps/dog_app/views.py" in create 14. dog = Dog(breed=request.POST['breed'],name=request.POST['name']) File "/usr/local/lib64/python2.7/site-packages/django/db/models/base.py" in __init__ 571. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) Exception Type: TypeError at /create Exception Value: 'breed' is an invalid keyword argument for this function Views.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from models import Dog from django.shortcuts import render,redirect # Create your views here. def index(request): dogs=Dog.objects.all() context={ 'dogs': dogs} return render(request, 'dog_app/index.html', context) def create(request): #print (request.POST['name'],request.POST['breed']) dog = Dog(breed=request.POST['breed'],name=request.POST['name']) dog.save() return redirect('/') index.html: <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <form … -
Concatenation of a field related to multiple rows of a record in query set in Django
I have to models with one to many relation with which I try to distinguish the type of my records. Let's say First model is dedicated to Book information and second model is some types such as A, B , C and there is an indirect relation from the Type table to Book, so each book could be A, B or C or any possible combination of Types. I want to use concatenation (or any other possible function in annotation to gather all the types in a field). Book.objects.all( ).annotate( Types = F('TableRelation__Type__Name') ).annotate( CombinedTypes = Concat('Types') ) which throws an error since only one argument is passed to be Concatenated. The result I am looking for is a CombinedTypes field filled with "ABAB" for any unique id of Book which shows that that record is an "AB" (or any other combination of A,B and C). How can I achieve this? -
django - post_save signal import different app
I have a post_save signal which is creating an object in a separate model in another app which references a model in the current app and it's giving an import error. Here's the signal from passwordfolders.models import PasswordFolder @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_personal_list(instance=None, created=False): if created: PasswordFolder.objects.create(name='Personal', description='Personal Folder', owner=instance, personal=True, parent='') here is the traceback: File "D:\Projects\enterpass\api\core\models.py", line 10, in <module> from passwordfolders.models import PasswordFolder File "D:\Projects\enterpass\api\passwordfolders\models.py", line 2, in <module> from core.models import AccessLevel, Owner, User The logic flow is it's a post_save on an BaseAbstractUser model in the core app which is calling PasswordFolder in the passwordfolders app which has an FK reference to AccessLevel in the core app. It's failing when trying to reference the import on AccessLevel which is clearly there so I'm not sure why it's failing. -
How to permanently have /xxx sub domain
I have a several applications running in a same cluster and want to set up subdomain for each application. To give you brief description of current set up, I have a Django app, Jira, and Gitlab running in a cluster. It would be nice I can redirect all requests to Django App via: xxxx.com(even localhost)/django-app Jira: xxx.com(+ localhost)/jira Also, I need to make sure any links within Django app should pick up this subdomain from the frontend so when if there is an <a href="category/page"> tag, it should always send users to xxx.com(localhost)/django-app/category/page I have been looking at Nginx reverse proxy but I cannot get subdomains to work like I want above. Please help! -
What is the difference between following in exclude query in django
can any one please help me with difference between this two exclude queries Consider I have Model TableA 1. TableA.objects.exclude(id__in=[1,3,4], is_active=False) 2. TableA.objects.exclude(Q(id__in=[1,3,4]) and Q(is_active=False)) I am asking this because 2nd query give me proper output but in 1st query is_active condition is not working. -
GoDaddy forward naked-domain for heroku app
Browsed around a few different answers here and can't seem to get this to work. There's a very similar question w/ the same problem as me I can't seem to locate again or I'd link. Essentially it is all of the following work on my heroku app (ssl is enabled). http://examle.com http://www.example.com/ https://www.example.com/ But, not https://example.com One of the suggestions in this question was to use wwwizzer to forward the naked domain. I tried this w/ no success using the following setup on GoDaddy and forwarding / A record linked below. My setup on GoDaddy wwwizzer forwarding attempt As an alternative will simply setting the forwarding to https://www.example.com/ work? Those are the only two things I can think of. -
DJango-tables2 how do I refresh/update the table on the webpage without hitting refresh button
I followed the DJango-tables2 official tutorial and was able to create data set in the terminal using: Person.objects.bulk_create([Person(name='Jieter'), Person(name='Bradley')]) However, the new data in the table on the website doesn't show up until I hit the refresh button. My question is how the table can be updated/refreshed without any human interaction on the webpage. What I'm trying to achieve is to update the table on the webpage without human interaction as soon as new data comes in. I'm relatively new to this, any suggestions would be greatly appreciated. Thank you. -
RuntimeError main thread is not in main loop Why sometimes does this error happen?
I got an error,RuntimeError at /accounts/draw_img main thread is not in main loop .I wrote codes, def draw_img(request): return render(request, 'draw_img.html', {'chart': _view_plot(request)}) def _view_plot(request): results = ImageAndUser.objects.filter(user=request.user).order_by('date') if len(results) == 0: plt.fill_between(x=[0,6], y1=0, y2=6, facecolor='yellow', alpha=0.2) jpg_image_buffer = io.BytesIO() plt.savefig(jpg_image_buffer) array = base64.b64encode(jpg_image_buffer.getvalue()) jpg_image_buffer.close() return array dates = [r.date for r in reversed(results)] xlist = [r.x for r in reversed(results)] ylist = [r.y for r in reversed(results)] if len(dates) > 5: dates = dates[-5:] xlist = xlist[-5:] ylist = ylist[-5:] image_data = [] for i in range(len(dates)): if dates[i] != None: image_data.append(dates[i]) image_data.append(xlist[i]) image_data.append(ylist[i]) plot_dates = [] plot_xlist = [] plot_ylist = [] for j in range(0, len(image_data), 3): plot_dates.append(image_data[j]) plot_xlist.append(image_data[j + 1]) plot_ylist.append(image_data[j + 2]) font = {'family': 'IPAexGothic'} matplotlib.rc('font', **font) for i in range(len(plot_xlist)): if i == 0: plt.plot(plot_xlist[i], plot_ylist[i], color="red", marker="x", linewidth=0, label=plot_dates[i]) elif i == 1: plt.plot(plot_xlist[i], plot_xlist[i], color="blue", marker="x", linewidth=0, label=plot_dates[i]) elif i == 2: plt.plot(plot_xlist[i], plot_xlist[i], color="green", marker="x", linewidth=0, label=plot_dates[i]) elif i == 3: plt.plot(plot_xlist[i], plot_xlist[i], color="yellow", marker="x", linewidth=0, label=plot_dates[i]) else: plt.plot(plot_xlist[i], plot_xlist[i], color="gray", marker="x", linewidth=0, label=plot_dates[i]) plt.legend() plt.xlim(0,100) plt.ylim(0, 100) plt.fill_between(x=[0, 95], y1=0, y2=80, facecolor='#CCFFFF') plt.fill_between(x=[0, 90], y1=0, y2=80, facecolor='#99FFFF') plt.fill_between(x=[0, 85], y1=0, y2=75, facecolor='#66FFFF') plt.fill_between(x=[0, 80], y1=0, y2=70, facecolor='#33FFFF') plt.fill_between(x=[0, 75], … -
Build an html table with session data in Django
I'm using sessions to persist data that hasn't been saved to the database for a multi-screen registration form. On the second screen in the form the user can add multiple rows of data (each row is an object that would be saved in the database) which are each saved to a django session variable using ajaj. The structure looks like this: request.session['data'] = [{'category': 'light jet', 'seats': 1, 'user': None, 'serial_number': '123abc', 'crew': 'one_crew', 'manuf_year': 2019, 'make_model': 'Pilatus/PC-12', 'tail_number': '456def', 'base_airport': 'Bozeman', 'ownership': 0.25, 'prof_pilot': False, 'op_cert': 'cert_part_91'}, {'category': 'light jet', 'seats': 1, 'user': None, 'serial_number': '123abc', 'crew': 'one_crew', 'manuf_year': 2019, 'make_model': 'Pilatus/PC-12', 'tail_number': '456def', 'base_airport': 'Bozeman', 'ownership': 0.5, 'prof_pilot': False, 'op_cert': 'cert_part_91'}] If the user fills out multiple rows and then chooses to navigate back to the first screen (to edit it or whatever) and then forward to the screen with the table using form buttons, I'm planning to rely on the session variable to repopulate the table. The Django endpoint looks like this: def applyAircraft(request): initial = {'aircraft': request.session.get('aircraft', None)} form = AircraftForm(request.POST or None, initial = initial) #del request.session['aircraft'] if request.method == 'POST': if form.is_valid(): if not 'aircraft' in request.session: request.session['aircraft'] = [] aircraft = request.session['aircraft'] aircraft.append(form.cleaned_data) … -
Django and django rest framework storing binary image and convert to image
I am using django to create API only and i am working together with my partner to integrate with his IOS phone. He told me that the image he sent will be in byte/binary format. And then i have to convert that binary data into image ? Also, the bigger the size of the image, the larger it is ? As i am not sure if i am storing in byte or byte array. This is the first time i heard of using about being able to store binary/byte and convert it to image. As i only know about using ImageField to store image. There are also very limited post regarding on storing image in byte and the conversion. Even the django documentation on BinaryField is very limited There is also a third party package which help the conversion but i have no idea on how to use it as there isnt much documentation on how to use it on the API. source: https://github.com/JeffreyATW/binaryimage I know this may be asking a lot but please help me Here is my code currently: models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, … -
djangorestframework JWT prefixing custom header "AUTHORIZATION" with "HTTP_AUTHORIZATION" automatically
I need help with this. I'm using django rest framework api_view() with JWT Token Authentication. When I try to send "Authorization" header from my android app, it automatically gets converted to "HTTP_AUTHORIZATION". I also tried it with a variety of other custom headers, but still got the same results. This is the result I get when I print request.META {'HTTP_AUTHORIZATION': 'JWT daf2f1f0aef9a3db70d5c3443445a92fce830f0e', 'RUN_MAIN': 'true', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/ashish', 'QT4_IM_MODULE': '', 'SERVER_SOFTWARE': 'WSGIServer/0.1 Python/2.7.12', 'UPSTART_EVENTS': 'started xsession', 'SCRIPT_NAME': u'', 'XDG_SESSION_TYPE': 'x11', 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': '218', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HOME': '/home/ashish', 'DISPLAY': ':0.0', 'LANG': 'en_IN', 'VIRTUAL_ENV': '/home/ashish/Lore/venv', 'SHELL': '/bin/bash', 'PATH_INFO': u'/api/users/details/bio/update/', 'XDG_DATA_DIRS': '/usr/share/xubuntu:/usr/share/xfce4:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop:/usr/share', 'QT_LINUX_ACCESSIBILITY_ALWAYS_ON': '1', 'MANDATORY_PATH': '/usr/share/gconf/xubuntu.mandatory.path', 'CLUTTER_IM_MODULE': '', 'UPSTART_INSTANCE': '', 'JOB': 'dbus', 'SESSION': 'xubuntu', 'SERVER_PORT': '8000', 'XMODIFIERS': '', 'JAVA_HOME': '/usr/lib/jvm/java-8-oracle', 'GTK2_MODULES': 'overlay-scrollbar', 'XDG_RUNTIME_DIR': '/run/user/1000', 'HTTP_HEADERLINE4': 'headerLine4Val', 'CONTENT_TYPE': 'application/json; charset=UTF-8', 'J2SDKDIR': '/usr/lib/jvm/java-8-oracle', 'HTTP_CONNECTION': 'Keep-Alive', 'HTTP_HOST': '192.168.1.106:8000', 'wsgi.version': (1, 0), 'XDG_CURRENT_DESKTOP': 'XFCE', 'XDG_SESSION_ID': 'c2', 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-do9HpUjbpz', 'GTK_MODULES': 'gail:atk-bridge', 'DESKTOP_SESSION': 'xubuntu', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'GNOME_KEYRING_PID': '', 'wsgi.run_once': False, 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x7fce73cf81e0>, 'wsgi.multiprocess': False, 'INSTANCE': '', 'XDG_MENU_PREFIX': 'xfce-', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:', 'XDG_SEAT': 'seat0', 'GLADE_PIXMAP_PATH': ':', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'QUERY_STRING': '', 'QT_IM_MODULE': '', 'LOGNAME': 'ashish', 'USER': 'ashish', 'GNOME_KEYRING_CONTROL': '', 'XDG_VTNR': '7', 'PATH': '/home/ashish/Lore/venv/bin:/home/ashish/bin:/home/ashish/TMI/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin', 'PS1': '(venv) \\[\\e]0;\\u@\\h: \\w\\a\\]${debian_chroot:+($debian_chroot)}\\u@\\h:\\w\\$ ', 'SSH_AGENT_PID': '1538', 'TERM': 'xterm', 'HTTP_USER_AGENT': … -
Django bulk create objects from QuerySet
If I have a QuerySet created from the following command: data = ModelA.objects.values('date').annotate(total=Sum('amount'), average=Avg('amount')) # <QuerySet [{'date': datetime.datetime(2016, 7, 15, 0, 0, tzinfo=<UTC>), 'total': 19982.0, 'average': 333.03333333333336}, {'date': datetime.datetime(2016, 7, 15, 0, 30, tzinfo=<UTC>), 'total': 18389.0, 'average': 306.48333333333335}]> Is it possible to use data to create ModelBobjects from each hash inside the QuerySet? I realize I could iterate and unpack the QuerySet and do it like so: for q in data: ModelB.objects.create(date=q['date'], total=q['total'], average=q['average']) But is there a more elegant way? It seems redundant to iterate and create when they're almost in the bulk_create format. -
Staticfiles don't load in admin on production server
As the title says, my staticfiles wont load in admin on my production server (though works fine locally). I'm using s3boto3 for staticfiles_storage. However, i've recently changed aws buckets/accounts. in my admin templates, {% url static 'static/file.js' %} still points to the old bucket/account. (e.g. https://myoldbucket.s3.amazonaws.com/admin/css/base.css?Signature=sdmlfnsdkfl%3D&Expires=1514514737&AWSAccessKeyId=AKdsfjsodifnsdiofs ) I've run collectstatic and i still have no current staticfiles. does anyone know what could be wrong? Here is my related code in settings.py: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = key AWS_SECRET_ACCESS_KEY = key AWS_STORAGE_BUCKET_NAME = 'mynewbucket' AWS_HEADERS = { 'Expires': 'Thu, 15 Apr 2010 20:00:00 GMT', 'Cache-Control': 'max-age=86400', } STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles/'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static')` -
Django modal content
I have weard problem with bootstrap 4 modals and django. I need to display the modal to edit the address and return to the previous page after editing. For this purpose, i pass 2 parameters in the URL address. when both parameters are given instead of modal to edit the address, the entire page is loaded this is my view class AddresssUpdateView(generic.UpdateView): model = Address template_name = 'Order_app/address_form.html' form_class = AddressForm def get_success_url(self): return reverse_lazy('Order_app:detail', kwargs={'pk': self.object.pk}) this is my modal content (address_form.html) <div class="modal-dialog modal-lg"> <div class="modal-content"> {% if adres %} <form role="form" action="{% url 'Order_app:edit_address' pk address_id %}" method="POST"> <div class="modal-header"> <h3>Edit</h3> </div> {% endif %} <div class="modal-body"> {% csrf_token %} <div class="panel panel-default"> <div class="panel-body"> {{ form.as_p }} </div> </div> </div> <div class="modal-footer"> <div class="col-lg-12 text-right"> <input type="submit" class="btn btn-primary" name="submit" value="Save"> <button type="button" class="btn btn-default" onclick="return hide_modal()"> exit </button> </div> </div> </form> </div> this is my urls.py file url(r'^$', views.ZleceniaListView.as_view(), name='lista_zlecen'), url(r'^(?P<pk>[0-9]+)', views.OrderDetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/edit/(?P<adres_id>[0-9]+)/$', views.AddressUpdateView.as_view(), name='edit_address'), my home page template fragment <button type="button" class="btn btn-warning btn-sm" onclick="return abrir_modal('{% url 'Order_app:edit_address' order.pk address.pk %}')" data-toggle="modal" data-target="#Modal"> edit <div class="modal" id="Modal" tabindex="-1" role="dialog"></div> <script> function abrir_modal(url) { $('#Modal').load(url, function () { $(this).modal('show'); }); return false; } function … -
Getting an error 'BadRequestException' object has no attribute 'get'
I am a newbie in python and django. Trying to setup django to work with Dropbox but keep getting error "'BadRequestException' object has no attribute 'get'". Here is my code. def get_dropbox_auth_flow(web_app_session): APP_KEY= '****' APP_SECRET = '****' redirect_uri = "http://localhost:8000/dropbox" return DropboxOAuth2Flow(APP_KEY, APP_SECRET, redirect_uri, web_app_session, "dropbox-auth-csrf-token") # URL handler for /dropbox-auth-start def dropbox_auth_start(request): authorize_url = get_dropbox_auth_flow(request.session).start() return HttpResponseRedirect(authorize_url) # URL handler for /dropbox-auth-finish def dropbox_auth_finish(request): try: access_token, user_id, url_state = get_dropbox_auth_flow(request.session).finish(request.GET) # oauth_result = get_dropbox_auth_flow(request.session).finish(request.query_params) except oauth.BadRequestException as e: return e except oauth.BadStateException as e: # Start the auth flow again. return HttpResponseRedirect("http://localhost:8000/dropbox_auth_start") except oauth.CsrfException as e: return HttpResponseForbidden() except oauth.NotApprovedException as e: raise e except oauth.ProviderException as e: raise e I am following the documentation here -
Django Rest Framework Token User with MongoEngine User
i try to get token using Django Rest Framework but doesn't accept my user ValueError: Cannot assign "<User: gaurav>": "Token.user" must be a "User" instance. models class User(Document): first_name = StringField(max_length=20, required=True) last_name = StringField(max_length=20, required=True) email = StringField(max_length=20, required=True) password = StringField(max_length=200, required=True) def set_password(self,password): self.password = make_password(password) class Meta: db_table = 'User' view token = Token.objects.create(user=user) Please let me know how I can get this to work.