Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload file to Django with Javascript
I have simple fetch function and I want to upload an base64 image. The function is as follows: function upload_to_server(canvasData){ console.log(canvasData); // that is data:image/png;base64,iVBORw0KGgoAAAANSUh....... return fetch(api_url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: {photo: canvasData} }).then(function (value) { if(value.ok){ return value.json().then(function (response) { debugger; }) } }).catch(function (reason) { debugger; }) } And I have simple django view: def upload_image(request): print(request.POST) pdb.set_trace() It goes successful to that view when function upload_to_server gets called, but request.POST is empty. It shouldn't be empty, it should have key photo with that base64 value. Any idea what I do wrong? -
Is django a restful api?
I am confused. Some say it is a Restful API and some say it is not. How do we define a RESTful API? GET,PUT,POST and DELETE commands ? Can I call any web application which is built using django Web framework a Restful API? -
pycharm does not recognise rest framework
I want to use rest_framework in my tutorial django project. I follow instruction steps and add 'rest_framework' in to settings.py as shown below. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig', 'rest_framework' ] However pycharm does not recognise the 'rest_framework' and give an error when I try to run server. Failed to get real commands on module "DjangoProject": python process died with code 1: Traceback (most recent call last): File "E:\PyCharm 2017.3.3\helpers\pycharm_jb_manage_tasks_provider.py", line 25, in django.setup() File "D:\DjangoProject\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\DjangoProject\venv\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "D:\DjangoProject\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "D:\DjangoProject\venv\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' What would be the reason ? Thanks for your interest. -
The data is not showing in fields when i update data in updateview
The data is not showing in fields when i update data in updateview def dis_update(request, pk, template_name='sales/distributor_form.html'): alldistributor = get_object_or_404(Distributor, pk=pk) if request.method=='POST': form = DistributorForm(request.POST, instance=alldistributor) if form.is_valid(): form.save() return redirect('index.html') else: form=DistributorForm() return render(request, template_name, {'form':form}) -
How to display the contents of several records into one?
how to display the contents of several records into one ??? I have to do something like that enter image description here -
Django Cloudinary Storage 'TypeError: invalid file: None' on python3 manage.py collectstatic
I've installed django-cloudinary-storage to store my static and media files on Cloudinary for my django project. I followed the instructions given here - https://github.com/klis87/django-cloudinary-storage My settings.py is as follows: DEBUG = False # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] #Media files (User uploaded Images, Videos) MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get('CLOUDINARY_CLOUD_NAME'), 'API_KEY': os.environ.get('CLOUDINARY_API_KEY'), 'API_SECRET': os.environ.get('CLOUDINARY_API_SECRET'), 'INVALID_VIDEO_ERROR_MESSAGE': 'Please upload a valid video file.', 'EXCLUDE_DELETE_ORPHANED_MEDIA_PATHS': (), 'STATIC_IMAGES_EXTENSIONS': ['jpg', 'jpe', 'jpeg', 'jpc', 'jp2', 'j2k', 'wdp', 'jxr', 'hdp', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'ico'], 'STATIC_VIDEOS_EXTENSIONS': ['mp4', 'webm', 'flv', 'mov', 'ogv' ,'3gp' ,'3g2' ,'wmv' , 'mpeg' ,'flv' ,'mkv' ,'avi'] } At the moment I have just one static file at the path given below: BASE_DIR/static/css/fonts.css I'm trying to upload the file to Cloudinary by performing collectstatic, but it throws this error everytime - Traceback(most recent call last): File "manage.py", line 15, in < module > execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 288, in run_from_argv self.execute( * args, ** cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 335, in execute output = self.handle( * args, ** options) File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle … -
django filtering based on foreign key
I need to get all the orders except orders with order_type =14 (order table has a foreign key reference to order_type and batch tables) when i am calling the url. Please help me to know the solution. #models.py class Batch(models.Model): batchnum = models.TextField(null=True, blank=True) otp= models.TextField(null=True, blank=True) class Order(models.Model): reqnum = models.TextField(null=True, blank=True) order_date = models.DateField(auto_now_add=True, null=True, blank=True) batch= models.ForeignKey(Batch, db_index=True,related_name='results', on_delete=models.PROTECT,null=True, blank=True) order_status = models.ForeignKey('DotOrderStatus', on_delete=models.SET_NULL, null=True,related_name='dot_order_status',default=1) order_type = models.ForeignKey('DotOrderType', on_delete=models.SET_NULL, null=True,related_name='dot_order_type',default=10) slno = models.TextField(null=True, blank=True) customer_name = models.TextField(null=True, blank=True) contact = models.BigIntegerField( null=True, blank=True) url:localhost:8000/api/v1/batch/id where '/id' is batch id Please help me to know the solution. Thanks in advance. -
Python ContentFile
I'm trying to save a ContentFile on the hard disk, but I can't! Tried to make a file object using ContentFile() and write on it using ".write" method, then I wanna know how to save it on hard disk with ".Save" method or sth like this. f1 = ContentFile("") Thank you in advance. -
Fetch next set of queries from Django database for async loading
If for instance, my Django table has hundreds of rows and initially, in a view, I fetch first 10 records in the following format to be displayed on a webpage. def fetchtExperts(request): if request.method == "GET": experts = Experts.objects.exclude(client_assigned=None).values('id', 'name', 'age').order_by('qualification')[:10] return render(request, 'index.html', {'experts': experts}) If these 10 records are displayed on page 1, I want the next 10 records to be displayed when the user clicks on page 2. How do I fetch the next 10 records starting from the record succeeding the last fetched record? Do I send page 1's last record's ID to the view so that I could fetch the next 10 records accordingly or is there some better approach to achieve this? -
implicit grant type with django oauth-toolkit
After reading about authentication flows for different clients, the suggested grant type for single-page application should be implicit. However, there is no good documentation for using implicit grant types in Django OAuth-toolkit. Here is how thought it works: 1. register the client as public, authorization grant type implicit and specify a redirect uri 2. 'curl -X POST -d "grant_type:implicit&username:&password:" -u "" http://localhost:8000/o/token/' 3. recieve the access token at the redirect uri Maybe someone could clearify how implicit grant types should be handled. -
Exact filtering on QuerySets
There is ManyToMany field in Entry model called tags. How do I filter Entries, which contain exact set of selected tags? E.g. get all entries, that have tags with ids 1,2,3 and not 1,2,3,4 or 1,2 Something like this: selected_tags = Tag.objects.filter(id__in=[id1,id2,id3]) entries = Entry.objects.filter(tags=selected_tags) Thanks! -
Gunicorn error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I'm running an Ubuntu 16.04 Digital Ocean server for my Django website, with Nginx & Gunicorn. When I perform sudo systemctl status gunicorn, I get on my server: And I can't pinpoint what the problem is. Any suggestions? -
Python 3 Django - middleware for some request
I created a middleware which contain lot of functions to check something before getting the view. And i added the middleware to the setting.py, but it is for all requests. So, how can i make the middleware work for some requests, not all? -
How to show the same content on every page in Django?
I'm coding a blog website with Django and everything's looking good until now but I remember something about Django: DRY (Don't repeat yourself) but in my case, it's exactly what I'm doing. For example, I have a widget to show the recent posts for my blog. This widget appears on every single or index page of my blog and I couldn't do this with include because when I include something, it can't detect the block tags or its content. So I'm writing a code block for this in every another page like category-index, blog-single-page, etc. And the more important one is that I'm adding the database codes to pull data from database and every view def contains this code to show the widget's data so it's against to DRY principle. Any good way to do this or this is the normal way? Thanks! Here is the view to give you an idea: def category_detail(request, category_slug): posts = Post.objects # FOR BLOG POSTS WIDGET categories = Category.objects.all() # FOR CATEGORIES WIDGET category = get_object_or_404(Category, slug=category_slug) category_posts = category.post_set.all() paginator = Paginator(category_posts, 10) page = request.GET.get('page') cat_posts = paginator.get_page(page) context = { 'posts': posts.order_by('is_pinned', '-published')[:20], 'popular_posts': posts.order_by('is_pinned','-views')[:15], 'categories': categories, 'category': category, 'category_posts': … -
How to fix "NoReverseMatch at /polls/" with "'polls' is not a registered namespace" error?
My mysite/urls.py is this from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And, my polls/urls.py is from .import views from django.conf.urls import url from django.contrib.auth.views import login urlpatterns= [ url(r'^$',views.index, name= "index"), #127.0.0.1/polls url(r'^(?P<question_id>[0-9]+)/$', views.detail, name= "detail"), #127.0.0.1/polls/1 url(r'^(?P<question_id>[0-9]+)/results$', views.results, name="results"), #127.0.0.1/polls/1/results url(r'^(?P<question_id>[0-9]+)/vote$', views.vote, name="vote"), #127.0.0.1/polls/1/vote url(r'^login/$', login, {'template_name': 'polls/login.html'}) ] The error I am getting is there is no registered namespace as polls. Do help. -
Is there an efficient way to get the count of object occurrence in another object list ? Django
In my Django app, I have a few models including, but not limited to: Vehicle, Vehicle Make, and Dealership. I create a list comprehension that creates JSON objects with the vehicle make, count of occurrences for that make in the Dealerships inventory, e.g. 6 Toyotas in their inventory, and the id of that make in my Postgres DB. The problem is I have to use .count on all the vehicles in the database that are of that make, and belong to that dealership, which takes a huge toll on the database. Is there any way to speed this up, or optimize this. I've been looking through the web for potential solutions, but am coming up dry. view function try: dealer = Dealer.objects.get(id=1) except Exception as e: logging.error(e) makes_map = [{ 'name': make.name, 'count': Vehicle.objects.filter(vehicle_make=make, dealer=dealer).count(), 'id': make.id } for make in VehicleMake.objects.filter( name__in=Vehicle.objects.filter(dealer=dealer).values_list('vehicle_make__name', flat=True)) ] -
How to fill detail of Foriegn key used in other models of Python class
I have the following user and order class: class User(models.Model): id = models.AutoField(db_column='id', primary_key=True) password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() Order table class Order(models.Model): orderid = models.AutoField(db_column='orderId', primary_key=True) orderuserid = models.ForeignKey('User', models.DO_NOTHING,related_name='users', db_column='orderUserId') orderamount = models.IntegerField(db_column='orderAmount', blank=True, null=True) Now my question is that I want to create a new order from existing user , so how can I auto fill the orderuserid field in the Order table when create a order by the user. I am confused how the serializer will work now. -
Django REST Framework get list view by FK
class Project(models.Model): user = models.ForeignKey(USER) status = models.CharField(max_length=100, choices=(('NEW', 'NEW'), ('CLOSE', 'CLOSE'), ('CANCEL', 'CANCEL'))) class Investment(models.Model): project = models.ForeignKey(Project) status = models.CharField(max_length=100, choices=(('BOOKED', 'BOOKED'), ('FAIL', 'FAIL'), ('CANCEL', 'CANCEL'))) class ProjectSerializer(serializers.ModelSerializer): investment = InvestmentSerializer(many=True) class Meta: model = Project fields = ('id', 'status', 'investment') class ProjectView(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): serializer_class = ProjectSerializer def get_queryset(self): return Project.objects.filter(user=self.request.user, status__in= ['CLOSE', 'CANCEL'], investment__status__in=["FAIL", "CANCEL"])) I want a project view, only investment's status is 'FAIL' or 'CANCEL', but above code all investment in the result not only status is 'FAIL' or 'CANCEL', how to do this? -
Storing user specific documents in user folder
I am using django as backend technology and has hosted my server on aws ec2 instance. I want to store user specific data like profile picture, invoice etc. I thought of creating different folders with user id as the name of those folders and putting the content in them. I thought of using S3 for storage. But S3 doesn't support folder structure. I want to know best practices of storing user specific documents on server. I do not want to store them on the same server as it will cause problem when I will be scaling. -
Why are the templates requiring that I import jQuery in every template page, despite having it once in base.html?
My base.html already includes jQuery. And my templates extend base, but won't allow the jquery to work unless I re-insert the script tag in each template. What's going on? base.html: ... {% block javascript %} <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> {% endblock javascript %} detail.html: {% extends 'base.html' %} {% load static %} {% block content %} ... {% endblock content %} {% block javascript %} <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> I am required to place the script tag here again, despite having it in base. {% endblock javascript %} -
Design pattern for dynamic forms in Django
I have a set of models which are similar logically to the ones below. The models are the structure of a form with groups of elements that we can add to and change as required. The elements are HTML form elements like radio buttons, checkboxes and textareas that a user can fill out. class Form(models.Model): name = models.CharField(max_length=50) class FormGroup(models.Model): name = models.CharField(max_length=50) form = models.ForeignKey('forms.Form', related_name="groups") class FormGroupElements(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50, choices=['checkbox', 'radio', 'textarea']) group = models.ForeignKey('forms.FormGroup', related_name="elements") For this example, we are working on a "Dining Survey" with just the Entree section. When serialized, it looks like this. { 'form-id': '6be0ac8, 'name': "Entree Survey", 'groups':[ { 'id': '9cba9e2', 'name': "I enjoyed my entree", 'elements':[ { 'id': '009c8a2', 'name': "Yes", 'type': "radio", }, { 'id': 'c02da91', 'name': "No", 'type': "radio", } ] }, { 'id': '0f91c10', 'name': "The meal I had for my entree was", 'elements':[ { 'id': 3, 'name': "Meal", 'type': "textarea", }, ] }, ] } This renders out into HTML which looks like this: <input type="radio" name="9cba9e2-i-enjoyed-my-entree" value="Yes" /> <input type="radio" name="9cba9e2-i-enjoyed-my-entree" value="No" /> <input type="text" name="0f91c10-the-meal-i-had-for-my-entree-was" value="" /> I would like to save their response in a format that allows them to … -
What function can be used instread of CASCADE
I created books app, It has Publisher and Books models. In books Model i assigned a foreignkey for Publisher using on_delete = models.CASCADE. Actually i don't want to use this on_delete function. because if i delete data from parent table it will delete data on child table also. But I am getting TypeError: __init__() missing 1 required positional argument: 'on_delete' if i don't use on_delete = models.CASCADE. -
Django: `unique_together` doens't work properly when the number of unique field sets over 2?
models.py class Symbol(BaseModel): currency = models.CharField(max_length=10) class Tick(BaseModel) symbol = models.ForeignKey("Symbol") trade_datetime = models.DateTimeField() trade_coin_volume = models.DecimalField(max_digits=15, decimal_places=8) trade_price = models.DecimalField(max_digits=15, decimal_places=8) is_ask = models.BooleanField("is_ask?") class Meta: unique_together = (('symbol', 'trade_coin_volume', 'trade_price', 'is_ask', 'trade_datetime'), ) As you can see above code, I set unique_together with 4 fields. And I test Tick-model generate code like below: # the dictionary variable that i want to store in DB In [10]: tick_dict Out[10]: { 'askBid': 'BID', 'changePrice': 908000.0, 'tradeTimeKst': '15:21:59', 'tradeDateKst': '2018-02-06', 'tradePrice': 6924000.0, 'tradeVolume': 0.0143 } Try to save (date_time is properly preprocessed): Tick.objects.create( symbol=symbol, trade_datetime=date_time, trade_coin_volume=tick_dict['tradeVolume'], trade_price=tick_dict['tradePrice'], is_ask=tick_dict['askBid']=="ASK", ) It occured IntegrityError: IntegrityError: duplicate key value violates unique constraint "tick_symbol_id_trade_coin_vol_a7999e46_uniq" DETAIL: Key (symbol_id, trade_coin_volume, trade_price, is_ask, trade_datetime)=(3388, 0.01430000, 6924000.00000000, f, 2018-02-06 06:21:59+00) already exists. So, I looked up which data row has same fields (total 4 fields): In [11]: Tick.objects.filter(is_ask=False, trade_coin_volume=Decimal(0.01430000)) Out[11]: <QuerySet []> Nothing with same data exists in my database! What's wrong with it? The strange thing that I found out is the name of unique constraint: tick_symbol_id_trade_coin_vol_a7999e46_uniq, which seems to indicate only symbol_id and trade_coin_vol...? Need your advices -
Using Checkbox in django admin
I'm implementing project in django. I have two models that Studio and Template. class Studio(models.Model): studio_id = models.IntegerField() class Template(models.Model): template_id = models.IntegerField() Now I want to map templates with Studios. One Studio can have multiple templates. so I created model that StudioTemplateMapping. class StudioTemplateMapping(models.Model): studio = models.ForeignKey(Studio) template = models.ForeignKey(Template) in admin.py class StudioAdmin(admin.ModelAdmin): list_display = ('studio_id', ) class TemplateAdmin(admin.ModelAdmin): list_display = ('template_id', ) class StudioTemplateMappingAdmin(admin.ModelAdmin): list_display = ('studio', 'template) admin.studio.register(Studio, StudioAdmin) admin.studio.register(Template, TemplateAdmin) admin.studio.register(StudioTemplateMapping, StudioTemplateMappingAdmin) when I allocate studio with template, it should display all existing templates in checkbox. I could not displayed in checkbox view. could anyone suggest any way to display all templates in checkbox view and allocate with studio. -
Wagtail Feedback form in homepage
Tell me how to get the Wagtail form not in its separate template but on the homepage, since I do not need lending and another page. I can not find how to specify it in the get_context of the Home model