Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run a script using Django?
So I've conntected GMail API to my Django project. When I run quickstart.py alone in PyCharm it runs and works perfectly (that's the script that opens a new tab with GMail log in). Great but now I have to give a user an opportunity to do the same. So I decided that I'll create a button and with pressing that button the quickstart.py will run and user will log in. I tried that by creating an action. Then I tried a usual 'a' tag. And in both cases was error "Not found". Also I even tried to run an php where I execute .py script.Sounds crazy. <?php echo exec('/quickstart.py'); ?> But the error is the same. I've also tried to play with url.py and write paths. I think I don't understand something. Please, explain. So again and shortly: Press button -> Run quickstart.py -
Django + PostgreSQL FTS: combine SearchVectorFields
I have the following issue. In a PostgreSQL DB I have created on each table I need to search a ts_vector column that I have indexed to boost performance. In my Django models I have something like this: class Article(models.Model): title = models.TextField() body = models.TextField() textsearchable_index_col = SearchVectorField() class Comment(models.Model): article = models.ForeignKey(Article) title = models.TextField() body = models.TextField() textsearchable_index_col = SearchVectorField() Now, in some cases I need to perform a search just in the articles, ignoring the comments, so the following will do: search_query = SearchQuery(text) rank = SearchRank(F("textsearchable_index_col"), search_query) Article.objects.annotate(rank=rank).filter(rank__gte=0.3) But in other cases I might want to include the comments in my search, therefore combining the two SearchVectorFields. The problem is that this seems not be allowed. It seems I can only combine SearchVector created on-the-go, like this: search_vector = SearchVector("body") + SearchVector("comment__body") + .. rank = SearchRank(search_vector, search_query) Article.objects.annotate(rank=rank).filter(rank__gte=0.3) But in this way I will loose the benefits of the indexed, pre-weighted and pre-combined columns (my real models have 6 columns indexed as ts_vector in the textsearchable_index_col). So my question is: is there a way I can somehow do something like this: search_vector = F("textsearchable_index_col") + F("textsearchable_index_col") The error I get by doing so is: … -
Django: Get selected fields from a One2Many relationship
In Django I have 2 tables in my models: app_title and the auth_user table. How do I query all rows while returning only the name field from app_title and the username and email fields from the auth_user table? It's basically a One2Many relationship. I can't seem to get it right. class Title(models.Model): name = models.CharField(max_length=50) country = models.CharField(max_length=2) # Don't return this field user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Django Template Tags -- Trying to Let Users Delete Own Comments
I'm pretty new to Django. This seems really basic, but I can't seem to figure out what is going wrong here. <div class="comment"> <h2 class="commenter">{{ comment.user }}</h2> <p class="commentdate">{{ comment.created }}</p> <p class="commentbody">{{ comment.body }}</p> "{{ comment.user }}" "{{ user.username }}" {% ifequal commment.user user.username %} <p><a href="#">Delete comment</a></p> {% endifequal %} </div> I want a delete button to show up only if the logged in user is the same as the user who made a comment. {{ comment.user }} and {{ user.username }} are printing the same result (this is just a test line to see what's stored in these), but the {% ifequal comment.user user.username %} tag is evaluating as false for some reason. What am I doing wrong? Is it maybe a data type issue? If so, I'm not sure how to address that in template tags. -
manage.py runserver stuck(without errors)
when i add to __init__.py line default_app_config = 'component.nodes.apps.NodesConfig' apps file have next code: from django.apps import AppConfig class NodesConfig(AppConfig): name = 'component.nodes' def ready(self): from component.nodes import signals Django manage.py runserver stuck and don't send any error if i press ctrl-c i receiveed nex traceback: ^CTraceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/storj/storj/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/storj/storj/lib/python3.6/site-packages/django/core/management/__init__.py", line 318, in execute autoreload.check_errors(django.setup)() File "/home/storj/storj/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/storj/storj/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/storj/storj/lib/python3.6/site-packages/django/apps/registry.py", line 116, in populate app_config.ready() File "/home/storj/storjboard_server/component/nodes/apps.py", line 8, in ready from component.nodes import signals File "/home/storj/storjboard_server/component/nodes/signals.py", line 5, in <module> from component.nodes.tasks import node_info_update File "/home/storj/storjboard_server/component/nodes/tasks.py", line 5, in <module> from server.celery import app File "/home/storj/storjboard_server/server/celery.py", line 10, in <module> django.setup() File "/home/storj/storj/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/storj/storj/lib/python3.6/site-packages/django/apps/registry.py", line 71, in populate with self._lock: KeyboardInterrupt -
uwsgi 2.0.17 + django 2.0.3 worker crash sporadically
I am running uwsgi 2.0.17 in combination with a nginx infront and a Django 2.0.3 behind in a docker container. 1,6% of my request are failing due to uwsgi dying for some reasons. The logfileslook like this: DAMN ! worker 1 (pid: 108) died, killed by signal 9 :( trying respawn ... Respawned uWSGI worker 1 (new pid: 149) It happens on random URI's, so no specific view causing it. My uwsgi.ini looks like this: [uwsgi] # this config will be loaded if nothing specific is specified # load base config from below ini = :base # %d is the dir this configuration file is in socket = %dapp.sock master = true processes = 4 # pot. fix for prematurely closed upstream error limit-as = 512 [dev] ini = :base # socket (uwsgi) is not the same as http, nor http-socket socket = :8001 [local] ini = :base http = :8000 [base] # chdir to the folder of this config file, plus app/website chdir = %dserver # load the module from wsgi.py, it is a python path from # the directory above. module=server.wsgi:application # allow anyone to connect to the socket. This is very permissive chmod-socket=666 Any idea on how … -
What is an efficient way of handling millions of records and saving back to database?
Am using Django with python 2.7. am having an excel sheet with millions of rows. I have to manipulate rows data and save back to database (postgresql). I want to do it efficiently. Following are the approaches am thinking of : 1.) enqueue all the rows (data) in a queue (preferably RabbitMQ) and will fetch with a bunch of 100 entries at once. and will execute and will save it in database. 2.) thinking of using thread in background which will be managing 100 rows by each thread and will save back the result to database. I'm not sure how many database connections will be opened in this scenario. Can you please suggest me an efficient way to achieve this. it will be really very helpful. -
Slow django-channels update - redis
I went trough the tutorial for the new django-channels setup for 2.0 and have a problem with speed. It takes several seconds for me to send a message trough the chat to see that very same message appear back on my client. I am using the windows redis client and this is the log from sending a single message and waiting: [6060] 02 May 18:39:36 - DB 0: 7 keys (4 volatile) in 4 slots HT. [6060] 02 May 18:39:36 - 1 clients connected (0 slaves), 1990288 bytes in use [6060] 02 May 18:39:39 - Accepted 127.0.0.1:56967 [6060] 02 May 18:39:39 - Client closed connection [6060] 02 May 18:39:40 - Accepted 127.0.0.1:56971 [6060] 02 May 18:39:40 - Client closed connection [6060] 02 May 18:39:41 - DB 0: 7 keys (4 volatile) in 4 slots HT. [6060] 02 May 18:39:41 - 1 clients connected (0 slaves), 1990456 bytes in use [6060] 02 May 18:39:41 - Accepted 127.0.0.1:56973 [6060] 02 May 18:39:41 - Client closed connection [6060] 02 May 18:39:42 - Accepted 127.0.0.1:56977 [6060] 02 May 18:39:42 - Client closed connection [6060] 02 May 18:39:43 - Accepted 127.0.0.1:56981 [6060] 02 May 18:39:43 - Client closed connection [6060] 02 May 18:39:43 - Client … -
Django complex query to parent
I am using django and I am having a little trouble figuring out how to handle complex queries to the database. I have two models: Parent: id = models.AutoField(primary_key = True) name = models.CharField(max_length = 60) category = models.ForeignKey(Categories, on_delete = models.CASCADE) And son: id = models.AutoField(primary_key = True) name = models.CharField(max_length = 60) parent = models.ForeignKey(Parent, on_delete = models.CASCADE) Basically, I have an object with a queryset of sons, and I need to filter this queryset by certain categories of the parent. For example, filter all sons where parent category is 9, 10 or 11. I know how to use Q to do the OR part, but I don't know how to filter by a field in the parent. -
django rest framework "ModuleNotFoundError: No module named 'router'"
i have imported all the restframework packages but i don't understand why am i getting this strange error from django.conf.urls import * from django.contrib import admin from django.views.generic.base import TemplateView from .views import Create,Home,signup,Search,QuestionViewSet from django.urls import reverse from .models import Question from django.contrib.auth import views as auth_views from rest_framework import routers router=routers.DefaultRouter() router.register(prefix='question1',viewset=QuestionViewSet) app_name='main' urlpatterns = [ # url(r'^/',views.home,name='home'), url(r'^home/',Home,name='home'), url(r'^ques/',Create.as_view(success_url="/index/home/"),name='ques'), url(r'^signup/',signup,name='signup'), url(r'^logout/$', auth_views.logout,name='logout'), url(r'^search/',Search,name='search'), url(r'^api/', include('router.urls')) # CreateView.as_view(model=myModel, success_url=reverse('success-url')) ] this is the issue i'm facing ModuleNotFoundError: No module named 'router' any kind of help is appreciated thanks in advance -
Using replace method on list of model objects
I want to print out a list of objects, which at the moment looks like this: [<model.Name: value_of_field1>, <model.Name: value_of_field2>, etc]. I would like to get only the values, so I am hoping for an outcome like: value_of_field1, value_of_field2, etc My attempt to do this was by using: list = [item.replace('model.Name: ', '') for item in list], however, this resulted in the following error: 'model.Name' object has no attribute 'replace'. How can I get a clean list, that I can later on use? -
testing django app view in pycharm
def report(request, report_id): employee_id = request.user.employee.user_id if not Report.objects.filter(report_id=report_id).filter(employee_id=employee_id).select_related().exists(): return HttpResponseForbidden() rep = get_object_or_404(Report, pk=report_id) return MyJsonResponse(rep.serialize()) Im trying to test this. So i've written this test def test_report(self): report_id = 99 request = self.factory.get('/reports/{}'.format(report_id)) request.user = AnonymousUser() response = report(request,report_id) self.assertEqual(response.status_code,403) The problem is that i cant debug my view. I placed a breakpoint on response = report(request,report_id) but i cant step into it in order to see what's happening inside of def report(request, report_id): When i try to step into(F7) it opens decorators.py my run\debug config -
voice integration in Django website
I am new to Django, is there any app for voice communication in django. Like on going to the main url of the site, site will say "Welcome to main page". After login, site will say "Hello ". Basically I am creating monitoring website, so my purpose is to check for issues, and if any issue comes, voice app will speak the issue details. I am able to build few portions of monitoring website, now looking for voice app but not able to find suitable app for voice integration after lot of googling as well :( I have build exes with this voice feature using pyttsx3, so similar app like pyttsx3 in django. Thanks -
django, does not display the avatar in the comments
I extended standart django user model by one-to-one field. Made news block, and added comments there. In comments i cant display user avatar from UserProfile model, cause dont understand how correctly ask database for it D;. Here my code: main/models.py from django.db import models from django.utils import timezone from django.contrib import auth from django.contrib.auth.forms import User from django.shortcuts import render, redirect from profiles.models import UserProfile # Create your models here. class News(models.Model): news_title = models.CharField(max_length=250) news_body = models.TextField(max_length=2000, blank=True) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) image = models.FileField() published_date = models.DateTimeField(blank=True, null=True) def publish(self, request): self.published_date = timezone.now() self.save() return redirect('index') def __str__(self): return self.news_title class Comment(models.Model): news = models.ForeignKey('main.News', related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text profiles/models.py class UserProfile(models.Model): JEW_CHOICE = ( ('Да', 'Да'), ('Нет', 'Нет'), ) MF_CHOICE = ( ('М', 'М'), ('Ж', 'Ж') ) user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=100, default='', blank=True) city = models.CharField(max_length=100, default='', blank=True) description = models.CharField(max_length=500, default='', blank=True) website = models.URLField(default='', blank=True) avatar = models.ImageField(default='', blank=True) gender = models.CharField(max_length=100, choices = MF_CHOICE, default = 'М', blank=True) jew = models.CharField(max_length=100, choices = JEW_CHOICE, default = 'Да', blank=True) def __str__(self): … -
How to fill a Django form using test Client
I'd like to test my Django forms, but I got this error django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] doing this : self.client.post(self.url, {"title" : 'title', "status" : 2, "user" :1}) And my model only need those fields... Thank you :) -
IntegrityError after table restore from backup, PostgreSQL + Django
I am trying to restore a table in my database from some db backups. The backup is created via pgAdmin 4 UI tool, select a table and next backup it. And here is the command that pgAdmin executes: --file "C:\\Users\\cchie\\DOCUME~1\\DB_BAC~1\\CURREN~1" --host "localhost" --port "5432" --username "postgres" --no-password --verbose --format=c --blobs --table "public.cosmetic_crawler_currency" "last_cosmetics" The problem is that I have an AutoField in that table and when I restore a table, and next try to add new items into it - I have errors like this: psycopg2.IntegrityError: duplicate key value violates unique constraint "cosmetic_crawler_product_pkey" DETAIL: Key (product_id)=(27) already exists. The above exception was the direct cause of the following exception: django.db.utils.IntegrityError: duplicate key value violates unique constraint "cosmetic_crawler_product_pkey" DETAIL: Key (product_id)=(27) already exists. As I understand - that means that PostgreSQL server does not know that I have restored the AutoField counter and tries to count from 0? Is there a way to fix that and make it count from the last number? I was told that I have to use this recipe. But when I run manage.py sqlsequencereset my_app_name - I see that that command runs: BEGIN; SELECT setval(pg_get_serial_sequence('"cosmetic_crawler_product"','product_id'), coalesce(max("product_id"), 1), max("product_id") IS NOT null) FROM "cosmetic_crawler_product"; SELECT setval(pg_get_serial_sequence('"cosmetic_crawler_sale"','sale_id'), coalesce(max("sale_id"), … -
django-allauth email template styling
I am using django-allauth in my django application and the challenge I am facing has to do with the styling of the email sent. When a user registers, a confirmation mail is sent to the person but the email is just rendered as plain text. how can one style the email template. -
django rest framework create json and csv api
i am trying to create 2 api's. 1 to access json using ajax datatable, and the other to create an export csv button. the json api i manage to create and get the data from it using ajax, but i get problems when i try to access the api in the browser and the other to add the csv api..i will show you part of my scripts and the errors i get. views.py class VideoViewSet(viewsets.ModelViewSet): queryset = DatamsVideos.objects.all() serializer_class = VideosSerializer parser_classes = (CSVParser,) + tuple(api_settings.DEFAULT_PARSER_CLASSES) renderer_classes = (CSVRenderer,) + tuple(api_settings.DEFAULT_RENDERER_CLASSES) def list(self, request, **kwargs): try: vs = query_vs_by_args(**request.query_params) serializer = VideosSerializer(vs['items'], many=True) result = dict() result['data'] = serializer.data result['draw'] = vs['draw'] result['recordsTotal'] = vs['total'] result['recordsFiltered'] = vs['count'] return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None) except Exception as e: return Response(e, status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None) def get_renderer_context(self): context = super(VideoViewSet, self).get_renderer_context() context['header'] = ( self.request.GET['fields'].split(',') if 'fields' in self.request.GET else None) return context @action(methods=['GET'], detail=False) def bulk_upload(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_303_SEE_OTHER, headers={'Location': reverse('videos-api')}) urls.py from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'videos', VideoViewSet) urlpatterns = [ url(r'^$', index, name='main'), url(r'^api/', include(router.urls)), ] and this is part of my models.py def query_vs_by_args(**kwargs): draw = int(kwargs.get('draw', None)[0]) … -
Django crispy form: iterate through query object and display separate ChoiceFields for each query result
I am trying to make a django crispy form which essentially will: Query my database and return a set of results for a sample Allow the user, for each result, to choose from a dropdown to 'report' 'confirm' or 'not_report' the result. I want this to happen with each of the results to be under the same select name. I have made something similar using custom HTML: {% for o in obj %} <select name='reported'> <option value="{{o.id}}_dontreport" > - </option> <option value="{{o.id}}_report" >Report</option> <option value="{{o.id}}_toconfirm" >To confirm</option> </select> {% endfor %} But I am struggling using Django form (and rendering using crispy form): class ReportSample(forms.ModelForm): class Meta: model = SampleResult # fields = ('reported',) fields = "__all__" def __init__(self, *args, **kwargs): super(ReportSample, self).__init__(*args, **kwargs) sr_id = self.data.getlist('id')[0] res_obj = SampleResult.filter( sample_run_id=sr_id) for o in res_obj: report = ("%s_report" %(o.id), 'report') to_confirm = ("%s_to_confirm" %(o.id), 'to_confirm') dont_report = ("%s_dont_report" %(o.id), 'dont_report') reported = forms.ChoiceField( label='Report', choices=( report, to_confirm, dont_report ), required=False ) self.fields['reported'] = reported self.helper = FormHelper() self.helper.layout = Layout( Field('reported', autocomplete='off', css_class="search-form-label", id = 'reported' ), Submit('submit', 'Report sample', css_class='upload-btn') ) self.helper.form_method = 'POST' This obviously just renders the last result in my 'res_obj' with a ChoiceField. Is there … -
Django 2.0 unit test not running due to AppRegistryNotReady
I built a very simple Django application to try unit testing. I can run a test without any problem when not importing any Django model, like: import os from django.test import TestCase class FirstTest(TestCase): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testje.settings") def test_First(self): a = 1 self.assertEqual(1, a) I'm running Django 2.0.1. Now when I'm trying to import a model like: import os from django.test import TestCase from polls.models import Question class FirstTest(TestCase): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testje.settings") def test_First(self): a = 1 self.assertEqual(1, a) it will fail with the following stack trace: Testing started at 16:46 ... C:\Users\martijnka\virtualenvs\Test\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py" --path D:/martijnka/Downloads/testDjango/testje/polls/tests.py Launching unittests with arguments python -m unittest D:/martijnka/Downloads/testDjango/testje/polls/tests.py in D:\martijnka\Downloads\testDjango\testje\polls Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py", line 35, in main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING) File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 94, in __init__ self.parseArgs(argv) File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 141, in parseArgs self.createTests() File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 148, in createTests self.module) File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 219, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 219, in suites = [self.loadTestsFromName(name, module) for name in names] File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 153, in loadTestsFromName module = __import__(module_name) File "D:\martijnka\Downloads\testDjango\testje\polls\tests.py", line 5, … -
Django/Python - Unwanted caching of instances in views.py
I'm having an issue with a page running on Django 2.1. My issue is that when a function is called from views.py to populate a template, an instance of a class seems to be cached. Every subsequent call to that function/every refresh of that page shows old data from the previous time that page/function was called. The code in question: foo/bar.html #this is foo/bar.html {{ MyTable.DataColumns }} <br> {{ MyTable.DataRows }} views.py #this is a relevant snippet from views.py #There isn't anything outside of the functions, #with imports being the exception to this rule def list_page(request): template = 'foo/bar.html' connection = a_connection_here query_results = connection.get_query_results(sql_query_here) list_of_rows = [x for x in query_results] dt = DataTable() dt.DataColumns = [list_of_columns_here] for each_row in list_of_rows: dt.add(each_row) return_dict = {"MyTable": dt} return render(request, template, return_dict) The first time this page is loaded, foo/bar.html appears to be just what I want. I can see the columns printed to the page, and the few rows in that table. The problem is visible if you refresh the page. It's as if dt is being cached after the function has returned the render(). When you refresh the page, you'll see the columns, and the rows from the first … -
Not able to update the desired field in the form
So when I'm clicking the edit button I'm getting a pre-populated form. I tried to update one of my entries but i wasn't successful. This is my update view: def update(request, id): item = get_object_or_404(BookEntry, id=id) if request.method=="POST": form = UpdateForm(request.POST, instance=item) if form.is_valid(): post=form.save(commit=False) post.save() return HttpResponseRedirect(reverse('bms:index'), id) else: form=UpdateForm(instance=item) return HttpResponseRedirect(reverse('bms:index'), id) return render(request, 'index.html',{'form':form}) This is my forms.py: from django import forms from bms.models import BookEntry class UpdateForm(forms.ModelForm): title = forms.CharField(max_length=100) author = forms.CharField(max_length=100) edition = forms.CharField(max_length=100) publisher = forms.CharField(max_length=100) genre = forms.CharField(max_length=100) detail = forms.CharField(max_length=100) language = forms.CharField(max_length=100) price = forms.IntegerField() dop = forms.CharField(max_length=100) cop = forms.CharField(max_length=100) copyright = forms.CharField(max_length=100) isbn = forms.IntegerField() class Meta: model = BookEntry fields = '__all__' -
Can't run uwsgi --myproject.ini command
Can't run uwsgi --myproject.ini. Obtained error: ImportError: cannot import name _remove_dead_weakref I'm trying to run django project with virtualenv under uwsgi myproject.ini [uwsgi] home = /var/virtualenv/myproject chdir = /var/virtualenv/myproject/www module = project.wsgi plugins = python master = true processes = 4 no-orphans = true socket = /var/virtualenv/myproject/config/project.sock pidfile = /var/virtualenv/myproject/config/pid log-date = true chmod-socket = 666 vacuum = true touch-reload = /var/virtualenv/myproject/config/touchme Trace: File "./project/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/var/virtualenv/myproject/lib/python2.7/site-packages/django/core/wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "/var/virtualenv/myproject/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 8, in <module> from django import http File "/var/virtualenv/myproject/lib/python2.7/site-packages/django/http/__init__.py", line 1, in <module> from django.http.cookie import SimpleCookie, parse_cookie File "/var/virtualenv/myproject/lib/python2.7/site-packages/django/http/cookie.py", line 6, in <module> from django.utils.encoding import force_str File "/var/virtualenv/myproject/lib/python2.7/site-packages/django/utils/encoding.py", line 10, in <module> from django.utils.functional import Promise File "/var/virtualenv/myproject/lib/python2.7/site-packages/django/utils/functional.py", line 1, in <module> import copy File "/usr/local/lib/python2.7/copy.py", line 52, in <module> import weakref File "/usr/local/lib/python2.7/weakref.py", line 14, in <module> from _weakref import ( ImportError: cannot import name _remove_dead_weakref -
When bootstrap modal form is submitted redirected to form action url using django in python
When bootstrap modal form is submitted and redirected to same form action url using django in python Need to redirect the current page. Do the needful. Thanks! Save modal Form def save_table_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() print("valid") data['form_is_valid'] = True #tables = Rparequest.objects.all() #data['update_form'] = render_to_string('uts/rpa_table.html', {'tables': tables}) else: print("Invalid") data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) Create table data def rpamodaltable(request): if request.method == 'POST': form = RparequestForm(request.POST) else: form = RparequestForm() return save_table_form(request, form, 'uts/send-request.html') Edit table Data [def table_update(request, pk): table = get_object_or_404(Rparequest, pk=pk) if request.method == 'POST': form = RparequestForm(request.POST, instance= table) else: form = RparequestForm(instance= table) return save_table_form(request, form, 'uts/update_table.html')][1] -
Nginx configurations to allow domain name access without www
I have deployed a Django app on Digital Ocean. My nginx configuration settings looks very much similar to this (taken from here): server { listen 80; server_name example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /root/djtrump/static/; } location / { include proxy_params; proxy_pass http://www.example.com:8030; } } The problem being the fact that www.example.com takes to my site whereas example.com does not. Error shown in the browser is the site can not be reached. What can be the possible error and required configuration to resolve the same?