Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import error in Django url.py
I just started a django project but i cant import a function from views.py. I have done some projects with very similar settings but without any problems. I'm using virtualenv(and it is activated), windows10, pycharm. #urls.py from django.conf.urls import url from django.contrib import admin from WebShop.main_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), ] #views.py def index(request): return HttpResponse("<h1>Hi</h1>") #cmd File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\b021l\Desktop\practice\django\WebShopProject\env\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen … -
iOS api call to local RESTful Django fails
Hi all first time posting a question. Long time reaping the benefits of other questions so I'd like to preface this with a thank you to everyone who answers questions on here. Onto my question. So I've set up a local Django server that returns a JSON object to my browser properly. I've also set up an API querying scheme in IOS using swift that work properly with the tutorials HTTP server. However when I try to call my own local server my data and response objects are nill My Django view.py and url.py files from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from snippets.models import Snippet from django.http import Http404 from snippets.serializers import SnippetSerializer class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class SnippetDetail(APIView): """ Retrieve, update or delete a snippet instance. """ def get_object(self, pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http404 def get(self, request, pk, format=None): snippet = self.get_object(pk) serializer = SnippetSerializer(snippet) return Response(serializer.data) def put(self, request, pk, format=None): snippet … -
How to store html markups in Django's database
Recently I've started to learn Django, I've decided to make a sample blog website. I've made Post model which creates and publish post. But there's a problem, I've no idea how to attach html markups to my Post object's attribute for instance "text". Here is how I've made Post model: from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) introduction = models.TextField() text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
after login redirect to another page
Im using django 1.10 embeded authentication. I want login redirect to another page and pass the variables too. Ive made my views but i have all the time error 404. I read about "login-redirect-url" and default is accounts/profile. Ive made a folder inside my templates. Is this correct way? i store it in Django/myapp/myapp/templates/accounts/profile/home.html error:"The current URL, accounts/profile/home.html, didn't match any of these." views.py def home(request): username = None if request.user.is_authenticated: username = request.user.username return redirect('accounts/profile/home.html',{'username': username}) else: return redirect('/accounts/profile') myapp/ulrs.py url(r'^accounts/profile/$', views.home, name='home') any suggestions will be welcome.If im doing this wrong please provide me an example. Thanks. -
How to use django (python) forms with django-rest-auth?
I am trying to build a Django application with RESTful API (django-rest-framework) and I would like to use django-rest-auth plugin. There is a demo app (http://django-rest-auth.readthedocs.io/en/latest/demo.html) but it is pretty ugly. It has a HTML forms hardcoded in templates, instead of Django python forms. Do you know any example (or can you provide one) how to make a registration and login form for django-rest-auth (in forms.py)? -
command "python setup.py egg info" failed with error code 1 in ~~
[root@myserver bin]# pip3.5 install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-ahudhqst/MySQL-python/setup.py", line 13, in <module> from setup_posix import get_config File "/tmp/pip-build-ahudhqst/MySQL-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ahudhqst/MySQL-python/ [root@myserver bin]# I failed to install MySQL-python (for django). Can I know why this error occur? I'm using centos 6.5 -
Django back end with a React front end
The idea I've started off building this social media kind of website, which includes the basic social media pages such as a profile, a status feed, searching, events, and so on. Each page is a seperate django template and data is visualized by using variables in the django template engine. But at this point, I want to change these static pages to something more dynamic, using ReactJS. But how? I would like to make the pages dynamic, but it should still be a multi page website with urls like /user/<id>. I came up with the following option: A template for each page. Each page having one bundle. Let Django handle the routes. Create a seperate Django template for each page, just like a normal Django application would do. Use django-webpack-loader to load bundles. Each page has a seperate bundle. Bundles are created by adding multiple entries in webpack.config.js. This can result in a fairly large amount of entry points when we have 40+ different pages. URLs are handled by Django and are accessible by React via a public javascript variable in the template. Example. And other initial data for the page (such as username, avatar, profile information) are also loaded … -
User-uploaded images not saving to media folder in production
I'm building a Django website where users can upload an image via a form that distinguishes them on the site. These are saved in the /grad/media/ folder (where grad is the name of the app). This is the code that accomplishes this: uni_object = University.objects.get(user=request.user) logo = uni_object.logo if request.method == "POST": form = UpdateUniversityForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data request.user.email = data['email'] request.user.save() uni_object.university_name = data['university_name'] uni_object.website = data['website'] if request.FILES and request.FILES['logo'] != '': new_logo = data['logo'] image = Image.open(new_logo) image = image.resize((400,400), Image.ANTIALIAS) thumb_io = StringIO.StringIO() image.save(thumb_io,format='JPEG') new_file_name = str(int(time.time())) thumb_file = InMemoryUploadedFile(thumb_io, None, '{0}.jpg'.format(new_file_name), 'image/jpeg', thumb_io.len, None) uni_object.logo = thumb_file uni_object.save() updated = True logo = uni_object.logo Essentially I need to convert it into a 400x400 square, and then save it. This code will work on localhost, and the file will be saved correctly. However in Heroku with DEBUG=False: The same code will not save the picture in the media folder Not even by saving a pic manually via the admin panel will the pic end up in media folder Even if the photo exists in the media folder, it will not be rendered on the site. The media folder is pushed to Heroku, so … -
How to make a signup and login form acessible on everypage that i may use modals Django 1.8
I have implemented both login and signup forms in my Django app. Currently they are being rendered to signup.html and login.html pages by corresponding views as below def user_login(request): if request.method == 'POST': #do some authentication stuff login as stay on the page login_form = LoginForm(request.POST) if login_form.is_valid(): cleaned_form_data = login_form.cleaned_data user = authenticate(username = cleaned_form_data['username'], password = cleaned_form_data['password']) if user is not None: #proceed to login if active if user.is_active: login(request,user) #return HttpResponse('Successfully Logged In') messages.success(request,'Login successfull') else: return HttpResponse('Inactive User') else: return HttpResponse('Invalid Login') else: login_form = LoginForm() template = 'accounts/login.html' context = {'form':login_form,} return render(request,template,context) def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): new_user = form.save(commit = False) password = form.cleaned_data['password'] new_user.set_password(password) new_user.save() return render(request,'accounts/reg_success.html',{'new_user':new_user,}) else: form = RegisterForm() template = 'accounts/register.html' context = {'form':form,} return render(request,template,context) How do i implement this so that i have have the forms sent to every page and can user Javascript Modals to login and signup users. Thanks. -
I am new to Django. Is there any include directive in Django?
Is there a way to include an html file containing JS code and map it to a django view? Or everything should be done via templates? What are django templates?How do I convert an html file to django view? -
How to backup Django database on Heroku into JSON format?
I want to dump my Heroku (PostgreSQL) database into JSON format. I used to do this in a view and return the JSON string as HttpResponse like this: from django.shortcuts import render from myapp1.models import * from myapp2.models import * from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect from django.contrib import auth from django.contrib.auth.models import User from django.db.models import get_app, get_models # deprecated? def print_all_objects_in_app(appname): app = get_app(appname) all_objects=[] for model in get_models(app): all_objects += list(model.objects.all()) JSONSerializer = serializers.get_serializer("json") json_serializer = JSONSerializer() return HttpResponse(json_serializer.serialize(all_objects)) It used to work for me (I just need to copy paste the page content into a JSON file manually which is OK for me). However, apparently get_app and get_models are not working anymore. Another option is to call heroku run python manage.py dumpdata > dump.json but I can't retrieve the newly (and remotely) created file with heroku git:clone -a myapp. So is there any way to make any of these two methods work? Thanks, -
Reverse url in django signal
I'm trying to send an email with my website address from django signal. I found this question: http://stackoverflow.com/a/15521046/2385132 and proceeded as was advised in the accepted answer, but when using that code, I'm getting this error: AttributeError: 'NoneType' object has no attribute 'get_host' Which is coming from the get_current_site in my code: @receiver(post_save, sender=MyModel) def post_obj_save(sender, instance: MyModel, **kwargs): def _get_html(obj: MyModel): return render_to_string('confirmation_email.html', _get_context(obj)) def _get_context(obj: MyModel): current_site = get_current_site(request=None) domain = current_site.domain action = reverse('obj_activation', request=None, format=None, kwargs={}) url = '{protocol}://{domain}/{action}'.format(protocol=PROTOCOL, domain=domain, action=action) return { 'header': _('Thank you for registering with ASDF.'), 'prompt': _('In order to be able to log in into ASDF administrator panel, you have to activate your account using'), 'link_name': _('this link'), 'activation_url': url } send_mail( _('ASDF account activation'), _get_html(instance), EMAIL_FROM, [obj.owner.email], fail_silently=False, ) So the question is: how do I get full url of my view in a signal? Btw. I'm using django-rest-framework. -
Providing initial values to formset in django admin inline for a custom form
I have a model "Timings" that goes like this. weekday = models.CharField(choices=constants.WEEKDAYS, max_length=10) start_time = models.TimeField() end_time = models.TimeField() lab = models.ForeignKey('Lab') I had to override the form in django admin and display it as inline in Lab form. I created a form for Timings model and excluded all model fields and introduced some form fields. day = forms.CharField(label="Day", required=False) start_session1 = forms.TimeField(label="Session-1 Start", required=False) end_session1 = forms.TimeField(label="Session-1 End", required=False) start_session2 = forms.TimeField(label="Session-2 Start", required=False) end_session2 = forms.TimeField(label="Session-2 End", required=False) My purpose here is to display a table like structure to user in inline. & rows for the 7 days in the week with storing upto 2 sessions per day. I have overridden the form's save method. Now my instances are getting saved in the DB but in edit mode, I need to display the already present instances in the DB according to the same structure of the form. I ran over the concept of formsets but could not figure out how to override the initial values dynamically. Can somebody help? Stuck at this problem for a week. -
How to insert csrf token in LPology/Simple-Ajax-Uploader
How to insert csrf token in LPology/Simple-Ajax-Uploader? var uploader = new ss.SimpleUpload({ button: btn, url: 'file_upload.php', name: 'uploadfile', multipart: true, hoverClass: 'hover', focusClass: 'focus', responseType: 'json', startXHR: function() { progressOuter.style.display = 'block'; // make progress bar visible this.setProgressBar( progressBar ); }, onSubmit: function() { msgBox.innerHTML = ''; // empty the message box btn.innerHTML = 'Uploading...'; // change button text to "Uploading..." }, onComplete: function( filename, response ) { btn.innerHTML = 'Choose Another File'; progressOuter.style.display = 'none'; // hide progress bar when upload is completed if ( !response ) { msgBox.innerHTML = 'Unable to upload file'; return; } if ( response.success === true ) { msgBox.innerHTML = '<strong>' + escapeTags( filename ) + '</strong>' + ' successfully uploaded.'; } else { if ( response.msg ) { msgBox.innerHTML = escapeTags( response.msg ); } else { msgBox.innerHTML = 'An error occurred and the upload failed.'; } } }, onError: function() { progressOuter.style.display = 'none'; msgBox.innerHTML = 'Unable to upload file'; } }); }; Full example: https://github.com/LPology/Simple-Ajax-Uploader/tree/master/examples/basic_example I use Django 1.9 on the backend instead. And my frontend form looks like: <form>{% csrf_tocken %} ... </form> -
Empty CharField with null=True returns NoneType Django 1.8
As fas as I understand, this CharField must return null when it's not filled with data, but instead it returns None. What is wrong? number_of_likes = models.CharField(max_length=1000, blank=False, null=True) -
Django Database Settings : Can we keep default database as empty dict? [Django 1.8]
I am getting the following error: ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE VALUE. My settings.py looks like: DATABASES = { 'default': { }, 'postgres': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app', 'USER':'user', 'HOST': 'localhost', }, 'cassandra': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'app', 'HOST': '127.0.0.1', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 }, 'connection': { 'consistency': ConsistencyLevel.LOCAL_ONE, 'port': 9042, 'retry_connect': True # + All connection options for cassandra.cluster.Cluster() }, 'session': { 'default_timeout': 10, 'default_fetch_size': 10000 # + All options for cassandra.cluster.Session() } } } } runserver, syncdb are working fine. The error pops up when I access the index page. Is there something I am doing wrong? Thanks in advance :) /Saha -
Filtering against the URL (REST framework)
i want to pass data from url in view. i read this and try to write! but i got a error : __init__() takes 1 positional argument but 2 were given serializer.py : class ContactsDetailsSerializer(serializers.ModelSerializer): class Meta: model = Contacts fields = ('id', 'profile_id', 'tel','email') views.py: class ContactsDetailsViewSet(generics.ListAPIView): serializer_class = ContactsDetailsViewSet def get_queryset(self): """ This view should return a list of all the purchases for the user as determined by the username portion of the URL. """ queryset = Contacts.objects.filter(profile_id=self.kwargs['profile_id']) return queryset urls.py: router = routers.DefaultRouter() router.register(r'profiles', views.ProfileViewSet) # router.register(r'users', views.UserViewSet) router.register(r'members', views.MemberViewSet) router.register(r'files', views.FilesViewSet) router.register(r'contacts', views.ContactsViewSet) router.register(r'products', views.ProductsViewSet) router.register(r'stories', views.StoriesViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('allauth.urls')), url(r'^', include(router.urls)), url('^test/(?P<profile_id>.+)$', views.ContactsDetailsViewSet), //here url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] anybody can help? how to pass data(by REST framework) ? -
FormView CBV change ModelForm per request
I am trying to build a Wizard for populating data in to DataBase. I try the session.Wizard with out success plus I don't think this is what ti need. correct me if I am wrong. so basically my database have some tables which needs to be fill, because of the joints need to be done, I wanted to make a nice wizard which takes you along the way. so I have a base template which would have steps, sometimes there would be no need in creating a new data if exists all ready. so I have made a display of each table on template so user can check if the table contain what he needs for next step or he needs to create it. I made a cbv FormView and I am trying to get the step from GET and load the needed ModelForm model.py Class A(models.Model): user = CharField() class B(models.Model): pupy = CahrField() form.py AForm(forms.ModelForm): class Meta: model=A fields = ['user'] BForm(forms.ModelForm): class Meta: model=B fields = ['pupy'] views.py class Wizard(FormView) template_name = 'test.html' def get(self, request, *args, **kwargs): self.step = self.request.GET.get('step') self.form_class = FORM[self.step] # FORM = dict {'step': ModelForm} def form_valid(self, form): self.object = form.save(commit=False) self.object.save() … -
Django Avatar Not Creating Resize files
On my test setup my django avatar scripts are working as they should. I.e. when I upload a profile picture it is updated and can be seen throughout the site as expected. I can also amend the picture and it works. When I upload to my main site everything still works. However, if I then change an avatar profile on the live site all it does is copy the file to the root of the username avatar folder but does not create any resized variants or show on the site. For example if you were to goto str8red.com it would show tingeyal on the right without an image (tingeyal is the ONLY user to try to upload the image on the live server). If anyone would like some code or settings just ask, was unsure what you may require, many thanks, Alan. -
How include jQuery-File-Upload in my model?
friends. I am try using jQuery-File-Upload in my project. Project including two apps: Orders, Fileupload. Orders have a model: from fileupload.models import Picture class Order(models.Model): title = models.CharField(max_length=200, verbose_name=u'Название') born = models.DateTimeField(verbose_name="День создания", default=timezone.now) user = models.ForeignKey(User, verbose_name=u'Пользователь') email = models.EmailField(verbose_name=u'Почта') name = models.CharField(max_length='200', verbose_name='Имя представителя') phone = models.CharField(max_length='12', verbose_name=u'Телефон') city = models.CharField(max_length='100', verbose_name=u'Город') body = models.TextField(verbose_name=u'Описание проекта') files = models.ForeignKey(Picture, default='', verbose_name=u'Файлы проекта') I want to insert jQuery-File-Upload in my model. How to do it? -
Django pip freeze results in empty file
I'm following the tutorial to deploy Django applications on Heroku. In the 5th line of code, it says pip freeze > requirements.txt but when I run it (from the venv), the requirements.txt file is empty! It produced 6-7 dependencies with the same code before. How can I fix this? Thanks, -
Why is Nginx returning zero length response with X-Accel-Redirect?
I'm stumped on this simple problem. I'm using Nginx with Django and I would like to use the X-Accel-Redirect header to serve up files from a protected location. The Django app manages to locate the file and set the Content-Length header along with the X-Accel-Redirect header (I see them both in the response in Chrome), but the actual response is empty and Chrome gives me the net::ERR_CONTENT_LENGTH_MISMATCH error. I see nothing logged in the nginx access.log or error.log files. Here is my nginx config file: server { listen 9000; server_name server_domain_or_IP; sendfile off; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/partie_base_tronc; } location /app/ { alias /home/username/partie_web_tronc/; } location ^~ /temp/ { internal; root /home/username/partie_base_tronc; } location / { include proxy_params; proxy_pass http://unix:/home/username/webapp.sock; } } I initially thought it was a naming issue, but if I delete the one line internal in the config, and I type in [site address]/temp/mypdf.pdf in my browser, for example, I can access the file just fine. But if the X-Accel-Redirect header is /temp/mypdf.pdf, then it doesn't work. Any ideas? -
request.user.first_name does not working in django
I'm trying to build a authentication based view! My html code is: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> {% if request.user.is_authenticated %} <ul class="menu"> <li {% if section == "dashboard" %}class="selected"{% endif %}><a href="{% url "dashboard" %}">My dashboard</a></li> <li {% if section == "images" %}class="selected"{% endif %}><a href="#">Images</a></li> <li {% if section == "people" %}class="selected"{% endif %}><a href="#">People</a></li> </ul> {% endif %} <span class="user"> {% if request.user.is_authenticated %} Hello {{ request.user.first_name }}, <a href="{% url "logout" %}">Logout</a> {% else %} <a href="{% url "login" %}">Log-in</a> {% endif %} </span> </div> </body> </html> Here the line: request.user.first_name supposed to show the logged in username according to Django By Example book. also when I'm changing the password in firefox it shows this massage: But in chrome it works fine in changing password, although the name is not showing in both browser! My Login page html code is : {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% else %} <p>Please, … -
Django: How to use request.POST in a delete view
I have a form sending data to a view via POST method. My problem is that I cant access the form's post data in the deleteview. After the song is deleted, I want the user to be sent back to the album-detail page to which the song belongs. My code is as shown below: The form (inside album_detail.html): <form action="{% url 'music:delete-song' pk=song.pk album_id=song.album_id %}" method="POST"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ song.album_id }}" /> <button type="submit" class="btn btn-danger btn-xs" role="button">Delete</button> </form> The urls.py: #---- app_name = 'music' urlpatterns = [ #---- url(r'^album/(?P<pk>[0-9]+)/detail/$', views.AlbumDetail.as_view(), name='album-detail'), url(r'^song/(?P<pk>[0-9]+)/delete/(?P<album_id>[0-9]+)/$', views.SongDelete.as_view(), name='delete-song'), ] And finally the view: class SongDelete(DeleteView): model = Song album_id = request.POST.get('album_id') success_url = reverse_lazy('music:album-detail', kwargs={'pk': album_id}) The album_id can not be set as above. How can I set the album_id to the post data album_id from the form, so that the user is sent back to the album-detail URL? -
Django all-auth. How to renew Facebook token?
I want to use all-auth token that stored in db to perform queries to graph api. How can I renew all-auth token when it becomes not valid ?