Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when clicking submit forms, opens home page and
I have built a Django web app (Django version = 1.11.13). I have problem when i click submit form in a sub page , it opens the home page and not runs view function for this sub page. Here is urls.py: *urlpatterns = [ url(r'^$', Part, name='Home'), url(r'^part/$', Part, name='Add Part'), url(r'^parts/$', Parts, name='Parts Page'), ]* This is from parts.html (Parts page) : *<form action="{% url 'Parts Page' %}" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary" value="{{ part.0 }}" name="increase">+</button> </form>* When i click submit this form in parts page , it opens the home page 'part page' but the link written in the browser is right 'parts page link' This issue happens on the hosting server 'A2 hosting' not localhost. Please help me Thanks -
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
I got the below error when I send a JSON request from angular and receiving it in DRF and tried to store in the database, [04/Aug/2018 22:52:02] "POST /users/ HTTP/1.1" 500 76640 Internal Server Error: /users/ Traceback (most recent call last): File "D:\Django_Angular\Djangoworkspace\venv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "D:\Django_Angular\Djangoworkspace\venv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Django_Angular\Djangoworkspace\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django_Angular\Djangoworkspace\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\Django_Angular\Djangoworkspace\venv\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "D:\Django_Angular\Djangoworkspace\venv\lib\site-packages\rest_framework\views.py", line 485, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "D:\Django_Angular\Djangoworkspace\venv\lib\site-packages\rest_framework\views.py", line 400, in finalize_response % type(response) AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` [04/Aug/2018 22:57:36] "POST /users/ HTTP/1.1" 500 76625 -
Elasticsearch does not return any values. Django
I'm trying to add a search engine for my blog project using ElasticSearch. I think I did everything correctly (using this tutorial), but whatever I write in the search engine, she always returns no results. My database has records and everything looks good. What can happen? Why can not return any results? Any help will be very appreciated My urls.py from django.conf.urls import url from . import views app_name = 'reviews' urlpatterns = [ # ex: / url(r'^$', views.review_list, name='review_list'), # ex: /review/5/ url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'), # ex: /wine/ url(r'^wine$', views.wine_list, name='wine_list'), # ex: /wine/5/ url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'), url(r'^wine/(?P<wine_id>[0-9]+)/add_review/$', views.add_review, name='add_review'), url(r'^review/user/(?P<username>\w+)/$', views.user_review_list, name='user_review_list'), url(r'^review/user/$', views.user_review_list, name='user_review_list'), url(r'^review/search/$', views.search, name='search'), ] My views.py rom django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Review, Wine from .forms import ReviewForm import datetime from django.contrib.auth.decorators import login_required from django.shortcuts import render from .documents import ReviewDocument def review_list(request): latest_review_list = Review.objects.order_by('-pub_date')[:9] context = {'latest_review_list':latest_review_list} return render(request, 'reviews/review_list.html', context) def review_detail(request, review_id): review = get_object_or_404(Review, pk=review_id) return render(request, 'reviews/review_detail.html', {'review': review}) def wine_list(request): wine_list = Wine.objects.order_by('-name') context = {'wine_list':wine_list} return render(request, 'reviews/wine_list.html', context) def wine_detail(request, wine_id): wine = get_object_or_404(Wine, pk=wine_id) form = ReviewForm() return render(request, 'reviews/wine_detail.html', {'wine': wine, … -
How to remove the user if the activation link is not clicked before given time?
I am trying to implement email verification based authentication system in my django app. What exactly I want is, the email link has to expire after sometime. Even though user clicks on it, the link should not work and the user should be deleted from the database. How to do that? forms.py: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password',] def clean_email(self): email = self.cleaned_data['email'] print('email cleaned data: ' + self.cleaned_data['email']) try: User.objects.get(email=email) raise forms.ValidationError('Email already exists.') except User.DoesNotExist: return email views.py : def register(request): form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.is_active = False # username = form.cleaned_data['username'] # password = form.cleaned_data['password'] # user.set_password(password) user.save() # user = authenticate(username=username, password=password) # if user is not None: # if user.is_active: # login(request, user) # return render(request, 'set_goals/index.html') # context = { # "form": form, # } current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('registration/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) # email.send() user.email_user(mail_subject,message) return HttpResponse('Please confirm your email address to complete the registration') context = { "form": form, } return render(request, 'set_goals/register.html', … -
Implementing views with template in django
I'm struggling to show on a webpage some model objects I created from the admin pages on my site. I combed through the relevant django tutorial page, and used this as my guide for writing my view: def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) Though I didn't understand the third line so left it out. This may be the problem, I'm not sure. Either way, nothiong I've tried works to show the model objects on the page. Here is my models.py: from django.db import models from datetime import datetime from datetime import timedelta # Create your models here. def get_deadline(): return datetime.today() + timedelta(days=3) class JobPost(models.Model): created_at = models.DateTimeField(auto_now_add=True, blank=True) deadline = models.DateField(default=get_deadline) wordcount = models.IntegerField() jobtaken = models.BooleanField(default=False) # client = models.User.username class Meta: ordering = ( # ("jobtaken"), ("-created_at"), ) def publish(self): self.pub_date = timezone.now() self.save() def __str__(self): return "Job #{}".format(self.pk)` views.py: from django.shortcuts import render from django.views.generic import TemplateView #from django.contrib.auth.decorators import staff_member_required from .models import JobPost from django.utils import timezone # Create your views here. # @staff_member_required() # class JobBoardView(TemplateView): # template_name = "jobs.html" # posts = JobPost.objects.filter(published_date__lte=timezone.now()).order_by('pub_date') #changed published_date to pub_date in .models def jobs(request): #posts = … -
Django; How to use jquery ajax? The server encountered an unexpected condition that prevented it from fulfilling the request
I'm creating a project using Django. I am adapting ajax into my project but there is an error. I was creating thumb up button and the error says HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.(XHR)POST js is like this function thumbUp(entry) { var $entry = $(entry) var id = $entry.data('id') $.ajax({ url:'/thumb_up/entry/' + id, method: 'POST', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } urls.py is like this path('thumb_up/entry/<int:entry_id>', views.thumb_up, name='thumb_up'), html is like this <a data-id="{{ entry.id }}" onclick="thumbUp(this)"><img src="{% static 'blog/images/thumb-up.png' %}" id="thumb-up-icon"></a> what is wrong with this? -
How can I get the "code" value from redirect url's response?
I wrote a function in order to get the code value from redirect url's response, however I cannot catch it. the function; CLIENT_ID = "xxx" CLIENT_SECRET = "xxx" REDIRECT_URI = 'http://127.0.0.1:8000/products/auth' AUTHORIZE_URL = "https://www.example.com/admin/user/auth" ACCESS_TOKEN_URL = "https://www.example.com/oauth/v2/token" STATE = "2b33fdd45jbevd6nam" # temporary state id request.GET.get('{}?client_id={}&response_type=code&state={}&redirect_uri={}'.format(AUTHORIZE_URL, CLIENT_ID, STATE, REDIRECT_URI)) request.session['code'] = request.GET.get('code') code = request.session['code'] print ("***AUTH START***") print (code) print ("***AUTH END***") return render (request, 'products/auth.html') I also wrote print that I can be sure that I am catching it. However I am getting this result; ***AUTH START*** None ***AUTH END*** -
Creating url out of user's choices from the form. Django gives NoReverseMatch, saying i need at least two arguments and i have none
So basically i have form on my homepage that asks users to choose two cities : where they are now, and where they want to go. I display all the available options with ModelChoiceField() easily, but when i try to use user's choices to make arguments for url, i get NoReverseMatch. I did a little research and found out due to the fact that at the time when page is loaded, user hasn't chosen anything, so there are no arguments. After that, i took different approach - i tried to set /search/ as url for the form. There, i extracted user's choices and tried to redirect back to the main url with these two arguments. Error still persists Reverse for 'route' with arguments '('', '')' not found. Here's my forms.py : class RouteForm(forms.Form): location = forms.ModelChoiceField(queryset=Location.objects.all()) destination = forms.ModelChoiceField(queryset=Destination.objects.all()) Here's my template : <p> From where to where ? </p> <form action="{% url 'listings:search' %}" method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Let's go!"> </form> My urls.py : urlpatterns = [ path('', views.index, name="index"), path('<location>/<destination>', views.route, name="route"), path('search/', views.search, name="search") ] and views.py : def index(request): form = forms.RouteForm() listings = Listing.objects.all() context = {"listings" : listings, "form" … -
Django Haystack user-specific ordering
I have a large set of Articles. For each pair of User and Article I have a Recommendation that stores a custom score (and some other data). #----- models.py ----- class Article(models.Model): title = models.CharField(max_length=255, unique=True) abstract = models.TextField() journal = models.CharField(max_length=255) authors = models.TextField() pubdate = models.DateField(db_index=True) class Recommendation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) score = models.FloatField(db_index=True) # some other fields ... class Meta: # Order descending by score ordering = ["-score"] I'm using Haystack and Solr to provide fulltext search on my articles. However what I want to display to the users are their recommendations filtered by the search. Therefore I am not interested in Solr's result ranking. I want to order the results based on my custom recommendation-score. The problem is that this custom score depends on the user. This means I can't add it to the article index, since it's not a single value but rather as many scores as there are users. My current solution: # Get the searched articles sqs = SearchQuerySet().auto_query(query).load_all() # Load the keys to all returned articles result_keys = sqs.values_list('pk', flat=True) # Get all recommendations belonging to these keys and this user recommendations = Recommendation.objects.filter(user=self.request.user, article__in=result_keys).select_related('article') # Setup … -
Bootstarp responsivenes not working in chrome
I am having problems with the responsiveness of my website. I have an image that, when tried fitted to the page overflows its container. the side works fine in firefox, and i only see the problem when i open it in chrome. Picture of Firefox and chrome side by side, Firefox on the left and chrome on the right The code from my base template <!doctype html> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-112234171-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-112234171-1'); </script> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yes"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous"> <title>NPCbase</title> {% block meta %} <script type="text/javascript" src="//platform-api.sharethis.com/js/sharethis.js#property=5a5215360f300f0013e83388&product=inline-share-buttons"></script> <meta property="og:url" content="http://www.npcbase.com/character/" /> <meta property="og:title" content="Generate over 84 million unique characters" /> <meta property="og:description" content="Click here to generate more!" /> <meta property="og:image" content="https://i.imgur.com/MhszXDH.png" /> {% endblock %} </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = 'https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.11&appId=474470075910812'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="container"> <header class="masthead"> <nav class="navbar navbar-expand-md navbar-light bg-light rounded mb-3"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> … -
How to dynamically change Django Serializer class fields
Hi I am using a simple serializer class with few fields in it. class ticker_name_list(serializers.ModelSerializer): class Meta: model = ticker fields = ('symbol', 'industry', 'company_name') I have userinput which customize the fields to show in the table. I have to display the data with those fields. How can I change my serialzer class fields based on the user input? -
Django FileResponse - How to speed up file download
I have a setup that lets users download files that are stored in the DB as BYTEA data. Everything works OK, except the download speed is very slow...it seems to download in 33KB chunks, one chunk per second. Is there a setting I can specify to speed this up? views.py from django.http import FileResponse def getFileResponse(filedata, filename, filesize, contenttype): response = FileResponse(filedata, content_type=contenttype) response['Content-Disposition'] = 'attachment; filename=%s' % filename response['Content-Length'] = filesize return response return getFileResponse( filedata = myfile.filedata, # Binary data from DB filename = myfile.filename + myfile.fileextension, filesize = myfile.filesize, contenttype = myfile.filetype ) Previously, I had the binary data returned as an HttpResponse and it downloaded like a normal file, with normal speeds. This worked fine locally, but when I pushed to Heroku, it wouldn't download the file -- instead displaying <Memory at XXX> in the download file. And another side issue...when I include a text file with non-ASCII data (i.e. á), I get an error as well: UnicodeEncodeError: 'ascii' codec can't encode characters...: ordinal not in range(128) How can I handle files with unicode data? Thanks. -
Django - error in importing rpy2 & django-rpy2
My R_HOME is set to C:\Program Files\R\R-3.5.1 but still when i import rpy2 or django-rpy2 its giving me the error of R_HOME. This : Error: Tried to guess R's HOME but no command 'R' in the PATH. I have worked with rpy2 in jupyter it works all fine but what to do here? -
unable to shift pages from homepage to about page
I am trying to create a small web application with django and I am a novice in this I am trying to create a homepage and a about button on homepage that reloads the page to about page This is my index.html <!DOCTYPE html> <html> <head> <title>Simple App</title> <h1> Testing the simple app</h1> </head> <body> <a href="/about/">About </a> </body> </html> This is my about.html <!DOCTYPE html> <html> <head> <title>Simple App</title> <h1> Testing the simple app</h1> </head> <body> This is the about page </body> </html> This is my views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) # Add this view class AboutPageView(TemplateView): template_name = "about.html" and urls.py from django.conf.urls import url from django.contrib import admin from homepage import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', views.HomePageView.as_view()), url(r'^about/$',views.AboutPageView.as_view()), ] However when i click on about button nothing happens -
AttributeError: type object 'Reporter' has no attribute 'model'
I have two simple models Reporter and Article, class Reporter(models.Model): name = models.CharField(max_length=50) class Article(models.Model): title = models.CharField(max_length=100) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) and my serializer class as, class ReporterSerializer(serializers.ModelSerializer): class Meta: model = Reporter fields = '__all__' and my views class ReporterAPI(viewsets.ModelViewSet): queryset = Reporter serializer_class = ReporterSerializer When I run python manage.py runserver I'm getting the following error, AttributeError: type object 'Reporter' has no attribute 'model' What I am missing here? Any help would appreciated. -
Django uggetext as __ instead of _ breaks makemessages
I just came across a weird bug (?) where I initially had from django.utils.translation import ugettext as _ Which I changed for from django.utils.translation import ugettext as __ But, surprisingly, running ./manage.py makemessages --all after doing that breaks all translations, they basically get all commented in my .po files, as if they weren't recognized as being translations anymore. Going back to _ and running makemessages fixes it. I don't quite follow why the name of the variable matters, and I wonder how I should name my ugettext and ugettext_lazy when I need both, for consistency. -
spacy 2.0.12 / thinc 6.10.3 crashing django on heroku
I'm having an issue with v2.0.12 that I've traced into thinc. pip list shows me: msgpack (0.5.6) msgpack-numpy (0.4.3.1) murmurhash (0.28.0) regex (2017.4.5) scikit-learn (0.19.2) scipy (1.1.0) spacy (2.0.12) thinc (6.10.3) I have code that works fine on my Mac, but fails in production. The stack trace goes into spacy and then into thinc -- and then django literally crashes. This all worked when I used an earlier version of spacy -- this has only come about since I'm attempting to upgrade to v2.0.12. My requirements.txt file has these lines: regex==2017.4.5 spacy==2.0.12 scikit-learn==0.19.2 scipy==1.1.0 https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz The last line pulls the en_core_web_sm down during deployment. I'm doing this so I can get those models loaded on Heroku during deployment. I then load the parser like this: import en_core_web_sm en_core_web_sm.load() Then the stack trace shows the problem here in thinc: File "spacy/language.py", line 352, in __call__ doc = proc(doc) File "pipeline.pyx", line 426, in spacy.pipeline.Tagger.__call__ File "pipeline.pyx", line 438, in spacy.pipeline.Tagger.predict File "thinc/neural/_classes/model.py", line 161, in __call__ return self.predict(x) File "thinc/api.py", line 55, in predict X = layer(X) File "thinc/neural/_classes/model.py", line 161, in __call__ return self.predict(x) File "thinc/api.py", line 293, in predict X = layer(layer.ops.flatten(seqs_in, pad=pad)) File "thinc/neural/_classes/model.py", line 161, in __call__ … -
add search bar to django website
I am using Django to make a website which includes a basic search bar. This search bar simply takes the word(s) entered by the user and returns several search results (Posts), on the same page, that are relevant to the search instead of the default results, ordered by date. I have tried using multiple resources to get something to work, including the official Django documentation, however, the information is only partial or not exactly what I am looking for. #models.py class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() image = models.ImageField(upload_to="post_image/", default='blankImg.jpg') Views.py that I tried but not exactly sure how to use. Here I am trying to take all of the "Post" objects and weigh the more relevant searches (searches that match closer to the title as opposed to the content/body) and then return a list of those objects. #views.py from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.views.generic import ListView from news.models import Post class newsSearchListView(ListView): """ Display a News List page filtered by the search query. """ model = news paginate_by = 10 def get_queryset(self): qs = news.objects.published() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') body_vector = SearchVector('body', weight='B') vectors … -
Can I use sublime Text build system to execute manage.py commands in a docker container?
I'm writing unit tests for a Django App. I'm using sublime text. My app is set up to run in a docker container. To run the tests currently I have to go into the docker container sudo docker exec -it {containerID} /bin/bash and then run python manage.py test polls. Is there some way to do this from sublime text's build system? I know I could set up the whole app to run out side the container then just command-B to build and run locally, but I want to run in the container. -
How to create generic ics file which works for gmail, yahoo, outlook and other clients, while send from programming application?
I have web application based on django framework. Application creates ICS file by cal python package. We are sending this ICS to differnt clients email ID(gmail, outlook, yahoo etc) So I am facing problem in below Scenarios Scenario - 1. Create Event 2. Update all Occurrences or update particular occurrence of event 3. Cancel all Occurrences or cancel particular occurrence of event. Create - ICS file is working with Gmail and outlook but not with yahoo when i send this from web application, and if I send the same file from other clients like gmail it creates event in yahoo also. Update - Same scenario is applicable for update case. Not working with yahoo. Cancel - In cancel case ICS is not working for any client. I have few point in Cancel file like - METHOD : CANCEL UID : Same as sent in create and update case. Above two are mandatory fields STATUS, SEQUENCE, RRULE - Is this required? If SEQUENCE is required then what will be the value of this variable. Please give your suggestions. -
Uncertainty after associated User as a Foreign Key in another model
I have a question about associated User as a Foreign Key in another model. when i associated User as a Foreign Key in my Post model, i save with: post.user = self.request.user i want the username be exactly the user that post something, and it should not allow to change and edit the user right, because if i can change the user in the specific post, then the post is not belong to that person already. but when i go to the admin and try to change the user in post model, i can edit/change the user in the specific post and the post is no longer the same person, should this suppose to happen or i miss something? Also, i didnt receive any error when i save the post, everything is fine. Thank you, hope you guys understand what i saying. models.py class PostModel(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length =200, unique = True) created_at = models.DateTimeField(auto_now=True) file = models.FileField(upload_to="post", validators=[FileExtensionValidator(allowed_extensions=['gif','png','jpg','jpeg','mp4'])]) description = models.TextField() def __str__(self): return self.title views.py class PostView(LoginRequiredMixin,generic.CreateView): model = PostModel fields = ['title','file','description'] template_name = 'post/post.html' success_url = reverse_lazy('home') def form_valid(self, form): post= form.save(commit=False) post.user = self.request.user post.save() return super(PostView, self).form_valid(form) -
Django static files 404 not found
I have read all of the similar questions regarding this and still can't find an answer. I downloaded a template from HTML5 and all of the required CSS, JS and images but when I run the server I get: ** Not Found: /erthreal/assets/js/main.js [04/Aug/2018 12:02:40] "GET /erthreal/assets/js/main.js HTTP/1.1" 404 2126 [04/Aug/2018 12:02:40] "GET /erthreal/images/gallery/thumbs/06.jpg HTTP/1.1" 404 2159 [04/Aug/2018 12:02:40] "GET /erthreal/images/gallery/thumbs/07.jpg HTTP/1.1" 404 2159 ** I have the following written in my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'erthreal/erthreal/templates/' ], STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/',), 'erthreal/static/erthreal', ] In my index.html: {% load static %} <!DOCTYPE html> <html> <head> <title>personal</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="{% static "erthreal/assets/css/main.css" %}"/> <noscript><link rel="stylesheet" href="erthreal/assets/css/noscript.css" /></noscript> </head> I'm pretty sure the problem is in my views.py: from django.shortcuts import render, HttpResponse def index(request): index = Index.objects.all() return render(request, 'erthreal/templates/index.html') I have read through all of the documentation both on the django website and the howto folders (which are pretty much copies of each other), but cant find an answer on how to fix it. This is my folder layout: erthreal/ static/ erthreal/ assets/ CSS/ fonts/ js/ sass/ images/ templates/ erthreal/ index.html … -
Is it bad practice to call model on controller (view) in django?
The question is not only about django though...I know the MVC mantra that claims that controllers should be thin and models fat. But speaking of the case I'm dealing with right now. I neeed to do such a simple thing as get an object from the DB by its id which means I have to use something like MyModel.objects.get(id=object_id), I would like to put this code into MyView (read controller) but I'm not sure if it's a good idea. On the other hand serializers are for serializing/deserializing data and all calls to models should be inside views. Is it right? -
How to increase performance for data insertion in Sqlite db in Django
In my Python- django app, I have to insert atleast 10 Lac records, 15 columns each in 3 different tables. Currently i am using Django Import- Export library to import data into models from csv and xlsx files. The functionality is working fine but it is taking too much time to insert this bulk data I have started with 1 Lac records in one table but since 3-4 hrs it is just updating the records. Is their any way in which i can bulk upload data from csv or xlsx files into django model. Thanks for the support. -
django-admin startproject does not create manage.py
I am trying to create a new django project. I just installed python 2.7.15, and virtualenv and django 1.5. I don't have any other version installed. When I run python django-admin.py startproject myproject, it creates a new folder myproject -- myproject ---- init.py ---- .... But, manage.py is missing in the top folder, what am I doing wrong? thanks.