Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Am I using get_or_create correctly?
Trying to use a single view for update and create operations. I employ two different urls: url(r'^update/(?P<pk>[0-9]+)/$', BoardUpdateView.as_view(), name='board-update'), url(r'^update/$', BoardUpdateView.as_view(), name='board-create'), Then I use this as my class: class BoardUpdateView(UpdateView): model = Board fields = ['author'] context_object_name = 'board' def get_object(self, queryset=None): if "pk" not in self.kwargs: self.kwargs['pk']=None obj, created = Board.objects.get_or_create(pk=self.kwargs['pk'], defaults={'author': self.request.user}) I know there are many ways to use Python, but I wondered if this approach is going to lead to any issues, or if there is a more idiomatic way to do this? For example, my check for whether pk exists or not seems weird/gross. -
How to insert variable into Django template and test whole HTML at client side?
I would like to front-end of my Django project. However, some DOMs specified in template and some DOMs generated in front-end JavaScript (mainly jQuery). At the same time, in Django template, some variables need to be queried from the database. I would like to know how to test whole front-end without setting the database. That is, just insert variables into template and test them at client side (i.e. load JavaScript as well, I mean). I know the Django support test cases on template and suggest using selenium on client side, but I don't know how to combine them and apply in my scenario at ease. I prefer use python library if possible, because not all members of our project know hot to program JavaScript, but all suggestions are welcome still. To be specific, I want to test this JavaScript file, which is loaded in this template. Therefore, var dataset_list = {{ blastdb_list|safe }}; var blastdb_type_counts = {{ blastdb_type_counts|jsonify }}; Load the variable, but I want to insert some already known value and write test of that javascript. As you see, that JavaScript mainly use JQuery and manipulate some DOMs. Can someone give some directions and live examples if possible? Thanks … -
Can't edit slug field in Django Admin
I have a Django app with a model that has a slug field. Up until now, I have been simply slugifying the model's label field, and making the slug read only in the admin. My client now wants me to allow them to be able to edit the slug themselves to whatever they want. I took off the readonly access in the admin, and changed the save method on my model to not use its slugified label. When I go to the admin however, and try to change the slug, it doesn't change when I save it. When I try to add a new model instance, even when I enter in something, it empties out the form field, and says that the slug field is required. I read in the Django documentation that it is custom to pre-populate the slug field, but it didn't say anywhere that it was required. Model class WebPage(models.Model): template = models.CharField(max_length=50, blank=True, null=True, choices=TEMPLATE_CHOICES, default='default') label = models.CharField(max_length=100) slug = models.SlugField(unique=True) meta_title = models.CharField(max_length=100, blank=True, null=True, help_text='This shows at the top of the browser, usually in the tab.') meta_description = models.CharField(max_length=180, blank=True, null=True, help_text='Optimal length is roughly 155 characters') meta_tags = models.CharField(max_length=500, blank=True, null=True) billboards … -
NoReverseMatch but nothing seems to be wrong
I keep getting this error: NoReverseMatch at / Reverse for 'login' not found. 'login' is not a valid view function or pattern name. But nothing in my code seems to be wrong, and in everything I have found on here and elsewhere the main problems are people not putting in the namespace into their urls. However, I am have all my namespaces and everything matches up. Here is my code, please help because while something obviously isn't right, I can't find it. users app views: from django.shortcuts import render,get_object_or_404 from users.forms import UserForm,UserProfileForm from users.models import UserProfileInfo from feed.models import UserPost from django.contrib.auth.models import User from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here. def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account now active") else: print("Login Unsuccessful") return HttpResponse("Username and/or password are not correct") else: return render(request,'login.html',{}) def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) … -
value too long for type character varying(10) when it is set to 255
In models.py class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id = models.CharField(max_length = 35) name= models.CharField(max_length = 255) I checked in manage.py dbshell within heroku, it says character varying (35) and character varying (255) respectively. I'm running out of thoughts as to why it is like this. Local runs just fine. It is when I deploy it to heroku, I get this error. I've also tried deleting the entire db in heroku and restarting everything all over. That did not work either. -
Difference between django mongoengine vs mongoengine
What's the difference between django mongoengine and mongoengine Can i use django default/build-in form mongodb -
Django REST api calls and allowed_hosts
I'm trying to implement a RESTful API in Django such that any ip could query the endpoints. However, I'm concerned about header attacks if I were to set ALLOWED_HOSTS = ['*']. I read an answer to Why is Django throwing error "DisallowedHost at /"? which suggests that api calls should be responded to, not for by the server. I don't full comprehend what they mean or how to implement it and am looking for suggestions. Ultimately, I want to know how can I make an api call which is not blocked by django because it is not in ALLOWED_HOSTS? -
Check if connected client is added to Django channels Group
i have a real-time django chatting app, first i try echoing the messages back to the connected client and it is working. now i want to use the channels Group() and start chatting but i can see any messages coming form the server. because the Django error-logs and the browsers error console doesn't show me where the error is i can't solve the problem? -
In Django, how to update other fields (in another table) in serializers.py?
I am beginner to django framework and am trying to update a foriegn key reference of my content, basically, there is a Users model as below class Users(models.Model): usr_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Member(models.Model): mem_id = models.AutoField(primary_key=True) usr_id = models.ForeignKey(Users) mem_details = models.CharField(max_length=100) with the above in the models in place, i am trying to create a serializer with the aim tat, whenever i create a instance of User table(instance), i should also update Member table details also, in the serializer am trying to do as below for the Member, but not working :( class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = ('usr_id','name'....) #have removed other fields class MemberSerializer(serializers.ModelSerializer): usr_id = UserSerializer() class Meta: model = Member fields = ('mem_id','usr_id','name'...)#removed other fields this is not taking UserSerializer's usr_id_id and it not pushing, Should i need to define override create method here??? Please help... -
Django tutorial: NameError: global name 'datetime' is not defined
I'm following this Django tutorial: https://docs.djangoproject.com/en/1.11/intro/tutorial05/ When I run python manage.py test polls, I get this error: ====================================================================== ERROR: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/learning-django/mysite/polls/tests.py", line 18, in test_was_published_recently_with_future_question self.assertIs(future_question.was_published_recently(), False) File "/home/user/learning-django/mysite/polls/models.py", line 16, in was_published_recently return self.pubDate >= timezone.now() - datetime.timedelta(days=1) NameError: global name 'datetime' is not defined ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) Destroying test database for alias 'default'... This is my tests.py code: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils import timezone from django.test import TestCase from .models import Question import datetime class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns `False`for questions whose pubDate is in the future """ time= timezone.now() + datetime.timedelta(days=30) future_question=Question(pubDate=time) self.assertIs(future_question.was_published_recently(), False) Why does Django/Python keep giving me this error even when I have import datetime in tests.py? -
No such table when creating the public user accounts by Mezzanine for Django web dev
I followed the guideline on the official website of Mezzanine (Mezzanine 1) as follow # In myapp/models.py from django.db import models class MyProfile(models.Model): user = models.OneToOneField("auth.User") date_of_birth = models.DateField(null=True) bio = models.TextField() # In settings.py INSTALLED_APPS = ( "myapp", "mezzanine.accounts", # Many more ) ACCOUNTS_PROFILE_MODEL = "myapp.MyProfile" But it says that: django.db.utils.OperationalError: no such table: app_myprofile. The signup page shows what I want, i.e., date of birth and the bio. But once I clicked the signip button, the error happened. Am I missing something? Shall I also add something in the views.py file? -
UI Bootstrap dropdown for Angularjs shows multiple values repeatedly in Django
I am trying to create a UI bootstrap dropdown in a Django project. This is my html code: <div class="container"> <div ng-controller="mainController"> <div class="btn-group" uib-dropdown is-open="status.isopen"> <button id="single-button" type="button" class="btn btn-primary" uib-dropdown-toggle ng-disabled="disabled"> Discrete Distributions <span class="caret"></span> </button> <ul class="dropdown-menu" uib-dropdown-menu aria-labelledby="simple-dropdown"> <li ng-repeat="discrete in discretes"> <a href>{% templatetag openvariable %} discrete {% templatetag closevariable %}</a> </li> </ul> </div> </div> </div> And this is my js code: var stats = angular.module('stats', ['rzModule', 'ui.bootstrap']); stats.controller('mainController', ['$scope', '$log', function($scope, $log){ $scope.discretes = ['Bernoulli', 'Binomial', 'Multinoulli', 'Multinomial', 'Geometric', 'Poisson']; }]); Output looks like the below picture. I tried all dropdown codes in here. I am new at both Angularjs and Django but I think it is about Django. Unfortunately I couldn't find the reason. Please help me to find it. -
'AnonymousUser' object is not iterable - accessing to views by anonymous and authenticateds users
I have the following Urls: The main urls.py: url(r'^accounts/profiles/', include('accounts.urls', namespace = 'accounts')), The accounts/urls.py url(r"^(?P<email>[\w.@+-]+)/$", views.UserDetailView.as_view(), name='detail'), I've created the UserDetailView to view the data of an user User = get_user_model() class UserDetailView(UserProfileDataMixin, generic.DetailView): template_name = 'accounts/user_detail.html' queryset = User.objects.all() def get_object(self): return get_object_or_404( User, email__iexact=self.kwargs.get("email") ) def get_context_data(self, *args, **kwargs): context = super(UserDetailView, self).get_context_data(*args, **kwargs) user = self.request.user following = UserProfile.objects.is_following(self.request.user, self.get_object()) context['following'] = following context['recommended'] = UserProfile.objects.recommended(self.request.user) return context When I access to /accounts/profiles/luisa@gmail.com/ url when the user who perform the request is loggedIn, the request is O.K [08/Sep/2017 23:56:20] "GET /accounts/profiles/luisa@gmail.com/ HTTP/1.1" 200 23577 But, I want that this view to be acceded from anonymous users or unauthenticated users, which does not register in my application. When an anonymous user access to /accounts/profiles/luisa@gmail.com/ url I get this message: TypeError: 'AnonymousUser' object is not iterable [09/Sep/2017 00:00:50] "GET /accounts/profiles/luisa@gmail.com/ HTTP/1.1" 500 151513 I've trying adding the dispatch method to my UserDetailView cbv to ask when the request came from anonymous user: def dispatch(self, request, email, *args, **kwargs): if request.user.is_anonymous(): # user = self.request.user # context = user.email # email = get_object_or_404(User, email__iexact=email) email = User.objects.filter(email__iexact=email) return HttpResponseRedirect(reverse_lazy("accounts:detail", email=email)) else: return super(UserDetailView, self).dispatch(request, *args, **kwargs) And I get … -
IntegrityError at /images/create/ - NOT NULL constraint failed: images_image.user_id
I tried getting an image via its URL and saving it to the database but I get IntegrityError at /images/create/ - NOT NULL constraint failed: images_image.user_id thrown at me. Here are files that could be concerned models.py (containing code to override the save() method to automatically generate the slug field based on the value of the title field) from django.db import models from django.conf import settings from django.utils.text import slugify class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) forms.py (containing code to override the save() method to retrieve a given image and save it) from urllib import request from django import forms from django.core.files.base import ContentFile from django.utils.text import slugify from .models import Image class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ('title', 'url', 'description') widgets = { 'url' : forms.HiddenInput, } def clean_url(self): url = self.cleaned_data['url'] valid_extensions = ['jpg', 'jpeg'] extension = url.rsplit('.', 1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('the given URL doesn\'t match valid image extensions') … -
how to pass data in a post request
I'm trying to post data (product.pk) but the data are not in the request pdb (Pdb) pp response.request {'CONTENT_LENGTH': 87, 'CONTENT_TYPE': 'multipart/form-data; boundary=BoUnDaRyStRiNg; charset=utf-8', 'HTTP_AUTHORIZATION': 'Token 2016d42561bc3bbdb2abf8262ff198477b2fcd60', 'PATH_INFO': '/addToCart/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'POST', 'SERVER_PORT': '80', 'wsgi.input': <django.test.client.FakePayload object at 0x7f7b64b03be0>, 'wsgi.url_scheme': 'http'} (Pdb) response <HttpResponseNotFound status_code=404, "text/html; charset=utf-8"> tests.py def test_view_user_is_adding_a_product_in_his_cart(self): # Test to sse if The user have a Cart # create some fake Product Model mixer.cycle(6).blend(StartupProduct) # Authentification user = mixer.blend(User, username='staffuser', password='password') self.client.force_authenticate(user=user) self.client.credentials(HTTP_AUTHORIZATION="Token " + user.auth_token.key) obj = StartupProduct.objects.first() data = { "pk": obj.pk } response = self.client.post('/addToCart/', data) pytest.set_trace() # response.context # check if the User.id is the one in the Cart assert Cart.objects.last().customer.id == user.id urls.py url ('^addToCart/(?P<pk>.+)/$', AddItemToCartView.as_view(), name='add_item_to_cart'), views.py class AddItemToCartView(CreateAPIView): ''' Add an item to a cart. Args: pk: Product_id ''' serializer_class = AddItemToCartSerializer permission_classes = (IsAuthenticated,) def create(self, request, *args, **kwargs): cart, created = Cart.objects.get_or_create(customer=self.request.user) # item = cart.search_items(self.request.data['product']) # cart.add_item(product=self.request.data['product'], product_type=self.request.data['type'], quantity=self.request.data['quantity']) \ # if item is None else item.update_quantity(self.request.data['quantity']) return Response(serializers.CartSerializer(cart).data, status=status.HTTP_201_CREATED) serializer class AddItemToCartSerializer(serializers.Serializer): product = serializers.IntegerField() quantity = serializers.IntegerField(default=1) excerpt of Model class Cart(models.Model): customer = models.ForeignKey(User) items = models.ManyToManyField("CartItem") created_on = models.DateTimeField(auto_now_add=True) So how can I pass some data in the Post request. -
XML submitted just fine to Amazon MWS but price not being updated
I created my own repricer of sorts but the price isn't being updated on Amazon's side. My code seems to work just fine based off the response from Amazon after submitting it. I'm hoping someone here knows more about why its not actually updating the price. Here's the XML submitted: <?xml version="1.0" encoding="utf-8" ?>\n <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">\n <Header>\n <DocumentVersion>1.01</DocumentVersion>\n <MerchantIdentifier>MERCHANTID</MerchantIdentifier>\n </Header>\n <MessageType>Price</MessageType>\n <Message>\n <MessageID>1</MessageID>\n <Price>\n <SKU>mysku</SKU>\n <StandardPrice currency="USD">350.50</StandardPrice>\n </Price>\n </Message>\n </AmazonEnvelope> Heres the response: GetFeedSubmissionResultResponse{}(ResponseMetadata: <Element_?/ResponseMetadata_0x7fee61f74248>, GetFeedSubmissionResultResult: <Element_?/GetFeedSubmissionResultResult_0x7fee61f74248>, AmazonEnvelope: {'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:noNamespaceSchemaLocation': 'amzn-envelope.xsd'}, DocumentVersion: '1.02', MerchantIdentifier: 'M_EXAMPLE_1234', Header: '\n\t', MessageType: 'ProcessingReport', MessageID: '1', DocumentTransactionID: '4200000000', StatusCode: 'Complete', MessagesProcessed: '1', MessagesSuccessful: '1', MessagesWithError: '0', MessagesWithWarning: '0', ProcessingSummary: '\n\t\t\t', ProcessingReport: '\n\t\t', Message: '\n\t') I don't know if showing my code will help in this instance since I get a successful response from Amazon. Here it is regardless: ... # Provide credentials. conn = MWSConnection( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, Merchant=AMZ_SELLER_ID ) # Get the service resource sqs = boto3.resource('sqs') # Get the queue queue = sqs.get_queue_by_name(QueueName=SQS_QUEUE_NAME) for index, message in enumerate(queue.receive_messages(MaxNumberOfMessages=10)): ... import time from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('repricer', 'xml_templates'), trim_blocks=True, lstrip_blocks=True) template = env.get_template('_POST_PRODUCT_PRICING_DATA_.xml') class Message(object): def __init__(self, s, price): self.SKU = s self.PRICE = round(price, 2) self.CURRENCY = USD_CURRENCY feed_messages … -
Set up current Album 'pk' in genericView
I'm trying to delete object (foto) from Album and I want Views to return to detail view (current Album) but I can't set up 'pk' of current Album . I tried various ways but I can't figure it out and solve it. Maybe I should add some independent 'foto_pk' for foto's objects, or instead of generic DeleteView use some usual definition? I'm out of ideas. Please give me some clues... Thanks. URLs: url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'albumadd/$', views.AlbumCreate.as_view(), name='album-add'), url(r'update/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='albumbum-update'), url(r'delete/(?P<pk>[0-9]+)/$', views.AlbumDelete.as_view(), name='albumbum-delete'), url(r'^(?P<pk>[0-9]+)/fotoadd/$', views.FotoCreate.as_view(), name='foto-add'), url(r'^(?P<pk>[0-9]+)/fotodelete/$', views.FotoDelete.as_view(), name='foto-delete'), Views: class FotoDelete(LoginRequiredMixin, DeleteView): model = Foto def album(request, pk): album = Album.objects.get(pk=pk) return reverse_lazy('albumbum:detail', kwargs={'pk': album.pk}) other try Views: class FotoDelete(LoginRequiredMixin, DeleteView): model = Foto success_url = reverse_lazy('albumbum:detail', kwargs={'pk': Album.pk}) other try Views: class FotoDelete(LoginRequiredMixin, DeleteView): model = Foto album = get_object_or_404(Album, pk=pk) success_url = reverse_lazy('albumbum:detail', kwargs={'pk': album.pk}) -
How does {% url 'x' y %} function in Django?
In the Django tutorial (https://docs.djangoproject.com/en/1.11/intro/tutorial03/), we are advised not to "hard code" urls in our templates. For example, this snippet: <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> should be replaced by: <ul> {% for question in latest_question_list %} <li><a href="{% url 'detail' question.id %}/">{{ question.question_text }}</a></li> {% endfor %} </ul> However, the tutorial doesn't do a great job of explaining what actually happens here. The first example was clear, {{ question.id }} would take the value of the question id and it would be placed in the url. But in the second snippet, we are using the keyword (is it called a keyword?) url and also doing something with 'detail', which I'm not sure where it comes from, though I suspect it has something to do with this: urlpatterns = [ ... url(r'^(?P<question_id>[0-9]+)/detail/$', views.detail, name = 'detail'), ] So, my question is what is happening in {% url 'detail' question.id %}? -
Django: How can I pass a variable into the url from an anchor tag?
Django again... I have seen only one way to do this but I am getting an error. I have the url: url(r'^wish_item/(?P<id>\d#)$', views.wish_item, name="wish_item") and the view, def wish_item(request, id): but the anchor tag in my template is causing me a NoReverseMatch. {% for x in myitems %} <a href="{% url 'wish_item' %}?id={{x.id}}">{{x.item}}</a> {% endfor %} What is the correct way to pass the variable into the url? Is anything wrong with the regex in my url or am I writing this wrong in the template tag? both? -
How to display only values in Django Serializers?
I am implementing Django REST API framework using the 'rest_serializer' module: Currently the output is: { "count": 86, "next": "http://127.0.0.1:8000/state/?page=2", "previous": null, "results": [ { "state_name": "Alaska" }, { "state_name": "California" }, ... ] } How do I display just this as a json list: [ "Alaska", "California", ... ] Below are my serializers: from .models import States from rest_framework import serializers class StateSerializer(serializers.ModelSerializer): class Meta: model = State fields = ('state_name',) view.py class StateViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = States.objects.values('state_name').distinct(); serializer_class = StateSerializer -
Django-allauth - How do I get the form errors from Ajax?
Using django-allauth, how do I obtain form errors via AJAX login? I am using this view with my /signup/ url: from allauth.account.views import SignupView Conveniently, it accepts my Ajax call: var signupForm = function(token) { $.ajax({ url:"/signup/", type:"POST", data: { "email": $('#user').val(), "password1": $('#pass1').val(), "password2": $('#pass2').val() }, success: function (){ location.href = '/'; window.location.reload(true); }, error:function (er) { alert("signup failure...",er); } }); }; Inconveniently, if there is a problem with the form, it returns: error 403: Bad Request This gives me no idea why a login has failed. I would like to be able to convey to the user what happened. Was it a problem with her password? Was her email address already registered? Can I accomplish this with all-auth, or do I need to write my own validation from javascript? -
django allauth extended user model - Using default signup form
I'm using django-allauth and have extended the user model with the model below. However when I go to accounts/signup/ then the only fields that appear in the form are those in the default user model. Does allauth require a custom signup form to display the other fields? models.py class User(AbstractUser): MR = 'Mr' MRS = 'Mrs' MISS = 'Miss' MS = 'Ms' DR = 'Dr' SIR = 'Sir' PROF = 'Prof' REV = 'Rev' TITLE_CHOICES = ( (MR, 'Mr'), (MRS, 'Mrs'), (MISS, 'Miss'), (DR, 'Dr'), (SIR, 'Sir'), (PROF, 'Prof'), (REV, 'Rev'), ) title = models.CharField(max_length=5, null=True, choices=TITLE_CHOICES) date_of_birth = models.DateField() primary_phone = PhoneNumberField() def __str__(self): return self.username Relevant settings: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', default=True) ACCOUNT_FORMS = {'login': 'switcher5.users.forms.LoginForm', # 'signup': 'switcher5.users.forms.ProfileForm', # no longer using a onetoonefield profile model 'reset_password': 'switcher5.users.forms.ResetPasswordForm'} ACCOUNT_ADAPTER = 'switcher5.users.adapter.AccountAdapter' SOCIALACCOUNT_ADAPTER = 'switcher5.users.adapter.SocialAccountAdapter' AUTH_USER_MODEL = 'users.User' -
Django: How to display a picture on homepage that is uploaded through registration?
I am having a problem with displaying a profile picture for every user after the user is done with the registration. I can see the pictures are being saved after the upload to the /media/profile_pictures folder, but I can't find a way to display that picture on the homepage. Please look at the code samples. I was following the Tango with Django tutorial for uploading a picture, but none of the questions that I found here and are related to this problem did not really help me. Thanks! forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('website', 'picture') views.py def register(request): context = RequestContext(request) registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True else: print (user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() return render(request,'webapp/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}) models.py class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_images', blank=True) def __unicode__(self): return self.user.username settings.py MEDIA_URL = '/media/profile_images/' … -
How to reference ForeignKey objects in HTTP POST?
I have a RESTful API on Django and I would like to know how to reference an existing ForeignKey when using json in HTTP POST? class Trainer(models.Model): account = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='profiles') username = models.CharField(max_length=30, unique=True, primary_key=True) start_date = models.DateField(default=date(2016,7,13), null=True, blank=True) faction = models.ForeignKey('Faction', on_delete=models.SET_DEFAULT, default=0, null=True, verbose_name="team") has_cheated = models.BooleanField(default=False) last_cheated = models.DateField(null=True, blank=True) currently_cheats = models.BooleanField(default=False) statistics = models.BooleanField(default=True) daily_goal = models.IntegerField(null=True, blank=True) total_goal = models.IntegerField(null=True, blank=True) last_modified = models.DateTimeField(auto_now=True) prefered = models.BooleanField(default=True, verbose_name="main profile") def __str__(self): return self.username class Faction(models.Model): name = models.CharField(max_length=140) colour = RGBColorField(default='#929292', null=True, blank=True) image = models.ImageField(upload_to=factionImagePath, blank=True, null=True) leader_name = models.CharField(max_length=140, null=True, blank=True) leader_image = models.ImageField(upload_to=leaderImagePath, blank=True, null=True) def __str__(self): return self.name This are the relevant models, I have a list of 4 Faction objects, with their primary keys being 0, 1, 2 and 3. I've tried many different way, but I just can't figure it out. This was my latest try, can you advice where I'm going wrong? { "username": "Bob123", "faction": "1" } Returned { "username": "Bob123", "faction": "Teamless", "start_date": "2016-07-13", "has_cheated": false, "last_cheated": null, "currently_cheats": false, "statistics": true, "daily_goal": null, "total_goal": null, "last_modified": "2017-09-08T21:05:18.001389Z", "prefered": true, "account": null } -
Confusion on getting Javascript to see a lsit of lists from Python via JSON as such
I am working on a Django app. I need to pass back a few parameters from the server, which I do with this code: num_periods = 25 num_traces = 2 opacities = [0.5, .99] ys = [[1,2,3,4,5],[7,6,5,4,3]] response = {'text' : request.POST['value'], 'num_periods' : num_periods, 'num_traces' : num_traces, 'opacity': opacities, 'ys': ys } return JsonResponse(response) On the client side, in the Ajax callback, I have code that looks like this: success : function(data) { console.log('num traces = ' + data.num_traces); console.log('opacitiees = ' + data.opacity); console.log('data = ' + data.ys); but, console.log(ys) gives data = 1,2,3,4,5,7,6,5,4,3, which looks flattened. However, if I do console.log(ys[1]), it 'looks like' an array: 7,6,5,4,3, though with no brackets. So, JS is aware of the nested list structure. But any attempt to get it into a list of lists of numbers fails. for example this code: z=[] z.push(ys[0]) z.push(ys[1]) gives me back z = 1,2,3,4,5,7,6,5,4,3 when I do console.log("z = " + z) Something deeply confusing is happening here. I also tried Object.values(ys[0]), but still this does not give a list. Other ideas I have seen are a clever use of slice like so : var ys=[]; while(list.length) ys.push(list.splice(0,5)); console.log("ys[0]="+ys[0]); which gives ys[0]=1,2,3,4,5,7,6,5,4,3 How do …