Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to login with facebook in django
I am not beig able to login with facebook from LOCAL HOST 8000.I tried all the steps listed in some tutorials.Please take a look at my code and help me with this I tried all the answers in stackover flow I'm posting my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'rg9n#$ebfj4w_mv-%7aahi2!qnitgw%xt(4re%i&)vdlppnz^e' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True SECURE_SSL_REDIRECT = False # Honor the 'X-Forwarded-Proto' header for request.is_secure() #SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Force HTTPS in the final URIs SOCIAL_AUTH_REDIRECT_IS_HTTPS = True ALLOWED_HOSTS = ['127.0.0.1','localhost',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'togther', 'django_select2', 'corsheaders', 'collabmates_api', # 'mail_templated', # "fcm_django" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'project.urls' 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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = … -
Creation a excel document from more than 1 resources by django-import-export
I have to generate an excel file from few ModelResource classes. But I havn't idea when (wich variable of class) and how I have to set multiresource variable in views.py function.. class RentersRes(resources.ModelResource): class Meta: model = Renters fields = ('name', 'snameplp','fnameplp',\ 'identity_doc','number_doc') export_order = ('name', 'snameplp','fnameplp',\ 'identity_doc','number_doc') class RentAddresRes(resources.ModelResource): class Meta: model = RentAddres fields = ('subject','city', 'street','house',\ 'telephon') export_order = ('telephon','subject','city', 'street','house') view.py function for generate excel file: def realreport(request): renter_info = RentersRes() cut = FcaRes() datasetrent = renter_info.export() datasetcut = cut.export() alldata = [] #how to unite result of export for RentersRes() and FcaRes()? response = HttpResponse(alldata.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="renter_info.xls"' return response -
Getting multiple checkbox POST values into django view
By using django view, I need to delete rows in my database based on list of checkboxes selected from html template index.html: {% csrf_token %} Delete {% for smail in form1 %} view.py: def mul_delete(request): if request.method == 'POST': chk = request.POST.getlist('check') print(chk) return redirect('/form1') [1,2,3,4] -
Django, how to set SMTP auth user management setup?
In web2py, we could set SMTP auth for user management by configuring SMTP mail address alone. In Django, how do we set that? Here, user management mean... The login form, gets user info and validate against in SMTP server and creates new user info in configured db. Is similar thing available in django? How do we achieve that in django? -
Update the database and send email when db is updated every day
I am trying to periodically update the database and then send email to db administrator that data base is updated. I use djnago and postgreSQL. Any idea what is the simplest way to achive what I am trying to do. I found celery to send email when db is updated, but I have not found any solution to update the db every day. I will appreciate any usefull advice, how can I solve the problem? -
How do you manually place forms from a formset?
I have a template page where it's suppose to load a form from the formset if a database query returns FALSE. <form method="post" class="form"> {% csrf_token %} {% for form in formset %} {% if comparelist.item2 %} <div class="col-3">{{comparelist.item2.name}}</div> <div class="col-3">{{comparelist.item2.price}}</div> <div class="col-3">{{comparelist.item2.store}}</div> {% else %} <div> {{form.form-0}} </div> {% endif %} {% if comparelist.item3 %} <div class="row"> <div class="col-3">{{comparelist.item3.name}}</div> <div class="col-3">{{comparelist.item3.price}}</div> <div class="col-3">{{comparelist.item3.store}}</div> </div> {% else %} <div> {{form.form-1}} </div> {% endif %} {% if comparelist.item4 %} <div class="row"> <div class="col-3">{{comparelist.item4.name}}</div> <div class="col-3">{{comparelist.item4.price}}</div> <div class="col-3">{{comparelist.item4.store}}</div> </div> {% else %} <div> {{form.form-2}} </div> {%endfor%} <button type="submit" class="btn btn-primary">Submit</button> </form> But obviously {{form.form-x}} doesn't work. So how do I insert these forms in manually? -
django-q task queue: Failed tasks keep processing forever
Anyone using django-q task scheduler: https://github.com/Koed00/django-q? (Not the database related Q library) I have a bunch of failed tasks. Everytime I run the django-q these failed tasks keep popping up: 18:06:14 [Q] INFO Process-1:9 processing [apart-sixteen-butter-friend] 18:06:14 [Q] INFO Process-1:10 processing [single-mississippi-bravo-fillet] 18:06:14 [Q] ERROR Failed [lithium-cola-batman-fanta] - No module named 'shootsta.user' 18:06:14 [Q] INFO Process-1:9 processing [ink-october-angel-california] 18:06:14 [Q] ERROR Failed [zulu-michigan-yankee-kilo] - No module named 'shootsta.user' 18:06:14 [Q] ERROR Failed [four-lemon-arizona-football] - No module named 'shootsta.user' 18:06:14 [Q] ERROR Failed [mississippi-fillet-winner-single] - No module named 'shootsta.user' 18:06:14 [Q] ERROR Failed [west-pennsylvania-asparagus-alabama] - 'BookingAnalytics' object has no attribute 'booking_uid' 18:06:14 [Q] ERROR Failed [wisconsin-pip-alanine-seventeen] - Can't switch from state 'job_complete' using method 'assign_camop' 18:06:14 [Q] ERROR Failed [finch-monkey-moon-oven] - 'AnalyticsFilter' object is not iterable 18:06:14 [Q] ERROR Failed [yellow-west-mango-papa] - 'AnalyticsFilter' object is not iterable 18:06:14 [Q] ERROR Failed [zulu-equal-mississippi-happy] - 'str' object has no attribute 'booking_uid' 18:06:14 [Q] ERROR Failed [six-beer-golf-blue] - 'str' object has no attribute 'booking_uid' 18:06:14 [Q] ERROR Failed [apart-sixteen-butter-friend] - 'str' object has no attribute 'booking_uid' 18:06:14 [Q] ERROR Failed [single-mississippi-bravo-fillet] - 'str' object has no attribute 'booking_uid' 18:06:14 [Q] ERROR Failed [ink-october-angel-california] - 'str' object has no attribute 'booking_uid' 18:06:15 [Q] ERROR reincarnated … -
how to upload image using django with ajax
trying to upload image using django with ajax but the system doesn't display any error as its not passing over the code. i create a model using ImageField in order to use image with specified the path. i create a function in the views file i create the path in urls file i create html file with ajax code that take the uploaded image models.py class photo(models.Model): titel = models.CharField(max_length=100) img = models.ImageField(upload_to = 'img/') urls.py from django.contrib import admin from django.urls import path, include from.views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', home2), path('upload/', upload), views.py from django.shortcuts import render,redirect from django.http import HttpResponse,JsonResponse from testapp.models import * import json as simplejson def upload(request): if request.method == 'POST': if request.is_ajax(): image = request.FILES.get('img') uploaded_image = photo(img = image) uploaded_image.save() return render(request, 'home2.html') home2.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script> function upload(event) { event.preventDefault(); var data = new FormData($('#ajax').get(0)); console.log(data) $.ajax({ url: '/upload', type: 'POST', data: data, contentType: 'multipart/form-data', processData: false, contentType: false, success: function(data) { alert('success'); } }); return false; } </script> </head> <body> <form method="POST" id="ajax" enctype="multipart/form-data"> {% csrf_token %} Img: <br /> <input type="file" name="img"> … -
ModuleNotFoundError: No module named 'drf_multiple_model'
when trying to start runserver it give me this error, I have no idea why, it was working fine before ModuleNotFoundError: No module named 'drf_multiple_model' Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/local/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/daniel/.local/share/virtualenvs/app-backend-RGL58hqa/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'drf_multiple_model' -
How to correctly migrate custom UserModel in Django
I have custom user model from AbstractUser. And in the user model i have 1 field as foreignKey to other model. So i can't make migrations because i recieve error: no such table: app_userrate I tired to comment this foreignKey field but it is not soulution cause i want to auto deploy app. class UserRate(models.Model): name = models.CharField(max_length=30, blank=False) max_active_events_cnt = models.PositiveIntegerField(default = 5) max_people_contacts_cnt = models.PositiveIntegerField(default = 30) def __str__(self): return self.name def default_rate(): obj, created = UserRate.objects.get_or_create(name="Basic") return obj.id class User(AbstractUser): rate = models.ForeignKey(UserRate, on_delete=models.PROTECT, default=default_rate) rate_until = models.DateField(null=True, blank=True) I want to understand what should i change to make migrations correctly -
How can I Update cart item quantity with django?
hope someone will help me to fix my problem. Since few time ago I am facing with a problem with my code, I couldn't understand why it's not working even that everything seem to be all ok for me. I want to give the possibility to update the cart quantity but I can only do it from the admin side not from a post request with a form. I have already try many example I have found on internet but nothing seem to fix mine. when I am posting the the quantity, I can see the data I am posting from the terminal by doing print(request.POST) but the doesn't going to the admin to update the cart quantity. Here is my models code: class Entry(models.Model): bustravels = models.ForeignKey(BusTravels, null=True, on_delete='CASCADE') bus_cart = models.ForeignKey(BusCart, null=True, on_delete='CASCADE') booking_seats_num = models.PositiveIntegerField(default=1, blank=True, null=True) def __str__(self): return "This entry contains {} {}(s).".format(self.booking_seats_num, self.bustravels) @receiver(post_save, sender=Entry) def update_cart(sender, instance, **kwargs): item = instance.booking_seats_num * instance.bustravels.price instance.bus_cart.subtotal += item instance.bus_cart.booking_seats_num += instance.booking_seats_num instance.bus_cart.updated = datetime.now() my modelForm to post the data: class BusQuantityForm(forms.ModelForm): PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 71)] booking_seats_num = forms.TypedChoiceField(label='Number of places', choices=PRODUCT_QUANTITY_CHOICES, coerce=int, required=False) class Meta: model = Entry fields … -
Django | making searchform to filter with multiple models
I'm trying to create a search form in my Django project that will filter multiple models(3) It works for a single model and an additional model tied by a foreign key. But,I can not combine different models query to one get_queryset. forms.py class SearchForm(forms.Form): username=forms.CharField( label = 'enterprise_id', required = False ) skill_name=forms.ModelChoiceField( queryset=Skill_name.objects, label='skill_list', required=False ) model.py class EnterpriseID(models.Model): enterprise_id = models.CharField('enterprise_id',max_length=40,blank=True,default="",) def __str__(self): return self.enterprise_id class Skill_name(models.Model): skill_name = models.CharField('skill_name',max_length=40,blank=False,null=False,) def __str__(self): return '{0}'.format(self.skill_name) class Skill(models.Model): enterprise_id = models.ForeignKey(EnterpriseID,verbose_name="enterprise_id",on_delete=models.PROTECT,) skill_name=models.ForeignKey(Skill_name,verbose_name="skill_name",on_delete=models.PROTECT,) def __str__(self): return '{0}'.format(self.enterprise_id) class Employee(models.Model): # user = models.OneToOneField(accounts_models.AuthUser, on_delete=models.CASCADE, blank=True) enterprise_id = models.ForeignKey(EnterpriseID,verbose_name="enterprise_id",on_delete=models.PROTECT,) join_at = models.DateField('join_at',default="",null=True,blank=True) def __str__(self): return '{0}'.format(self.enterprise_id) views.py class PersonalInfoSearchView(LoginRequiredMixin,ListView): model = Employee template_name = 'personal_info/search_personal_info.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = SearchForm(self.request.GET) return context def get_queryset(self): form = SearchForm(self.request.GET) queryset = super().get_queryset() if form.is_valid(): username = form.cleaned_data['username'] skill_name = form.cleaned_data['skill_name'] if username: queryset=queryset.filter(enterprise_id__enterprise_id__icontains=username) if skill_name: skill_query =Skill.objects.filter(skill_name=skill_name) return queryset.distinct() return redirect('personalInfo:personal_info_search') -
Query execution failed: \r\nTable already exists. (Tablename: django_migrations)
Found the error while initial migrate in django using NexusDB. pyodbc.Error: ('HY000', '[HY000] The query returned an error (ODBC State: HY000)\r\rError:\rNexusDB: <unnamed TnxODBCQuery instance>: Query execution failed: \r\nTable already exists. (Tablename: django_migrations)\r\n\r\n [$3304/13060]\r\rQuery:\rCREATE TABLE django_migrations ( id AUTOINC NOT NULL PRIMARY KEY, app NULLSTRING NOT NULL, name NULLSTRING NOT NULL, applied DATETIME NOT NULL)\r\r (-1) (SQLExecDirectW)') -
Requied explanation for Django views.py code
I'm learning Django and it was going pretty nice until I got confused with given code. Could someone explain me line by line what is happening there? from .forms import NewsLinkForm from .models import NewsLi class NewsLinkUpdate(View): form_class = NewsLinkForm template_name = 'organizer/newslink_form_update.html' def get(self, request, pk): newslink = get_object_or_404(NewsLink, pk=pk) context = { 'form':self.form_class(instance=newslink), 'newslink':newslink, } return render(request, self.template_name, context) def post(self,request,pk): newslink = get_object_or_404(NewsLink, pk=pk) bound_form = self.form_class(request.POST, instance=newslink) if bound_form.is_valid(): new_newslink = bound_form.save() return redirect(new_newslink) else: context = { 'form':bound_form, 'newslink':newslink, } return render( request, self.template_name, context ) -
How can I create a Django form out of a Model with 3 fields using the first field as the label, the rest as radio checks?
I have a Django model that has 3 fields: The name of the item The price of the small size The price of the large size Id like to create a form that looks like this The name of the item is essentially the label for the 2 succeeding radio checks. I'm not sure how to go about creating this type of form. I'd only like for one of the radio checks to be selected at a time. Do I have to iterate over every object in the database? -
Unable to redirect from CreateView
I'm new and inexperienced in Django and trying to implement a class based view and completely stuck trying to set the success_url. I've tried two approaches that I think are closest to being correct based on Google and not sure which one is least broken: success_url = 'letters/home' -> leads to unintended redirection /letters/write/letters/home whereas I want it to go to /letters/home reverse_lazy('letters:home') leads to "Reverse for 'home' not found. 'home' is not a valid view function or pattern name." Here's my code: View from .models import Topic from django.views.generic.edit import CreateView from django.views.generic import TemplateView from django.urls import reverse_lazy from .forms import WriteLetterForm class HomeView(TemplateView): template_name = 'letters/letter/home.html' class WriteLetterView(CreateView): template_name = 'letters/letter/write_letter.html' form_class = WriteLetterForm success_url = 'letters/home' # reverse_lazy('letters:home') # success_url = 'letters/home' # success_url = reverse_lazy('HomeView') def form_valid(self,form): form.instance.author = self.request.user form.instance.topic = Topic.objects.get(slug=self.kwargs['slug']) result = super(WriteLetterView, self).form_valid(form) cd = form.cleaned_data # user = authenticate(username=cd['username'], # password=cd['password1']) # login(self.request, user) return result urls.py within app from django.urls import path from . import views app_name = 'letters' urlpatterns = [ path('home/', views.HomeView.as_view()), path('write/<str:slug>', views.WriteLetterView.as_view()), ] forms.py from django import forms from .models import Letter from braces.forms import UserKwargModelFormMixin class WriteLetterForm(UserKwargModelFormMixin, forms.ModelForm): #letter = forms.ModelChoiceField(queryset=Letter.objects.all()) class Meta: model … -
How do I have multiple foreign keys in a django model
I have two classes in my models.py - Question and choice. The choice table has two columns which I want to be foreign keys to two (different) columns in Question. But this is giving an error. polls.Choice.question: (fields.E304) Reverse accessor for 'Choice.question' clashes with reverse accessor for 'Choice.topic'. HINT: Add or change a related_name argument to the definition for 'Choice.question' or 'Choice.topic'. polls.Choice.topic: (fields.E304) Reverse accessor for 'Choice.topic' clashes with reverse accessor for 'Choice.question'. HINT: Add or change a related_name argument to the definition for 'Choice.topic' or 'Choice.question'. I tried adding a 'related_name' parameter as I saw online but it didn't solve the problem. class Question(models.Model): id1=models.IntegerField(default=0) topic=models.CharField(max_length=222) question=models.CharField(max_length=222) answer=models.CharField(max_length=222) def __str__(self): return self.question #for the user to enter class Choice(models.Model): username = models.CharField(max_length=222) topic = models.ForeignKey(Question, name='topic',on_delete=models.CASCADE) question=models.ForeignKey(Question, name='question',on_delete=models.CASCADE) answer = models.CharField(max_length=222) def __str__(self): return self.username plz help -
Django Migration and Tests Pass Locally, but Fail in CI/CD Environment
Problem Honestly, I'm just firing this one into the dark because I have exhausted every possible avenue before asking this. I'm not sure what the problem is here. I have a Django application that works completely fine to run locally. I can run migrations. I have developed at length with this locally, and not had a single issue with the models, the testing, or any feature. The issue here is that the second I use GitLab's CI/CD Runner and perform the exact same steps I'm performing locally I get this output. ERRORS: piano_gym_api.LearnerEnrolledLesson.enrolled_course: (fields.E300) Field defines a relation with model 'piano_gym_api.LearnerEnrolledCourse', which is either not installed, or is abstract. piano_gym_api.LearnerEnrolledLesson.enrolled_course: (fields.E307) The field piano_gym_api.LearnerEnrolledLesson.enrolled_course was declared with a lazy reference to 'piano_gym_api.learnerenrolledcourse', but app 'piano_gym_api' doesn't provide model 'learnerenrolledcourse'. piano_gym_api.LearnerEnrolledLesson.enrolled_school: (fields.E300) Field defines a relation with model 'piano_gym_api.LearnerEnrolledSchool', which is either not installed, or is abstract. piano_gym_api.LearnerEnrolledLesson.enrolled_school: (fields.E307) The field piano_gym_api.LearnerEnrolledLesson.enrolled_school was declared with a lazy reference to 'piano_gym_api.learnerenrolledschool', but app 'piano_gym_api' doesn't provide model 'learnerenrolledschool'. Environment I'm using Python 3.7 with Django 2.2. My dependencies look like this: certifi==2019.3.9 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 Django==2.2 django-cors-headers==3.0.2 django-extensions==2.1.7 djangorestframework==3.9.4 djangorestframework-jwt==1.11.0 gunicorn==19.9.0 idna==2.8 itypes==1.1.0 Jinja2==2.10.1 lxml==4.3.3 MarkupSafe==1.1.1 music21==5.5.0 PyJWT==1.7.1 pytz==2019.1 requests==2.22.0 six==1.12.0 sqlparse==0.3.0 … -
Django REST Framework UniqueTogetherValidator
Problem Description: The DRF UniqueTogetherValidator is displaying some odd behaviour. For example: #-------models.py---------------# class MyModel1(models.Model): field1=models.IntegerField() field2=models.ForeignKey('MyModel2', on_delete...) class MyModel2(models.Model): field3=models.IntegerField() #------serializers.py-----------# class MyModel1Seriealizer(serializers.ModelSerializer): # some code here class Meta: model = MyModel1 validators = [UniqueTogetherValidator(queryset=MyModel1.objects.all(), fields=('field1', 'field2')] When the condition is violated by field1 only, it reports back a good 400 response with a message in non_field_errors, but when the violated field is field2 (or its _id), the server gives back a response code 500 (meaning Django caught it at the database/ORM level). The actual use-case is here on my GitHub. I've never linked to my own github issues before. Please let me know if this is not kosher before downvoting? -
Django templates not updating after database changes via admin
I am using Django v2.2 admin to change the information on my database but after I change it and refresh the page, the new data is not there, only the old data. A fix for this if I restart the server, the templates can now fetch the new data that I input. views.py # template with context class Home(TemplateView): template = 'home.html' context = { 'bar': Baby.objects.all() } def get(self, request): return render(request, self.template, self.context) home.html {% for foo in bar %} {{ foo.name }} {{ foo.cost }} {% endfor %} How I can get the new data by refreshing the page and not restarting the server? -
How to I print Data in human readable format on a template?
I have data in the following format coming from an API :"2019-05-29" I want to print it as May 29,2019 Below are the files and the response I am receiving from the API The response of the API "Data": [ { "id": 1, "news_title": "Recent Update", "news_description": "This is recent one line description", "image_id": 1, "news_date": "2018-05-18", "news_content": "the big content", "slug": "recent-update", "company_id": 1, "user_id": 1 } ] Views.py: def BlogViews(request,blog_type): """ The blogs are displayed according to the latest, current-month and last-month classification """ blog_type=blog_type.replace('-','_') response_blog=requests.get("API" % (settings.BASE_URL,blog_type),headers=headers,verify=False) if(response_blog.status_code==200): data_blog=response_blog.json() if(data_blog['ErrorCode']==0 and data_blog['SubErrorCode']==0): blog=BlogYearViews() if(len(data_blog['Data'])>0): blog_images=BlogImages(data_blog) blogs_and_images = zip(data_blog['Data'], blog_images) blog_type=blog_type.capitalize() blog_type=blog_type.replace('_',' ') return render(request,"CombinedBlog.html",{"blogs_and_images": blogs_and_images, "years":blog,"title":blog_type}) else: blog_type=blog_type.capitalize() blog_type=blog_type.replace('_',' ') return render (request,"NoBlogs.html",{"title":blog_type,"years":blog}) else: return redirect('/404') CombinedBlog.html <h2>{{title}} Articles</h2> <ul> {% for blog, image in blogs_and_images %} <li><h3>{{ blog.news_title }}</h3><br/> <a href="/blog/article/{{ blog.slug }}"><img src="{{ image.image_name }}"/></a><br/> {% blog.news_date "%Y %m %d" as time%} <time>{{time}}</time><br/> <a href="/blog/article/{{ blog.slug }}">click here</a><br/></li> {% endfor %} -
Nginx with uwsgi taking n*loading time with Moviepy
I am using Moviepy to edit a video and insert text into it in my web application. The page takes 10 seconds to load, that is alright for my client. The issue is when i host my project to a server. Say i send 5 requests simultaneously to the server, and the server gives response to all these requests in 50 seconds. Not giving response in 10 seconds for each of these requests. Below given is the nginx configuration file and uwsgi configuration. I have tried to add more processes, threads. Added uwsgi_read_timeout. But none of that fixed the issue. I don't have this issue in my local system. Each response takes only 10 seconds. That is why i thought the issue is not with moviepy, issue is somewhere in nginx and or uwsgi.Can somebody help me to figure out what is the issue here ? I am on an amazon instance with Intel(R) Xeon(R) Platinum 8175M CPU @ 2.50GHz processor with 2 cores and 8GB RAM. server { listen 80; error_log /home/ubuntu/error.log; client_max_body_size 100M; client_body_buffer_size 100M; location /media { alias /home/ubuntu/projectfolder/media; proxy_max_temp_file_size 0; uwsgi_read_timeout 300s; } location /static { alias /home/ubuntu/projectfolder/static; uwsgi_read_timeout 300s; } location / { uwsgi_pass unix:///tmp/uwsgi.sock; … -
How to reference a static file in Django that isn't inside my static file directory?
I want to use a javascript file that isn't in my static URL nor in any file that would be collected when running collect static. How would a point to this file in a way that I don't have to use {% load static %} It is basically so I can have only my DjangoTiny-MCE files in my Heroku server without collecting static instead of hosting them in AWS because that has proven troublesome. -
django template dynamic table field row data
I create django template dynamic table header, I want to get the table header from another model, and get the data corresponding to the table header from the data model. I want {{ data.field_name }} <== {{data.{{ header.{{header.field_id}} }} but not working, somebody help me... My views.py from asset_manager.models import ( AssetServiceCategory, AssetField, ) from asset.models import ( AssetList, ) #---[ Start Views ]---# #--[ Default Asset_manager View ]--# class Asset_View(View): #-[ Resuest GET URL:asset ]-# def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/accounts/login/') else: template_name = [ 'asset/asset.html', 'asset/asset/asset_service_category.html', ] service_category = AssetServiceCategory.objects.all() asset_list_header = AssetField.objects.filter(field_display="YES") asset_list_data = AssetList.objects.all() context = { 'service_category': service_category, 'asset_list_header' : asset_list_header, 'asset_list_data' : asset_list_data, } return render(request, template_name, context) My asset_list.html <table class="table table_asset_list"> <thead class="thead thead_asset_list"> <tr> {% for header in asset_list_header %} <th>{{ header.field_name }}</th> {% endfor %} </tr> </thead> <tbody class="tbody tbody_asset_list"> {% for header in asset_list_header %} {% for data in asset_list_data %} <tr> <td>{{ data.{{header.field_id}} }}</td> <== This is not working... </tr> {% endfor %} {% endfor %} </tbody> </table> -
Fixed default value provided issue with Django
This is my model: created_date = models.DateTimeField(default=datetime.datetime.now) after I run it.I receives the following error: article.Article.publish_date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use django.utils.timezone.now While I replace the code like this: created_date = models.DateTimeField(default=django.utils.timezone.now) it still remains me :NameError: name 'django' is not defined Any friend can help with this?