Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update existing user's profile in python django connected with mongodb database
I have written this function to update existing user's profile but it is creating a new user in database instead of updating existing user.Would you please help tofigure out the problem.Thanks def update_Profile(request): if request.method == 'POST': address =request.POST['address'] country=request.POST['country'] city=request.POST['city'] zipcode =request.POST['zipcode'] dob=request.POST['dob'] gender =request.POST['gender'] weight =request.POST['weight'] height =request.POST['height'] if(request.session.has_key('user_id')): userid = request.session['user_id'] if User_profile.objects.filter(email = userid).exists(): user = User_profile.objects.create(address = address ,city=city,country=country,zipcode=zipcode,dob=dob,gender=gender,weight=weight,height=height) user.save() return render(request,'app/userProfile.html') else: print ('login first') else: return render(request,'app/login.html') else: return render(request,'app/login.html') -
Django Templates - How to use same block name inside other block?
Hi django lover's actually i am creating a page dynamic page for logged in and logged out users. I want if the user is authenticated then i want show something different instead of my base template. Below is my code and you will surely understand after reading it. That's why i am trying this. Anyone has any idea to do this task in django. Your help will be really appreciable. {% extends 'gymwebapp/basic.html' %} {% if not user.is_authenticated %} {% block d-login %} <div id="dummy-right"> <a href="{% url 'register' %}"><button class="btn">Sign Up</button></a> <a href="{% url 'login' %}"><button class="btn">Login</button></a> </div> {% endblock %} {% block login %} <div class="right"> <a href="{% url 'register' %}"><button class="btn">Sign Up</button></a> <a href="{% url 'login' %}"><button class="btn">Login</button></a> </div> {% endblock %} {% block body %} <section class="form-area"> <div class="form-container"> <div class="form-heading"> <h3>Login</h3> </div> <form action="login" method="POST"> {% csrf_token %} <div class="form"> <input type="email" placeholder="Email" id="email" name="email" maxlength="30" required></br> <input type="password" placeholder="Password" id="pass" name="pass" maxlength="12" required></br> <button class="btn" id="fbtn" type="submit">Submit</button> </div> </form> </div> </section> {% endblock %} {% endif %} {% if user.is_authenticated %} {% block d-login %} <div id="dummy-right"> <a href="{% url 'register' %}"><button class="btn">{{user.first_name}}</button></a> <a href="{% url 'logout' %}"><button class="btn">Logout</button></a> </div> {% endblock %} {% … -
User model not authenticating, but superuser does? in Django
I have made a superuser through createsuperuser from the command line. I have created the following user class. class Teacher(AbstractUser): """ User model """ first_name = models.CharField(max_length=64) subject = models.CharField(max_length=64) USERNAME_FIELD = 'username' I then create a user through the admin screen; but when I want to authenticate using the following code; it user always returns none. except when I use the superuser account. def loginview(request): """Creates Login Screen""" if request.method == "POST": username = request.POST['username'] password = request.POST['password'] # Authenticate User via Django login system. user = authenticate(request, username=username, password=password) print(user) if user is not None: # Confirm credentials are correct. auth_login(request, user) return render(request, "score_board/points.html") else: return render(request, "score_board/loginview.html", {"message": "Wrong username/password!"}) else: return render(request, "score_board/loginview.html") -
geoDjango changing longitude automatically
i'm making a location base web application and for this i'm using geoDjango and postgres . the problem is whenever i try to store some location(latitude/longitude) around dhaka ,it automatically change the longitude. after doing some debugging i found that, whenever longitude cross 90.00, geoDjango save longitude as 89.something . My model: from django.db import models from django.contrib.gis.db import models as locationModels class Advertise(models.Model): house_name = models.CharField(max_length=100, null=True) geoLocation = locationModels.PointField(geography=True, null=True) Example : from django.contrib.gis.geos import Point lat, lng = 23.724609, 88.882694 pnt = Point(lat, lng) add = models.Advertise(geoLocation=pnt,house_name='test1') add.save() add = models.Advertise.objects.filter(house_name='test1') Output of add[0].geoLocation.y is 88.882694 if i change the value of lat,lng to 23.777976, 90.010106, the Output of add[0].geoLocation.y became 89.989894, but it should be 90.010106 can anyone tell me where i'm doing wrong ? -
new user is getting created
this is my models.py class Profile(models.Model): idno=models.AutoField(primary_key=True) name=models.CharField(max_length=30) email=models.CharField(max_length=40) choices = ( ('C', 'C'), ('C++', 'C++'), ('Java', 'Java'), ('Python', 'Python'), ) intrest = models.CharField(max_length=6, choices=choices) marks=models.IntegerField(default=0) this is my views where i am asking the user to choose their intrest def timeline(request): intrest=Profile.objects.all()[0].intrest if intrest =='': if request.method=="POST": choice=request.POST['choice'] print(choice) profile=Profile(intrest=choice) profile.save() this code is creating a new profile with blank name and email how can i save this current information to the same user? -
How to customize Django loaddata so can perform logic before loading the model data
I backed up DB with manage.py dumpdata, I now have a file I wish to use with manage.py loaddata, but I wish to perform some customised logic to the data before loading it. This is because I am migrating the data to a different structure. How does one get the data into python objects so I can perform my customised logic? -
How add image to site on Django?
I need to add one picture to the article. How to do it? Code under. Thanks #models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now= True) def __str__(self): return self.title -
How to post posts from website (Django Server) to social media accounts (Twitter, LinkedIn and Instagram )
Say someone posts something on our page using the Django admin console, I want to add an option there to post it also on Twitter, LinkedIn and Instagram, So with one click it also goes there. Is there any way to do it? -
Django 3.1 No reverse match at / not a registered namespace error
I'm following an old guide about online store design in django and i faced a weird problem using reverse function inside one of my apps model file. This is the general structure of my project: shop(main project) |-myshop(preview of general website pages) |-utility(some utilities and context processors) |-catalog(catalog related modules of the website) |-cart(shopping cart module) |-manage.py |-db.sqlite3 These are my error related files of project: main urls.py from django.contrib import admin from django.urls import path, include from myshop import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view), path('signup/', views.signup_view, name="signup"), path('sent/', views.activation_sent_view, name="activation_sent"), path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate'), path('signin/', views.signin_view, name="signin"), path('logout/', views.logout_view, name="logout"), path('catalog/', include(('catalog.urls', 'catalog'), namespace='catalog')), ] catalog urls.py: from django.urls import path, re_path from catalog import views app_name = 'catalog' urlpatterns = [ re_path(r'^$', views.home_view, name='catalog_home'), re_path(r'^category/(?P<category_slug>[-\w]+)/$', views.show_category, name='catalog_category'), re_path(r'^product/(?P<product_slug>[-\w]+)/$', views.show_product, name='catalog_product'), ] catalog models.py: from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255,help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text='Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at … -
Size Restriction of Uploaded Images Django
I want to limit the size of image(Base64) saved to the database. For example, I want the maximum size of image to be 100KB, how can I do that? I'm using Django. -
How to push update of packages/dependencies of your live django website
I have created a django website which now I am looking to deploy through DigitalOcean, I have not uploaded it yet because I want to get a clear picture before actually starting. My questions are, How to I update the packages required for my website once I have deployed my website? Eg: I am using CKEditor 6. In future, when CKEditor 7 arrives how do I update the package so that my website uses the latest CKEditor without losing any data. DigitalOcean deployment works with and without git right? So should I skip git, because I really do not care about versioning my website. Simple update through FTP apps(WinSCP, Filezilla) will work for me. -
How to convert mysql query to django orm
I'm trying to execute this query, it's working fine in MySQL workbench, but It's not working in python shell. And I have to export that result in an Excel sheet. -
How to extract particular record from QuerySet using Django?
let say : I have 'views.py' def login(request): if request.method == 'POST': # here 'Employees' is the model class having some fields as : name, email, pass, mobile etc. emp = Employees.objects.filter(email=request.POST['email'], password=request.POST['password']) if emp: # Now here I'm getting confused how to get particular record like id, email, pass from emp var to store in session. I might be wrong cuz so please ignore my mistakes and give me best way to do that request.session['id'] = emp[0].id ... some code ... return redirect('/homepage') else: return render(request, 'forms/login.html') else: ... some code ... At the last I'm saying that this is only the hint what I want to get from queryset. Please don't ask why I'm doing that stuff. Only what I found problem so sharing with all Thanks -
Restrict Azure Application access to a specific folder in OneDrive
We have a requirement to upload to and read files from a single folder in onedrive for Business through a Django app. We are using Microsoft Graph API with application permission. While the Azure provides Files.ReadWrite.All permission, the application can also potentially access all files and folders, as provided in graph permissions reference: Allows the app to read all files in all site collections without a signed in user. (ref: https://docs.microsoft.com/en-us/graph/permissions-reference) Is there a way to use Graph API's Application Files.ReadWrite.All Permission while restricting the application's access to a single folder in OneDrive? Thanks for the help. -
How to Solve Django Error Message : TemplateDoesNotExist at
I am trying to do a project for a blog by django 3.1.2 , but unable to link the templates.I tried fixing it with **'DIRS': [os.path.join(BASE_DIR, 'templates'),]** I cannot find the logic miss. The template does exist and when I review the code, the query is performing correctly. I'm at a loss. my setting TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] my blog images my blog urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('posts.urls')), path('admin/', admin.site.urls), ] my posts urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] my posts views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return render(request,'posts/index.html') posts images -
Python Django project handling .env and SECRET_KEY on GitHub Actions + Kubernetes Deployment
We have a web service written in Django that is stored on GitHub. We used GitHub Actions to create a workflow that builds a Docker image and pushes it to Azure Container Registry. Then the workflow triggers a Terraform file that in turn provisions a Kubernetes Cluster and using a deployment.yaml it deploys the web service app on Kubernetes cluster. This whole process works fine but when pods are up they get terminated CrashLoopBackOff The terminated pod's log can be found in the ix output below http://ix.io/2BCx I know the log clearly shows that its missing some .env file and environment variables such as SECRET_KEY that seems to require these BEFORE the image build, we are unaware where and at what stage to provide these information to the image? Whether in the GH Actions workflow itself, in Dockerfile, a bash script to inject somewhere. Any guidance is highly appreciated. Thanks. -
Socket Communication between python and Django || HTTP - POST
I was trying to establish a communication between python and Django backend. I want to send an image from python using socket and HTTP post The Django View on successful post request will will save the image and respond back with an audio file . what I tried is client side # reading the file f = open(file_name, 'rb') file_content = f.read() f.close() # HTTP-POST Method req_data = '--{b}\r\n'.format(b=boundary) req_data += 'Content-Disposition: form-data; name="file"; filename={fn}\r\n'.format(fn=file_name) req_data += 'Content-Type: {ft}\r\n'.format(ft=file_type) req_data += '\r\n' req_data += '{file_content}\r\n'.format(file_content=file_content) req_data += '--{b}--'.format(b=boundary) # first method I tried req = 'POST /dataHandle/imagePort/ HTTP/1.1\r\n' req += 'Host: {host}\r\n'.format(host=host) req += 'Content-Type: image/jpeg; boundary={b}\r\n'.format(b=boundary) req += 'Content-Length: {l}\r\n'.format(l=len(req_data)) req += 'Connection: close\r\n' req += '\r\n' req += '{data}'.format(data=req_data) # second method I tried req = 'POST /dataHandle/imagePort/ HTTP/1.1\r\n' req += 'Host: {host}\r\n'.format(host=host) req += 'Content-Type: multipart/form-data; boundary={b}\r\n'.format(b=boundary) req += 'Content-Length: {l}\r\n'.format(l=len(req_data)) req += 'Connection: close\r\n' req += '\r\n' req += '{data}'.format(data=req_data) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) byt = req.encode() data_len = s.send(byt) # Response Receive length = 1024 while True: f = open('response.mp3','wb') print ("Receiving...") l = s.recv(length) while (l): f.write(l) l = s.recv(length) f.close() print ("Done Receiving") s.send(' ') s.close() break print("outside") print("done") s.close() Django … -
How to hide pagination with Javascript
I am trying to hide my bootstrap pagination bar if the search results in less than one page of items. this is my home.html pagination: <div class="pagination" id="paginationField"> <nav aria-label="..."> <ul class="pagination", id="pagination"> <li class="page-item {% if not prev_page_url %}disabled {% endif %} "> <a class="page-link" href="{{ prev_page_url }}" tabindex="-1">Previous</a> </li> {% for n in page.paginator.page_range %} {% if page.number == n %} <li class="page-item active"> <a class="page-link" href="?page={{ n }}">{{ n }} <span class="sr-only">(current)</span></a> </li> {% elif n > page.number|add:-3 and n < page.number|add:3 %} <li class="page-item"> <a class="page-link" href="?page={{ n }}">{{ n }}</a> </li> {% endif %} {% endfor %} <li class="page-item {% if not next_page_url %}disabled {% endif %} "> <a class="page-link" href="{{ next_page_url }}">Next</a> </li> </ul> </nav> </div> Here is my js file: function showHidePagination() { if(document.getElementById('paginationField').length > 15) { document.getElementById('pagination').style.display='none'; } else { document.getElementById('pagination').style.display='block'; } } -
Receiving 'none' id value from post request input parameter in Django form
I am passing an id primary key in from a Django model called Project to projects.html where is says {{p.id}}. When I submit the form I get a 'none' value where it says print(id) even though the id is showing up properly in the browser. it's when I post the form it won't carry the value into the view. projects.html <form action="" method="POST">{% csrf_token %} <div class="form-group"> <input type="submit" value="View >>" class="btn btn-primary" /> <input type="hidden" id="{{p.id}}" class="btn btn-primary" /> <div class="submitting"></div> </div> </form> views.py def projects(request): if request.method == 'POST': id = request.POST.get('id') print(id) project=Project.objects.get(id=id) context = { 'p' : project, } return render(request, 'residential/project_info.html', context=context) p=Project.objects.all() context = { 'projects' : p, } return render(request, 'residential/projects.html', context=context) -
celery worker only imports tasks when not detached
I'm trying to get my django app to submit tasks to a celery worker and it's succeeding when the worker is run attached. As soon as I add the --detach the tasks are failing to be registered. [2020-10-26 04:09:33,159: ERROR/MainProcess] Received unregistered task of type 'devapp.tasks.create_random_files'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[20, "blah", 5120], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (93b) Traceback (most recent call last): File "/pysite/project/venv/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received strategy = strategies[type_] KeyError: 'devapp.tasks.create_random_files' In my tasks.py I have import os import string import subprocess from celery import shared_task, task @shared_task(name='devapp.tasks.create_random_files') def create_random_files(total,filename,size): for i in range(int(total)): filenum = str(i).zfill(5) rnd_filename = '/brdis/{}-{}'.format(filenum,filename) with open(rnd_filename, 'wb') as f: f.write(os.urandom(size)) f.close return '{} random files created'.format(total) and in my views.py I have from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages from django.views.generic import TemplateView from django.views.generic.list import ListView from django.views.generic.edit import FormView from django.shortcuts import redirect from .forms import CreateRandomFilesForm, GetFileListForm, ClamScanFileForm from .tasks import create_random_files, clamscanfile class ClamScanFileView(FormView): … -
Cannot resolve NoReverseMatch at / error in Django
I am trying to make an auction website (for a project). And we need to have an option to add each product to the "watchlist". However, I keep getting error when clicking on "watchlist" button. This is in Python using Django. This is the exact error I'm getting: NoReverseMatch at /viewlisting/3/addwatchlist Reverse for 'addwatchlist' with arguments '('',)' not found. 1 pattern(s) tried: ['viewlisting/(?P<listing_id>[0-9]+)/addwatchlist$'] Here is a summary of my code: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create_listing", views.create_listing, name="create_listing"), path("viewlisting/<int:listing_id>", views.viewlisting, name="viewlisting"), path("viewlisting/<int:listing_id>/addwatchlist", views.addwatchlist, name="addwatchlist") ] views.py: def viewlisting(request,listing_id): productname= listings.objects.get(id=listing_id) name= productname.name description = productname.description image = productname.image price= productname.price seller = productname.seller category = productname.category date = productname.date productid= productname.id return render(request, "auctions/viewlisting.html",{ "name":name, "description":description, "image":image, "price":price, "seller":seller, "category":category, "date":date, "id":productid }) def addwatchlist(request,listing_id): if request.method == "POST": item_exists= watchlist.objects.filter( id = listing_id, user= request.user.username ) if item_exists: show_watchlist = watchlist.objects.all() exist_alert= "This item already exists in your watchlist!" return render(request,"auctions/viewlisting.html",{ "alert":exist_alert, "show_watchlist":show_watchlist }) else: new_item = watchlist() new_item.user = request.user.username new_item.listing = listings.objects.get(id=listing_id).name new_item.save() success_alert = "This item was added to your watchlist!" show_watchlist = watchlist.objects.all() return render(request,"auctions/viewlisting.html",{ "alert": … -
RelatedObjectDoesNotExist -- relationship error between models?
I am currently creating an application called "Hospital Management System," where patients can appoint doctors (through a system that I have not implemented yet). Currently, I am encountering an error regarding "RelatedObjectDoesNotExist." Here is the full error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/hms_app/doctor_register/ Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hms_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 (most recent call last): File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\acer\Desktop\My_Django_Stuff\hospital_management_system\hms_app\views.py", line 60, in doctor_register doctor.doctor_profile.doctor_first_name = doctor_profile_form.cleaned_data.get('doctor_first_name') File "C:\Users\acer\anaconda3\envs\myDjangoEnv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 421, in __get__ raise self.RelatedObjectDoesNotExist( Exception Type: RelatedObjectDoesNotExist at /hms_app/doctor_register/ Exception Value: User has no doctor_profile. This error appears every time I try to register a doctor, but this does not happen when I try to register a patient I am suspecting that this error has to do with my models and how each of them relate. Right now, I am trying to implement multiple roles using Django's user model -- specifically, the roles are doctor and patient. Here is what I have coded so far: models.py from django.contrib.auth.models import AbstractUser from django.db import models … -
Nginx in docker container not serving static files
I recently took over someone's project and I am supposed to deploy it to a new server. There is an Nginx server serving the static files of a Django app. I keep getting a 404-not-found error from Nginx. Here is the Nginx.conf file: server { listen 80; server_name localhost; return 301 https://$host$request_uri; } server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name localhost; charset utf-8; client_max_body_size 150M; include /config/nginx/proxy-confs/*.subfolder.conf; include /config/nginx/ssl.conf; location /static { sendfile on; sendfile_max_chunk 25m; alias /static; } location /media/user { sendfile on; sendfile_max_chunk 50m; internal; alias /media/user; } location /admin/login { return 301 " /login"; } location /media/protected { if ($http_user_agent ~* (360Spider|80legs.com|Abonti|AcoonBot|Acunetix|adbeat_bot|AddThis.com|adidxbot|ADmantX|AhrefsBot|AngloINFO|Antelope|Applebot|BaiduSpider|BeetleBot|billigerbot|binlar|bitlybot|BlackWidow|BLP_bbot|BoardReader|Bolt\ 0|BOT\ for\ JCE|Bot\ mailto\:craftbot@yahoo\.com|casper|CazoodleBot|CCBot|checkprivacy|ChinaClaw|chromeframe|Clerkbot|Cliqzbot|clshttp|CommonCrawler|comodo|CPython|crawler4j|Crawlera|CRAZYWEBCRAWLER|Curious|Curl|Custo|CWS_proxy|Default\ Browser\ 0|diavol|DigExt|Digincore|DIIbot|discobot|DISCo|DoCoMo|DotBot|Download\ Demon|DTS.Agent|EasouSpider|eCatch|ecxi|EirGrabber|Elmer|EmailCollector|EmailSiphon|EmailWolf|Exabot|ExaleadCloudView|ExpertSearchSpider|ExpertSearch|Express\ WebPictures|ExtractorPro|extract|EyeNetIE|Ezooms|F2S|FastSeek|feedfinder|FeedlyBot|FHscan|finbot|Flamingo_SearchEngine|FlappyBot|FlashGet|flicky|Flipboard|g00g1e|Genieo|genieo|GetRight|GetWeb\!|GigablastOpenSource|GozaikBot|Go\!Zilla|Go\-Ahead\-Got\-It|GrabNet|grab|Grafula|GrapeshotCrawler|GTB5|GT\:\:WWW|Guzzle|harvest|heritrix|HMView|HomePageBot|HTTP\:\:Lite|HTTrack|HubSpot|ia_archiver|icarus6|IDBot|id\-search|IlseBot|Image\ Stripper|Image\ Sucker|Indigonet|Indy\ Library|integromedb|InterGET|InternetSeer\.com|Internet\ Ninja|IRLbot|ISC\ Systems\ iRc\ Search\ 2\.1|jakarta|Java|JetCar|JobdiggerSpider|JOC\ Web\ Spider|Jooblebot|kanagawa|KINGSpider|kmccrew|larbin|LeechFTP|libwww|Lingewoud|LinkChecker|linkdexbot|LinksCrawler|LinksManager\.com_bot|linkwalker|LinqiaRSSBot|LivelapBot|ltx71|LubbersBot|lwp\-trivial|Mail.RU_Bot|masscan|Mass\ Downloader|maverick|Maxthon$|Mediatoolkitbot|MegaIndex|MegaIndex|megaindex|MFC_Tear_Sample|Microsoft\ URL\ Control|microsoft\.url|MIDown\ tool|miner|Missigua\ Locator|Mister\ PiX|mj12bot|Mozilla.*Indy|Mozilla.*NEWT|MSFrontPage|msnbot|Navroad|NearSite|NetAnts|netEstate|NetSpider|NetZIP|Net\ Vampire|NextGenSearchBot|nutch|Octopus|Offline\ Explorer|Offline\ Navigator|OpenindexSpider|OpenWebSpider|OrangeBot|Owlin|PageGrabber|PagesInventory|panopta|panscient\.com|Papa\ Foto|pavuk|pcBrowser|PECL\:\:HTTP|PeoplePal|Photon|PHPCrawl|planetwork|PleaseCrawl|PNAMAIN.EXE|PodcastPartyBot|prijsbest|proximic|psbot|purebot|pycurl|QuerySeekerSpider|R6_CommentReader|R6_FeedFetcher|RealDownload|ReGet|Riddler|Rippers\ 0|rogerbot|RSSingBot|rv\:1.9.1|RyzeCrawler|SafeSearch|SBIder|Scrapy|Scrapy|Screaming|SeaMonkey$|search.goo.ne.jp|SearchmetricsBot|search_robot|SemrushBot|Semrush|SentiBot|SEOkicks|SeznamBot|ShowyouBot|SightupBot|SISTRIX|sitecheck\.internetseer\.com|siteexplorer.info|SiteSnagger|skygrid|Slackbot|Slurp|SmartDownload|Snoopy|Sogou|Sosospider|spaumbot|Steeler|sucker|SuperBot|Superfeedr|SuperHTTP|SurdotlyBot|Surfbot|tAkeOut|Teleport\ Pro|TinEye-bot|TinEye|Toata\ dragostea\ mea\ pentru\ diavola|Toplistbot|trendictionbot|TurnitinBot|turnit|Twitterbot|URI\:\:Fetch|urllib|Vagabondo|Vagabondo|vikspider|VoidEYE|VoilaBot|WBSearchBot|webalta|WebAuto|WebBandit|WebCollage|WebCopier|WebFetch|WebGo\ IS|WebLeacher|WebReaper|WebSauger|Website\ eXtractor|Website\ Quester|WebStripper|WebWhacker|WebZIP|Web\ Image\ Collector|Web\ Sucker|Wells\ Search\ II|WEP\ Search|WeSEE|Wget|Widow|WinInet|woobot|woopingbot|worldwebheritage.org|Wotbox|WPScan|WWWOFFLE|WWW\-Mechanize|Xaldon\ WebSpider|XoviBot|yacybot|Yahoo|YandexBot|Yandex|YisouSpider|zermelo|Zeus|zh-CN|ZmEu|ZumBot|ZyBorg) ) { return 410; } sendfile on; sendfile_max_chunk 50m; internal; alias /media/protected; } location /media { sendfile on; sendfile_max_chunk 25m; alias /media; } location /media/images/company { alias /media/images/company; } location / { proxy_pass http://web:8000; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; … -
How can I upload a file with JSON data to django rest api?
I am using angular as the front-end scope and Django Rest as the back-end. Now I am facing a situation where I want to create a Model. The structure of a model is really complex in nature, I could use some other simple way outs but using JSON and passing the files with that can really simplify the logic and also make process really efficient. I am have been trying a lot but none of the ways seem to work. Can some someone help me with a standard way or tell me even it is possible or not. This the structure of my Typescript which I want to upload. import { v4 as uuid4 } from 'uuid'; export interface CompleteReport{ title: string; description: string; author: string; article_upload_images: Array<uuid4>, presentation_upload_images: Array<uuid4>, report_article: ReportArticle, report_image: ReportImage, report_podcast: ReportPodcast, report_presentation: ReportPresentation, report_video: ReportVideo, } export interface ReportArticle{ file: File; body: string; } export interface ReportPodcast{ file: any; } export interface ReportVideo{ file: Array<File>; } export interface ReportImage{ file: File; body: string; } export interface ReportPresentation{ body: string; } export interface UploadImage{ file: File; } -
The ignore_bad_filters parameter of the build_filters function
I have a TaskTemplateResource like this: class TaskTemplateResource(GCloudModelResource): pipeline_template = fields.ForeignKey( PipelineTemplateResource, 'pipeline_template') class Meta: queryset = TaskTemplate.objects.filter(pipeline_template__isnull=False, is_deleted=False) resource_name = 'template' authorization = TaskTemplateAuthorization() always_return_data = True serializer = AppSerializer() filtering = { "id": ALL, "business": ALL_WITH_RELATIONS, "name": ALL, "category": ALL, "pipeline_template": ALL_WITH_RELATIONS, "subprocess_has_update": ALL, "has_subprocess": ['exact'] } def build_filters(self, filters=None, **kwargs): if filters is None: filters = {} orm_filters = super(TaskTemplateResource, self).build_filters(filters, **kwargs) Super class GCloudModelResource: class GCloudModelResource(ModelResource): def build_filters(self, filters=None, ignore_bad_filters=False): if filters is None: filters = {} print filters orm_filters = super(GCloudModelResource, self).build_filters( filters, ignore_bad_filters ) print orm_filters class PipelineTemplateResource: class PipelineTemplateResource(GCloudModelResource): class Meta: filtering = { 'subprocess_has_update': ALL, 'has_subprocess': ['exact'] } The question is filter like this: <QueryDict: {u'has_subprocess': [u'true']}> but orm_filters like this: {'pipeline_template__exact': True} Why?The has_subprocess is a filed of PipelineTemplateResource. When the filter is: <QueryDict: {u'pipeline_template__has_subprocess': [u'true']}> the orm_filters will be: {'pipeline_template__has_subprocess__exact': True}