Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I store form input in a session in Django?
Who can help me with the following challenge? I have a registration template where users can sign up. They are then redirected to an url with a payment button and activated when a successful payment is made. In the HTML template I store the username in a custom field within the payment button which is used to later activate the account. Now since the user is not activated/logged in yet, I can't call the user object yet like {{user.username}}. So I want to try sessions to solve this and capture the username during registration to retrieve this session variable and put it in my custom field on a different page. But how? I tried using request.session but I’m not sure where to fit this the files below and then how to call this variable in the html template. Any advise or help is greatly appreciated! Here is my regbackend.py class MyRegistrationView(RegistrationView): form_class = UserProfileRegistrationForm def register(self, form_class): user_package.username = form_class.cleaned_data['username'] And here my forms.py class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['username', 'email'] Here my registration.html <form method="post" action="."> {% csrf_token %} {{ form.username|as_crispy_field }} <input class="btn btn-success" type="submit" value="{% trans 'Submit' %}" /></form> And finally my HTML … -
right username password not login django
I am developing a small website with django and I am using the built-in login view. When I register a standard user and then try to login with the right credentials it shows me the login error "please enter a correct username and password". This problem doesn't occurr with the superusers that I created. The can login with the right credentials without any error message showed. This is the views.py with my registration view. from django.shortcuts import redirect, render, get_object_or_404 from django.contrib.auth.models import User from .forms import UserForm def register_user(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): user = form.save() return redirect('user_profile', pk=user.pk) else: form = UserForm() return render(request, 'interport/register_user.html', {'form':form}) The admin.py: from django.contrib import admin from django.contrib.auth.models import User forms.py: from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password',) urls.py: from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'^accounts/login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'), url(r'^register_user$', views.register_user, name='register_user'), url(r'^$', views.home, name='home'),] the template for login: {% extends "interport/base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="center col s4 offset-s4 card-panel … -
Unique identifier key for (sub)identical post titles with same permalinks (slug) in URLs
After spending several hours searching and getting results specific to Wordpress only, I need to ask the question here. I am developing a web application where a user can create and publish posts. A field with name permalink is created in database where sanitised version of first few words of the post title (slug) is stored which will be used for SEO-friendly URL generation. For example, a post with name 'Working with suitable elements' will generate URL localhost/posts/working-with-suitable. What if another user creates and publishes a post with name 'Working with suitable devices' or may be the same name as the already published post 'Working with suitable elements' again? Usually I have seen some random alphanumeric characters appended to the URL, like localhost/posts/working-with-suitable/hY8uuAQ to make the URLs unique. So the question is (I) should I need to create another column (along with permalink) in my posts table which will contain alphanumeric characters randomly generated at the time the post is published and then use them for URL generation, Or (II) Use the primary key post_id instead of random characters, Or (III) Some hash or base64 conversion (as I read somewhere) of primary key post_id on the fly each time a … -
Django - in the model, created_at is a UNIX timestamp
I am new to Django. I would have better grasp of this in Rails but am not familiar enough with all the libraries and converstions in Python / Django. I have a model: class Status(models.Model): created = models.DatetimeField(auto_now_add=True) This results in the format: "created": "2017-01-06T22:21:51.531723Z" I was hoping to see if before saving to the DB that it stores as a UNIX value? I stumbled across this django Datefield to Unix timestamp but it was asked 7 years ago and I'm trying to do this in the model and not the template. This looked promising http://stackoverflow.com/a/34843855/3007294 but can't get it working. Every time I try to create a Status object, I get this error: Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]. My intentions are to not have to enter this every time a Status object is created. Thanks - -
Why this Django error "Too Many Values to Unpack"?
I have a Django view that I'm calling via an Ajax function in a template. My template has a 'Country' pulldown and a 'Region' (or State) pulldown. When the user clicks on a Country, I want to use an Ajax function to fetch all the regions (or states) in that country and populate a 'Region' dropdown with that data. However, when my view executes and tries to return the query set, I'm getting this error: ValueError: too many values to unpack Here is the template tag and Ajax function: # demo.html <select id="id_country" name="country" onchange="getState(this.value);"> <option value="" selected="selected">Please choose...</option> <option value="US">United States</option> <option value="GB">United Kingdom</option> <option value="CA">Canada</option> </select> <script> function getState(val) { $.ajax({ type: "GET", url: "/demo/get_region", data:'country_id='+val, success: function(data){ $("#id_region").html(data); } }); } </script> Here is the view: # views.py from location.models import CountryRegion def get_region(request): country_id = request.GET.get('country_id', None) country_region = CountryRegion.objects.filter(country_cd=country_id) # Error occurs here on the return return country_region The model (which I realize isn't normalized) looks like this: class CountryRegion(models.Model): country_cd = models.CharField(max_length=2) country_name = models.CharField(max_length=50) region_cd = models.CharField(max_length=3) region_name = models.CharField(max_length=50) A database record looks like this: id country_cd country_name region_cd region_name 59 US United States NY New York Why is this error occurring? … -
Approach to running long tasks on django to produce a dashboard
I have a django site, I currently use it as a frontend to kick backend tasks (using celery). The tasks usually take about 5 minutes and produce a .txt file. I want to run the same analysis but instead of spitting a .txt file I want to display data on a dashboard. I'm concerned about time-out issues as processing takes about 5min. Alternatively, could I set up a 'loading' message to prevent timeout issues? Best practices, ideas or suggestions are highly appreciated! -
postgres - Creating aSnew user
A horrible curse was put on me the moment I got a new laptop with UEFI boot mode that locks me into Windows. Everything is so horrifically awkward and complicated now, I'm on the verge of a nervous breakdown. So I setup a Ubuntu 16 VM with Vagrant and I used a prebuilt box I got on the atlas. The user which setup for postgres is django. I need to create a new database owned by postgres, so I ran: django=> CREATE DATABASE mydb OWNER postgres and I get this error: ERROR: must be member of role "postgres" So I decided to just create the database thinking that I could add postgres as a user with all privileges to it. But heres what happens: mydb=> CREATE USER postgres; ERROR: permission denied to create role So I read that I need administrative privileges to create a new user. So I run su and login as root. The problem is root isn't authorised to login to psql. So I try running su - django, but django isn't a user, so I created the Ubuntu user django and added it to the sudoers, then run su - django and login into psql like … -
How to join related objects and render them in template?
I have to related models: class Poll(models.Model): creator = models.ForeignKey(User, blank=True, null=True) title = models.CharField(max_length=300) pub_date = models.DateTimeField('date published') published = models.BooleanField(default=True) class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=300) votes = models.IntegerField(default=0) My problem is how to list all polls along with their respective choices in the template. The ORM query that I have right now is: polls = Choice.objects.select_related('poll') And in template: {% for p in polls %} <li>{{p.choice_text}}</li> {% endfor %} But this solution only lists the choices. What I want is to render choices related to each poll. How can I achieve this? -
How Can I Debug `IOError: cannot identify image file` in Django with Pillow
I wrote a simple module that uses Pillow to facilitate common image-related tasks and use it in several image-processing scripts without issue. However, when I use it in a web application, I get the following: IOError: cannot identify image file <open file '/tmp/tmpXjel94', mode 'rb' at 0x2c74930> A stipped example of my image module: from PIL import Image as PILImage class Image(object): def __init__(self, src): self.image_fh = open(src, 'rb') self.image = PILImage.open(self.image_fh) So the first thing this class does is create an image with PIL.Image.open. In my view, I have a method to handle image uploads. Because my Image class reads from the file system, I create a temporary file in my view, and pass its path. def upload_image(self, request): # Get the InMemoryUploadedFile object. image_file = request.FILES['image'] # Create a named temporary file to guarantee a path on the file system. temp = tempfile.NamedTemporaryFile() temp.write(image_file.read()) temp.flush() # Instantiate my Image class and raise the Exception I'm posting about. image = Image(temp.name) I first thought that perhaps the data from the client wasn't what I was expecting, so in my upload_image method, I added the following few lines of code between writing the temporary file and creating an Image object. … -
How to find out decimal-point format currently used by authorized django user?
in Django 1.10 & py 2.7 how can I find out the current authorized user's locale decimal-point, i.e. does the current user use ',' or '.' as decimal separator (should it be 11,23 or 11.23)? I am using _thread_locals for some other user settings, all things works fine and ',' vs. '.' is used correctly everywhere - but I now need to find out inside a view which is used and have not been able to figure this out... BTW - each authorized user has own locale so one user can have ',' and another '.' depending on the user locale. / Jens -
PyCharm is changing the default encoding in my Django app
I am running into an issue where plyplus is erroring out with: File "/Users/FOO/.virtualenvs/ff/lib/python2.7/site-packages/plyplus/grammars/__init__.py", line 6, in open return _open( os.path.join(os.path.dirname(__file__), grammar_name) ) LookupError: unknown encoding: [06/Jan/2017 22:27:45] "GET / HTTP/1.0" 500 200257 If I add import locale; print 'LOCALE: [' + locale.getpreferredencoding() + ']' to my settings.py and run the Django server from PyCharm (2016.3.1) I see LOCALE: [] this when I start my server. If I run the server from the command line, I see LOCALE: [UTF-8] and the plyplus issue goes away. Can anyone tell me what I need to do in PyCharm to get the proper encoding set in my Django server? -
How to filter private user to user interactions?
I'm creating a private user to user chat system, for now I'm displaying all of the objects through the views in the profile of the user like this user = userComment.objects.all(). The problem with that is that everyone can read everyone's chat messages and I would like to filter it so only the recipient and the sender can read the messages they send to each other. If if filter it like so : userComment.objects.filter(sender=request.user) then only sended message will be shown. If I filter it like that : userComment.objects.filter(recipient=request.user) then only received message will be shown. I would like to filter it so only the recipient and the sender can read their chat. Why do I want to filter it into one variable ? So it can look like this : And not like this : models.py class userChat(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, blank=True, null=True, related_name="receiver") sent_at = models.DateTimeField(auto_now_add=True) comment = models.TextField(max_length=255, null=True) def __str__(self): return str(self.sent_at) template/file.html {% for user in users %} {% if user.client == request.user %} <li style="text-align:left; background:yellow;"> <p>from {{ user.client }} to <strong>{{ user.worker }} </strong> | {{ user.sent_at }}</p> <p>{{ user.comment }}</p> </li> {% else %} <li style="text-align:right; background:#eaeaea;"> <p>from … -
Connecting python back-end to local web server
Let me apologize in advance if this is a beginner question or too vague. I am familiar with Python but very new to web development. I have developed a python command-line application. I would like to develop a browser-based UI for the application that may be hosted on a raspberry pi and accessed on a local network. Could you point me in the right direction for how to go about this? What are common/popular approaches? E.g., might I utilize Django, Apache, and Bootstrap? Are there any popular tutorials or resources out there that I should be aware of? -
Graphen-Django: Concepts of Connections, Edges, and Nodes
I just started experimenting with graphene-django/GraphQL and am pretty confused about the relay library that has been brought in for graphene-django. After running through the cookbook example (implementing it with my own models) and running a test query, upon POST the query gets transformed to a strangely nested object with edges and nodes. What are these and what are they doing? { companies { edges { node { id } } } } -
How can I clear only one specific form field after submit?
I'm creating a chat application and there are 2 fields, receiver's name and body, I would like to clear the body without clearing the receiver's name after form submit, how can I achieve that ? views.py if request.method == 'POST': form = userCommentForm(request.POST, request.FILES) if form.is_valid(): form.save(client=request.user) > clear body field. forms.py ("worker" field is the receiver's name.) class userCommentForm(forms.Form): worker = CommaSeparatedUserField(label=_(u"worker"), widget=forms.TextInput(attrs={'readonly': 'readonly'})) comment = forms.CharField(label=_(u"comment"), widget=forms.Textarea()) def save(self, client): workers = self.cleaned_data['worker'] comment = self.cleaned_data['comment'] message_list = [] for worker in workers: msg = userComment(client=client, worker=worker, comment=comment,) if None is not None: msg.parent_msg = None None.save() msg.save() message_list.append(msg) return message_list form.save(client=request.user) Any suggestions ? -
Select Checkbox Values Already Saved on Editing in Form
A user will be able to list his property and he/she will be able to edit the listing. The Problem On editing, all other fields will show data already saved by the user and only amenities field won't display 'values already selected'. All the values of the amenities field are saved in a TextField and user can select multiple items via 'CheckboxSelectMultiple' widget. Models class Motel(models.Model): user= models.ForeignKey(User) name= models.CharField(max_length=100, verbose_name='Name') amenities= models.TextField() I added 'checked' to the form field widget but it will only check all the items. class MotelForm(forms.ModelForm): amenities = forms.MultipleChoiceField(choices=FACILITY_CHOICES, required= False, widget=forms.CheckboxSelectMultiple(attrs={'checked':'checked'})) Views @login_required def edit_motel_details(request, motel_id, slug): if id: motel= Motel.objects.get(id=motel_id, slug=slug) else: motel= motel() motel_form= MotelForm(instance=motel) MotelImagesInlineFormSet= inlineformset_factory(Motel, MotelImages, fields=('image',)) formset= MotelImagesInlineFormSet(instance=motel) if request.method== "POST": motel_form= MotelForm(request.POST, request.FILES) if id: motel_form= MotelForm(request.POST, request.FILES, instance=motel) formset= MotelImagesInlineFormSet(request.POST, request.FILES, instance=motel) if motel_form.is_valid(): created_motel= motel_form.save(commit=False) formset=MotelImagesInlineFormSet(request.POST, request.FILES, instance=created_motel) if formset.is_valid(): created_motel.save() formset.save() redirect_url=reverse('listed') return HttpResponseRedirect(redirect_url) return render(request, 'm/m_edit.html', {'motel_form': motel_form,'formset':formset,}) I want to display already selected/saved items by the user in the 'edit form'. What am I missing? -
Django 1.10 / Apache 2.4.18, Internal Server Error "No module named urls",
(Ubuntu 16.04, Django 1.10, Apache 2.4.18, mod_wsgi, no virtualenv.) I finished my app (I'm NOT following the tutorial ;)), testing it using the light Django dedelopment server -- no errors there. Before deployment I want to test it 'at home' using an apache server on my laptop. I moved the project, called 'zarzif', to /var/www/html, so that manage.py is in /var/www/html/zarzif (and 'import zarzif' is working in that location). The file wsgi.py is in /var/www/html/zarzif/zarzif. My apache2.conf contains the following: WSGIScriptAlias / /var/www/html/zarzif/zarzif/wsgi.py WSGIPythonPath /var/www/html/zarzif/ <Directory /var/www/html/zarzif/zarzif> <Files wsgi.py> Require all granted </Files> </Directory> However, starting the server and going to 127.0.0.1 results in "500 Internal Server Error" and the error.log says (in a few copies) from django.urls import reverse, referer: http://127.0.0.1/ ImportError: No module named urls, referer: http://127.0.0.1/ What am I doing wrong? I checked a few related questions, but I found none with this particular issue. Thanks in advance! (Not sure if this is important, but the group www-data owns both /var/www/html and /var/www/html/zarzif.) -
Django 1.10: Flatpage site migration runtime error
I'm currently beginning a project in Django 1.10, trying to use the included flat pages application. After installing the apps within my (base) settings file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'first_app'] SITE_ID = 1 # for use with 'django.contrib.sites' Yet when I run python manage.py migrate, the console returns the following error: RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Can someone explain to me what is causing this error, when I clearly declared the app in my 'INSTALLED_APPS' list? Thanks in advance for any advice! NOTE: It may be worth noting that I'm using multiple settings files, but this code is within the base settings file (the other files change small things such as the DEBUG variable), but i've had no problems running the server or any other errors. -
What framework can I use to create an activity stream in django
I'm working on a project using django and djangorestframework. I want ot be able to create a notifications page but I don't know which is the best framework to use to implement this. I need some suggestions with examples on how to use with DRF. Thanks -
Possible update PHP-based site to one based on Ember 2.0?
A friend of mine has a fairly extensive site (maybe 30 pages) that someone long ago wrote in PHP (and static HTML). The PHP doesn't access a DB, it does other stuff organise data based on file titles, etc. Is it possible convert the site from PHP-based to Ember 2.0 while leaving some of the PHP pages as they are. In any case, I'm new to Ember, and want to practice it -- I was thinking of updating my friend's site to give them an admin backend for the parts they update frequently, but leaving a lot of the more "static" PHP pages alone (for instance, the original programmer wrote the Contact page in PHP, for reasons I can't figure out), simply to make the scale of the project more manageable (I'd be doing this for free, as a learning experience). Would this work, combining PHP pages "into" an Ember 2.0 site? Just provide links back and forth, like in any website? But ember route URLs only work, as I understand it, within the Ember app -- it's different to Django, I think, in which one can link to any state within the app -- Thanks! -
NoReverseMatch at /accounts/home_page/
#Reverse for 'user_profile_view' with arguments '(u'Emmanuel',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] : #project/urls.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.default.urls')), url(r'', include('app.urls', namespace='app')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #app/urls.py from .views import * from . import views from django.conf import settings from django.conf.urls import url from django.views.generic import TemplateView from django.conf.urls.static import static app_name = 'app' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^accounts/home_page/$', home_page), url(r'^accounts/home_page/(?P<username>[\w-]+)/$', UserProfileView.as_view(), name='user_profile_view'), # url(r'^accounts/profile/$', views.user_profile, name='user_profile'), # url(r'^accounts/profile/edit/$', views.edit_user_profile, # name='edit_user_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #views.py class UserProfileView(View): @method_decorator(login_required) def get(self, request, user): if request.user.username == user: profile = get_object_or_404(User, user=request.user) return render(request, 'registration/home.html', {'profile': profile}) else: raise Http404 @login_required def home_page(request): return HttpResponseRedirect( reverse('user_profile_view', args=[request.user.username], current_app='app')) So what I'm actually trying to do is allow a user login with is name appearing in the url but since the LOGIN_REDIRECT_URL = '/accounts/home_page' cannot take a dynamic parameter like I am using a redirect. But I get this error please what am I doing wrong. Thanks in advance!!! -
Scrapy Get returned Value from pipeline
I'm trying to get returned value from pipeline. I'm using yield generator to generate item. And this is my code. def get_or_create(model): model_class = type(model) created = False try: obj = model_class.objects.get(product_company=model.product_company, barcode=model.barcode) except model_class.DoesNotExist: created = True obj = model # DjangoItem created a model for us. obj.save() return (obj, created) def update_model(destination, source, commit=True): pk = destination.pk source_dict = model_to_dict(source) for (key, value) in source_dict.items(): setattr(destination, key, value) setattr(destination, 'pk', pk) if commit: destination.save() return destination class ProductItemPipeline(object): def process_item(self, item, spider): if isinstance(item, ProductItem): item_model = item.instance model, created = get_or_create(item_model) item['cover_photo'] = item['files'][0]['path'] if created: item.save() for image in item['files']: imageItem = ProductImageItem(image=image['path'], product=model) imageItem.save() for comment in item['comments']: commentItem = CommentItem(comment=comment.comment, product=model) commentItem.save() return model Also this is my spider. item = ProductItem(name=name, price=price, barcode=barcode, file_urls=objectImages, product_url=response.url,product_company=company, comments = comments) product = yield item print type(product) print "yield product" And product type is returning nonetype -
Google Chrome not seeing my manifest.json
I am currently deploying a Django Project using Google App Engine. When I turned the debugging environment off in Django and run my project locally, Chrome's console is giving me the following error: Manifest: Line: 1, column: 1, Unexpected token. When I click on the manifest.json file that the error links me to, it brings me to my index.html file. Does anyone know why this might be happening? Thanks -
Custom Form Validation Django Registration Redux
I'm building a web application that integrates Django Registration Redux. The functionality it provides is appropriate for my application, but I would like to augment it by adding some extra validation for the user email field (specifically, checking for a certain domain). I've done some research on customizing this and the most common answer I've seen is to write a new custom form that extends the registration form. This seems like overkill since I just want to do this one small thing. Is there anyway to do this an easier way or should I just go ahead and override the registration form? -
Django Crispy Forms and Option Groups
I've been searching around on the Crispy Forms documentation as well as general web searching for an answer to this. Can Crispy Forms output 's within a ChoiceField using the forms.Select widget? Or must I take the data into the context and build the form out the old fashioned way in the template? Thanks!