Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template get value from foreign keys without context
I have the following data model: class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=11) price = models.IntegerField(default=50) stripe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) In my nav bar I would like to show the membership_type if the user is authenticated. Is it possible to do it without a view passing the context? I tried the following: {% if request.user.is_authenticated %} {{ request.user.usermembership.membership.membership_type }} {{ request.user.usermembership_set.membership_set.membership_type }} {% endif %} -
How to align deleteCssClass inside a Jquery Formset?
I'm utilizing a javascript code, called Jquery Formset ( https://github.com/elo80ka/django-dynamic-formset/blob/master/src/jquery.formset.js) and I'm trying to adjust the layout, in particular about the deleteCssClass modifying the script code: .. addText: '+', deleteText: '-', addCssClass: "btn btn-primary", // CSS class applied to the add link deleteCssClass: "btn-primary", // CSS class applied to the delete link .. But the button delete is not in line with the forms, and the result is the following: I have insert the form in a table and I have delete the single Lables replacing them with the table head. Below the code of my tamplate: <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4"> <h2>Inserimento costi</h2> <hr> <div class="form-group"> <form action="." method="post"> {% csrf_token %} <div> {{ form.as_p }} </div> <table class="table"> {{ costi_materiali_form.management_form }} {% for form in costi_materiali_form.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} form-group formset_row1"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ … -
Django App to handle Authentication and sessions for Android app
I want to build an Android app and use my already existing Django app that is serving a website to authenticate users and handle sessions for the App. I was thinking of token authentication which could be, I build a token on Android App using shared secret and send it across to recieve authentication from server. Will that be possible ? Or any other way to do that with minimal or no dependencies ? -
AJAX in Django page refreshing issue
I have a database with user saved items. On their account the list of those items is displayed; a button next of each items can remove them from the database. Whenever I click on one of the items, their is 5 'delete icons' showing up next to each item. I am using Pagination set on 5 items to display them. But as well with console.log() I realize that whatever button I select my first button is selected. I know the AJAX call is working because the first item is removed from my database. My HTML: {% for saved in saved_list %} <div class="card mb-3" style="width: 49%;"> <div class="row no-gutters"> <div class="col-md-2 my-auto"> <img class="mx-auto d-block " style="width:auto; height:auto; max-width:100px; max-height:100px; " src="{{ saved.sub_product.picture }}"> </div> <div class="col-md-9"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'finder:detail' saved.sub_product.id %}" class="aaccount">{{ saved.sub_product.real_name}}/ {{ saved.sub_product.real_brand }}</a> </h5> <img src="/static/finder/img/nutriscore-{{ saved.sub_product.nutrition_grade}}.svg" style="width:70px;"><br> </div> </div> <div class="col-md-1 my-auto mx-auto"> <form class="form_id" method='post'>{% csrf_token %}{{ saved.id}} <button class='substitut' type="submit" value='{{ saved.id}}'><i class='fas fa-trash'></i></button> </form> </div> </div> </div> </div> {% endfor %} My AJAX: $(".form_id").on('submit', function(event) { event.preventDefault(); var product = $('.substitut').val(); console.log(product); var url = '/register/delete/'; $.ajax({ url: url, type: "POST", data:{ 'product': product, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', … -
ValueError at /shop/checkout/ Incorrect AES key length (20 bytes)
Traceback (most recent call last): File "C:\Users\uc\Envs\test\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\uc\projects\MyEcomSite\MyCart\shop\views.py", line 104, in checkout param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict, MERCHANT_KEY) File "C:\Users\uc\projects\MyEcomSite\MyCart\Paytm\Checksum.py", line 24, in generate_checksum return encode(hash_string, IV, merchant_key) File "C:\Users\uc\projects\MyEcomSite\MyCart\Paytm\Checksum.py", line 103, in encode c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8')) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher\AES.py", line 232, in new return _create_cipher(sys.modules[name], key, mode, *args, **kwargs) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher__init__.py", line 79, in _create_cipher return modes[mode](factory, **kwargs) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher_mode_cbc.py", line 274, in _create_cbc_cipher cipher_state = factory._create_base_cipher(kwargs) File "C:\Users\uc\Envs\test\lib\site-packages\Crypto\Cipher\AES.py", line 93, in _create_base_cipher raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) ValueError: Incorrect AES key length (20 bytes) [03/May/2020 11:49:35] "POST /shop/checkout/ HTTP/1.1" 500 97074 -
how can i display mysql content using 2 for loops is flask jinja2
I have written a code in flask in which users are allowed to upload images and along with image they can ask questions for taking user questions i have created a form and on submitting form user questions are stored into the database I am able to retrieve the question from database and images and diplay them in HTML using jinja2 What I want is to display the image and below that display its comment from flask import Flask,request,render_template,redirect,url_for,session,logging,flash,send_from_directory from flask_sqlalchemy import SQLAlchemy import pymysql pymysql.install_as_MySQLdb() from flask_mail import Mail app = Flask(__name__) import os app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/akashauto' db = SQLAlchemy(app) class Upload_tb(db.Model): snob = db.Column(db.Integer, primary_key=True) commentb = db.Column(db.String(20), unique=True, nullable=False) datab = db.Column(db.String(20), unique=True, nullable=False) APP_ROOT=os.path.dirname(os.path.abspath(__file__)) @app.route("/plcpro") def problem(): return render_template("plcpro.html") @app.route("/uploader",methods=["GET","POST"]) def uploader(): target=os.path.join(APP_ROOT,"images/") print(target) if not os.path.isdir(target): #if folder does not exist . create a folder os.mkdir(target) if(request.method=='POST'): f=request.files['file1'] text=request.form.get('comment') filename=f.filename f.save(os.path.join(target,filename)) image=os.listdir('./images') existing_entry=Upload_tb.query.filter_by(commentb=text).first() if existing_entry: # flash('Email already exist','danger') return redirect(url_for("plcove")) new_entry=Upload_tb(commentb=text,datab=filename) db.session.add(new_entry) db.session.commit() question=Upload_tb.query.all() return render_template('ans.html',file=filename,text=text,image=image,question=question) @app.route("/uploader/<filename>") def send_img(filename): return send_from_directory("images",filename) This is the Form code <form id="upload-form" action="/uploader" method="POST" enctype="multipart/form-data" onsubmit=" return askvalidateform()"> <div class="form-group"> <label for="name">Enter Name:</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter your name"> <span id="nameerror" class="text-danger"></span> </div> <div class="form-group"> <label … -
Bootstrap and css are both not working correctly in django project
I am using a html5 theme (https://colorlib.com/preview/theme/personal/) in my django 2 project. But, It's style not working correctly. I have linked all css correctly. My Django Project link (https://github.com/shahriar-programmer/personal-django). How can I modify my code to make it properly stylish like the theme preview? -
django orm relations - join three tables at diffrent fields
in my django model i have 3 model like : class Industry(models.Model): section = models.CharField(max_length=16, blank=True, null=True) industry = models.CharField(max_length=16, blank=True, null=True) class Company(models.Model): instrument = models.CharField(max_length=16, blank=True, null=True) symbol = models.CharField(max_length=16, blank=True, null=True) company = models.CharField(max_length=64, blank=True, null=True) industry = models.ForeignKey(Industry, on_delete=models.CASCADE, max_length=16, blank=True, null=True) class DailyData(models.Model): instrument = models.CharField(max_length=16, blank=True, null=True) i want to join DailyData and Company on field instrument . and join this to Industry on field industry . multiplie tables outer join on instrument and industry fields -
I am facing this problem in my about page if i remove my css then it works well otherwise it gives me an error whenever i use to display images
I am facing this problem in my about page if i remove my css then it works well otherwise it gives me an error whenever i use to display images please reply as soon as possible please reply fast for this question if anyone can Django Version: 3.0.5 Python Version: 3.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysiteapp'] 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\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\newproject\mysite\mysiteapp\views.py", line 27, in about return render(request,'about.html') File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loaders\base.py", line 24, in get_template contents = self.get_contents(origin) File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loaders\filesystem.py", line 24, in get_contents return fp.read() File "C:\Users\Rishabh\AppData\Local\Programs\Python\Python37-32\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) … -
django Templates does not exists execpt home url
I am creating a simple website.and having kinda odd error TemplateDoesNotExist at /about/ but my homepage working fine without TempaletDoesNotExist error. mine both home.html and about.html in same directory and I tried many solutions with the reference of this answer the actual problem is one URL is working and another one is not. please help me out thanks TemplateDoesNotExist at /about/ about.hmtl Request Method: GET Request URL: https://www.appname./about/ Django Version: 2.2.9 Exception Type: TemplateDoesNotExist Exception Value: about.hmtl Exception Location: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /home/name/virtualenv/appname/3.5/bin/python3.5_bin Python Version: 3.5.7 Python Path: ['/home/name/appname', '/opt/passenger-5.3.7-4.el6.cloudlinux/src/helper-scripts', '/home/name/virtualenv/appname/3.5/lib64/python35.zip', '/home/name/virtualenv/appname/3.5/lib64/python3.5', '/home/name/virtualenv/appname/3.5/lib64/python3.5/plat-linux', '/home/name/virtualenv/appname/3.5/lib64/python3.5/lib-dynload', '/opt/alt/python35/lib64/python3.5', '/opt/alt/python35/lib/python3.5', '/home/name/virtualenv/appname/3.5/lib/python3.5/site-packages'] Server time: Sun, 3 May 2020 04:48:46 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/contrib/admin/templates/about.hmtl (Source does not exist) django.template.loaders.app_directories.Loader: /home/name/virtualenv/appname/3.5/lib/python3.5/site-packages/django/contrib/auth/templates/about.hmtl (Source does not exist) django.template.loaders.app_directories.Loader: /home/name/appname/mysite/templates/about.hmtl (Source does not exist) My templates<dir> /home/name/appname/mysite/templates/home.html /home/name/appname/mysite/templates/about.html app<views.py> from django.shortcuts import render from django.http import HttpResponse def homepage(request): return render(request=request,template_name='home.html') def about(request): return render(request=request,template_name='about.hmtl') app<urls.py> from django.conf.urls import include, url from django.contrib import admin from django.urls import path from . import views app_name = "bugengine" urlpatterns = [ url(r'^$', views.homepage, name="homepage"), url(r'^about/',views.about, name="about"), ] setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Vue.js img src using absolute path (django+webpack)
I am using django + Vue.js & webpack for development. In my App.vue file i try to load img: <img src="/static/webapp/img/logo.png" alt="logo"> In production I use nginx which is directing /static path into static folder that I share and it's working. But in the development when i run my django on localhost:8000 and load this js from my App.vue it's trying to get the image from localhost:8000/static/webapp/img/logo.png. I would like it to take from localhost:8082/static/webapp/img/logo.png (localhost:8082 is where webpack is running) where it can be found. I tryied to change publicPath in my webpack.config.js: if (process.env.NODE_ENV === 'development') { module.exports.output.publicPath = 'http://localhost:8082/' } but it does not change default behaviour and the img asset src is still localhost:8000/static/webapp/img/logo.png. How can I change img assets default base path to another url to make it work? Cheers. -
How do you create a custom ChoiceField widget in Django?
I am trying to create a custom select field widget that includes at bootstrap input group. I can get the select element to render, but none of the options get rendered. The only documentation I can find is on creating custom widgets using text inputs. I have copied some of the below code from the Django source code hoping that would solve the issue, but the options are still not generated. Any help would be appreciated. widgets.py from django.forms import widgets from django.template import loader from django.utils.safestring import mark_safe class Select2(widgets.Select): template_name = 'widgets/select2.html' option_template_name = 'widgets/select2-options.html' def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) select2.html <select class="form-control select2" name="{{ widget.name }}">{% for group_name, group_choices, group_index in widget.optgroups %}{% if group_name %} <optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %} {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} </optgroup>{% endif %}{% endfor %} </select> <div class="input-group-append"> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#modal-xl"><i class="fa fa-plus"></i></button> </div> select2-options.html <option value="{{ widget.value|stringformat:'s' }}">{{ widget.label }}</option> -
Django admin: using extra field to filter dropdown values
I have a treebeard model like this (simplified version) from django.db import models from treebeard.mp_tree import MP_Node class CompanyHierarchy(MP_Node): department = models.CharField(max_length=30) employee_title = models.CharField(max_length=300) employee_name = models.CharField(max_length=300) It has 6 levels of depth and thousand of records. Now I'd like to add a new model with relationships between employees class Links(models.Model): from = models.ForeignKey("CompanyHierarchy", related_name='source', verbose_name='Документ', on_delete=models.CASCADE) to = models.ForeignKey("CompanyHierarchy", related_name='destination', verbose_name='Ссылка', on_delete=models.CASCADE) Now, CompanyHierarchy has thousands of records, so adding new Links through django admin panel is very cumbersome, as you have to pick one record from thousands in dropdown menu. How can I make this more user friendly? I was thinking of adding extra fields in django admin so that dropdown menu options could be filtered down. For example, adding extra field department, so that I can pick it first, and then dropdown menu for from would be filtered to include only that department. Or (even better) adding an extra field for setting depth first (treebeard creates this field), then having an extra field that will show only records of this selected depth, then filtering options in dropdown menu to include only records that are children of selected item (using path field that treebeard also creates). Is … -
Django not sending emails to local
I am very new to django and previously had emails sending to my terminal using: python -m smtpd -n -c DebuggingServer localhost:1025 I am trying to access the PasswordResetConfirmView template but cannot access the url as it is not appearing in my terminal. I believe it is now not sending an email. Here is what I used before in my settings: EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 Here are my urls: urlpatterns = [ # Homepage path('', views.home, name='home'), # Login/Logout path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), # Register path('register/', views.register, name='register'), # Profile path('profile/', views.view_profile, name='view_profile'), # Edit profile path('profile/edit/', views.edit_profile, name='edit_profile'), # Edit password path('change-password/', views.change_password, name='change_password'), # Password reset path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'), name='reset_password'), path('reset-password/done/', PasswordResetDoneView.as_view(template_name= 'accounts/reset_password_done.html'), name='password_reset_done'), path('reset-password/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset-password/complete/', PasswordResetCompleteView.as_view(template_name= 'accounts/reset_password_complete.html'), name='password_reset_complete') ] And a change_password view: def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user= request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('view_profile')) else: return redirect(reverse('change_password')) else: form = PasswordChangeForm(user= request.user) args = {'form' : form} return render(request, 'accounts/change_password.html', args) I am not sure why this has stopped sending emails and I am getting no errors on any page. Any ideas? -
Deserializing Nested JSON API response with Django
I'm pretty new to the DRF and serializing/deserializing. I'm slowly building a dashboard for my business during the corona virus and learning to code. I am in a little deep, but after spending more than $10k on developers on upwork and not really get much result, I figured, what do I have to lose? Our software provider has a full API for our needs https://developer.myvr.com/api/, but absolutely no dashboard to report statistics about our clients reservation data. The end result will be a synchronization of some of the data from their API to my database which will be hosted through AWS. I chose to do it this way due to having to do some post processing of data from the API. For example, we need to calculate occupancy rates(which is not an endpoint), expenses from our accounting connection and a few other small calculations in which the data is not already in the provided API. I originally wanted to use the data from the API solely, but I'm hesitant due to the reasons above. That's the backstory, here are the questions: The API response is extremely complex and nested multiple times, what is the best practise to extract a replication … -
I have deployed my Django App on Microsoft Azure and Static files are not displaying, only html
I've deployed a Django app on Azure and run it, everything was working fine css, images, js. After i run Gunicorn to automate the site then Only skeleton HTML displayed, css, images and js disappeared. this is the Erro: /home/honest/venv/lib/python3.6/site-packages/django/core/handlers/base.py:58: FutureWarning: TemplateForDeviceMiddleware is deprecated. Please remove it from your middleware settings. mw_instance = mw_class() /home/honest/venv/lib/python3.6/site-packages/django/core/handlers/base.py:58: FutureWarning: TemplateForHostMiddleware is deprecated. Please upgrade to the template loader. Not Found: /static/images/sample/slider/img7.png/ May i know if i need to configure WhiteNoise for gunicorn on Azure? Do i Need to edit my HTML templates to point to static folder in Azure? I tried some of the solutions i saw here like setting DEBURG to True set path for static files in Settings.py but it couldn't help. I will be glad receiving a step by step solution to this. Thanks for the assistence. -
advantages of MVT(Model View Template) over MVC(Model View Controller)
Any one explain advantages of MVT(Model View Template) over MVC(Model View Controller)? -
Google Places API - Getting an error on POST request when using domain restricted apikey
Google Places API - Getting an error on POST request when using domain restricted apikey. My code works fine for Google Places api when I'm using an unrestricted apikey for both the GET and POST request. When I use the apikey with the following HTTP referrers restriction: stage.myapp.com/* it seems to work fine for GET request, however for post request from stage.myapp.com/mypage/ I get a 500 error. Any recommendation on how to fix this. -
Django PATCH request update password using set_password method
I have below setup, view.py class UserViewSet(viewsets.ModelViewSet): queryset = apis_models.User.objects.all().order_by('-date_joined') serializer_class = apis_serializers.UserSerializer permission_classes = [HasPermPage] http_method_names = ['get', 'patch'] Serializer.py class UserSerializer(CustomSerializer): group = GroupSerializer(read_only=True) class Meta: model = apis_models.User fields = '__all__' models.py class User(DFModel, AbstractBaseUser): GENDER_CHOICES = [ ('m', 'Male'), ('f', 'Female'), ('n', 'Not sure'), ] email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, null=True) company = models.CharField(max_length=255, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) date_of_birthday = models.DateField(null=True) job_title = models.CharField(max_length=255, null=True) description = models.TextField(null=True) credit_card = models.CharField(max_length=255, null=True) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) group = models.ForeignKey('Group', on_delete=models.PROTECT, null=True) Using REST API I am doing PATCH request on User model and trying to update the password. The password is getting stored as plain text. I found that set_password method store it as encrypted. Can anybody please help me to implement that. I am not sure where to include that method. In viewset or serializer? And how? Any help would be appreciated. -
DRF ListAPIView custom return not an object
I'm trying to customise ListAPIView in order to return custom object. By default DRF returns object in an array, I want just a customized object. class PostDetailApiView(ListAPIView, CreateAPIView): serializer_class = PostSerializer permission_classes = [AllowAny] def get_queryset(self, request, *args, **kwargs): response = super().get_queryset(request, *args, **kwargs) return Response({ 'status': 200, 'message': 'Post delivered!!', 'data': response.data }) I'm getting error: lib/python3.7/site-packages/django/template/response.py", line 120, in __iter__ 'The response content must be rendered before it can be iterated over.' **django.template.response.ContentNotRenderedError: The response content must be rendered before it can be iterated over.** [03/May/2020 02:34:14] "GET /en-us/blog/api/posts/VueJS%20blog%20in%20progress HTTP/1.1" 500 59 The error dissappears when I return an empty array e.g.: def get_queryset(self): queryset = [] queryset.append(Post.objects.get(title=self.kwargs["title"])) return queryset How could I return an object like this from Class-based views?: { "status": 200, "message": "Post created!", "data": {} } Thank you -
Requests download to media server in django
I have this module that I imported into django. It uses request to download files from specific urls. This works well given that the host is my system. If I move to a server, this would mean the files would get downloaded to the server and that is not efficient or good at all. How can I use this module to download and automatically upload to media server or better still, download directly to the media server and from there, serve it up to user to download. This is the script's code def download_course_file(self, course): username = self._login_data["username"] p = Path(f"{username}-{course}.txt").exists() if not p: self.get_download_links(course) statime = time.time() with open(f"{username}-{course}.txt", "r") as course_link: data = course_link.read().splitlines(False)[::2] p.map(self.download, data) def download(self, url): response = self._is_downloadable(url) if response: name = response.headers.get('content-disposition') fname = re.findall('filename=(.+)', name) if len(fname) != 0: filename = fname[0] filename = filename.replace("\"", "") print(filename) else : filename = "Lecture note" with open(filename, 'wb') as files: for chunk in response.iter_content(100000): files.write(chunk) I omitted the self._is_downloadable() logic since it doesn't apply here def download_course(request, id): course = course = get_object_or_404(Course, id=id) course_name = (course.course_name)[:6] person, error = create_session(request) if "invalid" in error: data = {"error":error} return JsonResponse(data) person.download_course_file(course_name) data = {"success":"Your … -
Deploying a Django App to GitHub - Landing page isn't being displayed
I'm trying to deploy my Django application on github. Files have been uploaded successfully, the url works fine, but when I go the site https://qasim-khan1.github.io/blog/ It doesn't direct me to my landing page. It shows nothing, simply 'Blog' written in bold text. -
How to add correctly add JSONField to RegisterSerializer in Django?
I'm building a web app at the moment that lets people build pages. These pages should be stored as JSON in my Postgres Database. I've implemented a customer user manager/model in Django: from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.postgres.fields import JSONField class UserManager(BaseUserManager): def create_user( self, email, page, username, password=None, commit=True): """ Creates and saves a User with the given email, first name, last name and password. """ if not email: raise ValueError(_('Users must have an email address')) user = self.model( email=self.normalize_email(email), username=username, page=page ) user.set_password(password) if commit: user.save(using=self._db) return user def create_superuser(self, email, username, password, page=None): """ Creates and saves a superuser with the given email, first name, last name and password. """ user = self.create_user( email, password=password, username=username, commit=False, ) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('email address'), max_length=255, unique=True ) # password field supplied by AbstractBaseUser # last_login field supplied by AbstractBaseUser username = models.CharField( max_length=30, blank=True, unique=True) page = JSONField(default=dict) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of … -
Django - making API call with user input
I'm creating a Django webapp where the user will input a zip code then the page will display a list of establishments in that area using the Yelp API. homepage.html <form method="GET" action="{% url 'homepage' %}"> {% csrf_token %} <label>Zip Code: </label> <input name="zip_code"> <button type="submit">Submit</button> </form> yelp.py def get_name(location): """ makes call to Yelp API and returns list of establishments within the given zip code """ restaurants = [] url = 'https://api.yelp.com/v3/businesses/search' params = { 'location': f'{location}' } headers = {'Authorization': f'Bearer {YELP_KEY}'} response = requests.get(url, params=params, headers=headers).json() for business in response['businesses']: restaurants.append(business['name']) return restaurants I'm super new to this so I'm unsure how to take the input from homepage.html and use it to make the API call in yelp.py. I know there are Views and Models and Forms, I'm just confused what each of them do and how to use them in this scenario. Let me know if there's more info I can provide. -
How to setup uWSGI vassal names for better log reference?
INFO: Framweork: Django 2.X < 3.x ; Services: supervisord; uWSGI Host: CentOS Linux 7 Hello, i am currently testing how to deploy multiple django apps with uWSGI on my host. I set everything up based on manuals provided by my Host & uWsgi and it works. However i would like to customized everything a bit further, so that i can understand everything a bit better. As far as i understand my uWSGI service uwsgi.ini currently works in an emperor mode and provides vassals for my two different app named baron_app.ini and prince_app.ini to handle my different apps. Question I noticed that the err.log is a kind of confusing for debugging with multiple apps. for instance... announcing my loyalty to the Emperor... Sat May 2 21:37:58 2020 - [emperor] vassal baron_app.ini is now loyal.... [pid: 26852|app: 0|req: 2/2]..... Question: Is there a way to give my vassals a name so that it will printed in the Log ? Or a way to tell uWSGI to set some kind of process & app log relation (Emperor - Vassals - Worker etc.) in the Log? For instance i could imagine something like this, could be easier when it comes to find errors. #baron_app: …