Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django -> Exception Value: (1048, "Column 'user_id' cannot be null")
I have the following view which works perfectly: @transaction.atomic def register(request): next_url = request.POST.get('next', request.GET.get('next', reverse('profile'))) if request.method == 'POST': form = RegistrationForm(request.POST) profileform = ProfileForm(request.POST) if form.is_valid() and profileform.is_valid(): new_user = form.save() # Login the newly created user. authenticated_user = authenticate(username=new_user.username, password=form.cleaned_data['password1']) login(request, authenticated_user) return redirect(next_url) else: form = RegistrationForm() profileform = ProfileForm() return render(request, 'meta/register.html', {'form': form, 'profileform': profileform, 'next': next_url}) However, when I wish to save the additional profile information using the following line (placed below the line new_user = form.save() ): new_user_profile = profileform.save() I get the following error: Exception Type: IntegrityError Exception Value: (1048, "Column 'user_id' cannot be null") My model for the profile is as follows: class Profile(models.Model): user = models.OneToOneField(User) dob = models.DateField(max_length=8) class Meta: managed = True db_table = 'fbf_profile' Any help would be great, Alan. -
Within Django, how can I turn my Python datetime string into a Javascript Date object?
I am attempting to go from JSON data -> Javascript Date object within Django. Currently, I have it set up so that I have a function which hits the API and saves the JSON data into one of my Model objects. Then in my View, I will query for the object containing the JSON, and send a datetime string which was acquired from the JSON, over to my template as a context variable. Within the template, I am trying to graph the string data using Google Chart, and Google Charts requires that the first column for the Line graph to be a JS Date object. How can I turn the sent over template variable: {{ date }} into a format equivalent to Javascript's new Date(2017, 01, 14) so that it may be used with Google Charts? -
Display auth.User fields in related model
I have created this Django model: class Teacher(models.Model): user = models.OneToOneField('auth.User', on_delete=models.CASCADE, default=1) surname = models.CharField(max_length=15, null=True) creation_date = models.DateTimeField('creation date', auto_now_add=True) deletion_date = models.DateTimeField('deletion date', null=True, blank=True) and a form to represent it in read-only mode: class TeacherViewForm(ModelForm): def __init__(self, *args, **kwargs): super(TeacherViewForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: for field in self.fields: self.fields[field].widget.attrs['disabled'] = True class Meta: model = Teacher exclude = ['deletion_date'] As you can see, there is a OneToOne relation between the Teacher and the auth.User models. I need to displayfirst_name and last_name from auth.User model, but only the username is shown. How can I display these fields the same way field Teacher.surname is being displayed? Do I have to include them in the model, the form.fields or is there a property I havo to modify in order to achieve it? Thanks -
Django REST Framework -- static alias for {pk} url
There's a standard ViewSet, and urls are like: /api/users/ and /api/users/{pk}/. I'd like to have /api/users/me/ that behaves exactly like detail view accessed by pk (so /api/users/me/ behaves like /api/users/5/ if your user id is 5). I've tried this: def dispatch(self, request, *args, **kwargs): if kwargs.get('pk') == 'me' and request.user: kwargs['pk'] = request.user.pk return super(UserViewSet, self).dispatch(request, *args, **kwargs) And, it works perfectly (all HTTP methods) with SessionAuthentication but not with TokenAuthentication. With TokenAuthentication, it returns: curl -H "Authorization: Token f14b876aa54ebb7679330b88ea1c5b5ea4d693e9" http://127.0.0.1:8000/api/users/me/ {"detail":"Not found."} And, dispatch() is not even executed, so something earlier must be blocking it. Other views (eg. /api/users/) work correctly. What may be the cause, how to debug this? -
how Follow feature, just like in instagram, works in backend
I want to create a Follow feature for my website without using any third party API so i want to know how this feature works in backend and how it affects the database. I will be very helpful if you give the answer from Django point of view. -
why docker-compose run command can create files in local filesystem
I am new to Docker and I am learning Docker with its official docs. In one of its Tutorial, it explains how to create a Django project with docker. What I can not understand is a command below. docker-compose run web django-admin.py startproject composeexample . The doc says it will create a Django project inside a container and those new created files will be in local filesystem. My question is why those new created files will be in local system if they are created in a container? -
Change queryset in ModelViewSet in Django Rest Framework
I wrote a RegistrationView for Djoser class RegistrationView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserRegistrationSerializer permission_classes = ( permissions.AllowAny, ) def perform_create(self, serializer): user = serializer.save() signals.user_registered.send(sender=self.__class__, user=user, request=self.request) if settings.get('SEND_ACTIVATION_EMAIL'): self.send_activation_email(user) elif settings.get('SEND_CONFIRMATION_EMAIL'): self.send_confirmation_email(user) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) token = create_token(serializer.data) return Response(data=token, status=status.HTTP_201_CREATED, headers=headers) def send_activation_email(self, user): email_factory = utils.UserActivationEmailFactory.from_request(self.request, user=user) email = email_factory.create() email.send() def send_confirmation_email(self, user): email_factory = utils.UserConfirmationEmailFactory.from_request(self.request, user=user) email = email_factory.create() email.send() As you can see, I want to use my own create function. That's why I use a ModelViewSet But as you can see, I declare the queryset in a way where all the user objects will be listed, and I don't really like it. So, my question. Is there a way to declare another "queryset" that doesn't show that information? Or should I write my "create" function in another place and don't write the queryset there? The point is that I want to call the create function in the registration process. -
Update model field based on date
I have an Article model with views field. I store views in redis then launch a cron every weeks with a Django command to update database with the number of views in redis. class Article(models.Model): title = models.TextField(max_length=500, default='') description = models.TextField() owner = models.ForeignKey(User) created = models.DateTimeField(default=lambda: datetime.datetime.utcnow()) updated = models.DateTimeField(auto_now=True) views = models.PositiveIntegerField(default=0) In my Django command: def handle(self, *args, **options): # Get article views in redis For art in Article.objects.all(): art.views = cache.get('article_views:%s' % art.id) art.save() Is there a way to do it without a command launched periodically, something like adding a check on the model to update its views field with redis values every week ? -
Save a new record from formset instance
I need to save a new record from the exitsing instance of inline formset. I managed to save a new instance from the parent model (Order), but I can't figure out how to save a new instance of a formset. The code is like this: def order(request, date): edit = Order.objects.get(date=date, user=None) edit_formset = inlineformset_factory(Order, Order_items, can_delete=False, fields='__all__', extra=0) if request.method == 'POST': form = OrderForm(request.POST, instance=edit) formset = edit_formset(request.POST, instance=edit) if form.is_valid(): instance = form.save(commit=False) # edit = form.save(commit=False) instance.pk = None instance.user_id = request.user.id # edit.id = None form.save() if formset.is_valid(): add_new = formset.save(commit=False) add_new.save() return HttpResponseRedirect('order') else: form = OrderForm(instance=edit) formset = edit_formset(instance=edit) return render(request, 'diner/order.html', {'edit': edit, 'form': form, 'formset':formset}) -
I've changed Mysql but Django don't Show me
I Have A Data Base That I Store here my Posts.When I Changed Manually The My Data Base.My Page Don't Show The Changes! -
urlpatterns = patterns('') NameError: name 'patterns' is not defined
I am making users' images upload system. But when I run server,I got a error, urlpatterns = patterns('') NameError: name 'patterns' is not defined. My app has 2 app,one of them is a parent and another is child. In a parent app of urls.py,I wrote from django.conf.urls import url from django.contrib import admin from django.conf.urls import include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'accounts/', include('accounts.urls')), url(r'api/', include('UserToken.urls')) url(r'^media/(?P<path>.*)$','django.views.static.serve', {'document_root': settings.MEDIA_ROOT}) ] In a parent app of settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'image') MEDIA_URL = '/image/' in views.py of children app, from django.shortcuts import render # Create your views here. import os import uuid from PIL.Image import Image from django.views.generic import View from django.conf import settings class ImageTop(View): """ 画像に設定する画像処理 古い画像ファイルの削除処理 """ def get_image_top_path(self, filename): """ カスタマイズした画像pathを取得する UUIDにして画像ファイル名をhash化 :param self: インスタンス(model) :param filename: 元の画像ファイル :return: カスタマイズしたファイル名を含む画像パス """ prefix = 'test/' name = str(uuid.uuid4()).replace('-', '') extension = os.path.splitext(filename)[-1] return prefix + name + extension def delete_previous_file(self, function): """ 不要となる古い画像ファイルを削除する為のでコレータ実装 :param function: メイン関数 :return: wrapper """ def wrapper(*args, **kwargs): self = args[0] #保存前の画像ファイル名取得 result = Image.objects.filter(pk=self.pk) previous = result[0] if len(result) else None super(Image, self).save() #関数実行 result = function(*args, **kwargs) #保存前のファイルがあったら削除 if previous: os.remove(MEDIA_ROOT + '/' + previous.image.name) return result return wrapper<span style="font-family: Arial;"> </span> … -
Get the filter kwargs from Django Queryset in model manager
I have a Company model which hides some of its status. So when a user queries Company.objects.all() I will filter out any of special status I deem inappropriate. Something like below class Company(models.Model): name=models.TextField() status=models.CharField() ... objects = FilteredCompanyManager() where class FilteredCompanyManager(models.Manager): def get_queryset(self): return super(FilteredCompanyManager, self).get_queryset().exclude(status__in=CompanyConstants.SPECIAL_STATUS.values()) My question is that I want something like Company.objects.filter(displayAllObjects=True) to not exclude any statuses. So my amended fictional FilteredCompanyManager would look something like class FilteredCompanyManager(models.Manager): def get_queryset(self): if 'displayAllObjects' in super(FilteredCompanyManager, self).get_queryset().get_kwargs(): return super(FilteredCompanyManager, self).get_queryset() else: return super(FilteredCompanyManager, self).get_queryset().exclude(status__in=CompanyConstants.SPECIAL_STATUS.values()) I know I can probably do it with objects=FilteredCompanyManager and allObjects=models.Manager() but want a way where its possible in a single model manager and not with two model managers. -
How can I use wildcard subdomain in Django with Amazon route 53?
How can I use wildcard domain like http://username.abc.com? -
How to change django-leaflet settings inside Selenium Tests
I need to write a Selenium test to draw a polygon on a map. For that I need to change the NO_GLOBALS setting. How to do that inside a python selenium test? -
Django : Instance of IntegerField in a model gives type as 'int'
I was trying to implement some functions defined for the IntegerField . This is the code: class student(models.Model): marks=models.IntegerField(blank=True,default=0,null=True) def __unicode__(self): print self.marks.has_deafult() return str(self.marks) This is the error I got: 'int' object has no attribute 'has_deafult' I then implemented this code: class student(models.Model): marks=models.IntegerField(blank=True,default=0,null=True) def __unicode__(self): print type(self.marks) sample=models.IntegerField() print(type(sample)) return str(self.marks) And this is the ouput I got: <type 'int'> <class 'django.db.models.fields.IntegerField'> Now,I don't understand why this is happening. Shouldn't the type for both be the same as both of them are instances of models.IntegerField() -
How to implement ajax Django comment?
What I am doing is following. post_detail.html <div class="comment_form"> <form id="comment_form" method="POST" class="post-form"> {% csrf_token %} {% include "myblog/post_comment.html" %} <button id="add_comment" type="submit" class="save btn btn-default" >Comment</button> </form> </div> Post detail view def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) return render(request, 'myblog/post_detail.html', {'post': post}) Add comment to post def add_comment_post(request, slug): form = CommentForm(request.POST or None) if request.method == "POST": post = get_object_or_404(Post, slug=slug) form = CommentForm(request.POST or None) if form.is_valid(): lst_com = form.save(commit=False) lst_com.post = post x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') lst_com.ip_address = ip lst_com.published_date = timezone.now() lst_com.save() return render_to_response('myblog/post_comment.html', {'form': form }, RequestContext(request)) ajax request_to_add_comment_post $('#add_comment').click(function() { $("input[name=csrfmiddlewaretoken]").val()}, $.ajax({ type: "POST", url: "comment/", data: {'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()}, success: addSucsess, dataType: 'html' }); }); function addSucsess(data, textStatus, jqXHR) $('#comment_form').html(data); Now, my problem here is when add_comment_post return "render_to_response", post_detail.view is called again. How to solve this? What is the correct solution ? -
Django: is possible to find specific object in pagination?
Let say, I want to built a forum with implements the Thread and Comment concept.. and the Comment model is ForeignKey to the Thread. class Thread(models.Model): title = models.CharField(max_length=200) .... class Comment(models.Model): thread = models.ForeignKey(Thread, ...) comment = models.TextField() .... The Detail Thread have some Comments The Comments at Detail Thread using /?page={number} for the pagination. But, I have a problem if I want to find the single object comment. For example, I have single object comment with id=13 found in the page=3. I want to create it with dynamically, for example in my views.py: def find_comment(request, pk): """ Return redirect to the comment on thread, with current page. :param `pk` is pk/id from comment. """ comment = get_object_or_404(Comment, pk=pk) comments = Comment.objects.filter(thread__in=comment.thread) # what i should be do here? Thanks so much before.. -
independence of individual test methods in APITest class in Django Rest Framework
I followed the tutorial for testing from APITestCase documentation in dry site. But I could find answers to some of my doubts in the drf document. I have a APITestCase subclassed as below class GroupTest(APITestCase): def setUp(self): . . def tearDown(self): . . def test_case_A(self): . # I create a group here # but I dont delete the group object in case A . def test_case_B(self): . # Will the group object from case A exist in case B ? # are the different test methods in a APITestCase independent? . If I have two test cases in GroupTest class, are they independent? will a group object created in case A affect case B? -
Fetching phone number from graph facebook api
Fetching Mobile number via FB api is disable by Facebook few years ago. I did not find anything to fetch mobile number of user in latest api. Please somebody helps me how can i fetch mobile number? -
How to iterate through list inside Dictionary in Django Python
I have passed a dictionary who's structure is like dic={'items':[1,2,3,4,5], 'price':[20,30,40,50,60]} return render_to_response('somepage.html',dic) from my template somepage.htm i want output to be like 1 20 2 30 3 40 4 50 5 60 What code should I write in somepage.html to get this output. -
get() unable to find POST data
I'm trying to build ajax comments in my django app. Comments are written in a TextField(), which have a name="comments_text" and class="comment_text. So to fetch the entered text I tried ajax_comment = request.POST.get('comment_text'). However this returned None for some reason. Here's my code: models.py class Comments(models.Model): comment_id = models.IntegerField() parent_id = models.IntegerField() comment_text = models.TextField(max_length=350, blank=True) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comments fields = [ 'comment_text' ] views.py def article(request, category, id): ... comment = CommentForm(request.POST or None) ajax_comment = request.POST.get('comment_text') print(ajax_comment) #returns None if request.is_ajax(): #True if comment.is_valid(): # True ajax_comment = request.POST.get('comment_text') print(ajax_comment) #returns None return HttpResponse('Something') context = { 'comment': comment, } return render(request, 'article.html', context) template <div class="commentsContainer"> <form action="" class="comment_form">{% csrf_token %} {{ comment.comment_text|add_class:"comment_text" }} <input type="submit" value="Comment" class="comment_submit"> </form> <div class="comment_div"> <h3>Username1</h3> <p>Something</p> </div> </div> base.js $('.comment_form').on('submit', function(e) { e.preventDefault(); var url = window.location.href.split('?')[0]; console.log(url); // this works fine $.ajax({ type: 'POST', url: url, dataType: 'json', data: { text: $('.comment_text').val(), csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, success: function(text) { $('.comment_div').append("<div class='comment_div'><h3>username</h3><p>" + text + "</p></div>"); console.log(text); // text=something&csrfmiddlewaretoken=sWJashvQgbKG9hM0imiFTjj3EQrCP5qRfq60XraoQK1SULlPumJonyMktt9DllEC } }) }); Any idea? -
Django-Allauth - How do I check the provenance of the connected account ?
I would like to display the profile image of the user through my template, but I need to know if the user comes from facebook or not, so I can retrieve the correct link to the avatar image. I'm using the django-allauth package. here is the base.html template {% if ...? %} #what should I put in the if tag to check the user's provenance ? <img src="{{ user.socialaccount_set.all.0.get_avatar_url }}"> {% else %} <img src="{{ user.profile.avatar }}"> {% endif %} How can I differenciate both of these through the template ? -
Django - Date picker for date of birth
I have the following form: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('title', 'dob') labels = { 'dob': ('D.O.B'), } Which is based on the following model: class Profile(models.Model): user = models.OneToOneField(User) title = models.CharField(max_length=10) dob = models.DateField(max_length=8) class Meta: managed = True db_table = 'fbf_profile' the HTML part is as follows: <div class="form-group"> <label class="col-sm-5 control-label">{{ profileform.dob.label }}:</label> <div class="col-sm-7"> {{ profileform.dob }} <div class="text-danger"> {% for error in profileform.dob.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> It is displaying correctly but in it's current format the user has to type their date of birth manually. I would like a date picker that allows them to choose day, month, year from three separate drop down boxes. Any idea on the best way to achieve this? Or if someone has any better ways they think selecting date of birth then I am open to ideas. Many thanks, Alan. -
"QuerySet" prints before list result
I'm building a blog in Django. I ran these commands in this order inside my virtualenv in the terminal: python manage.py shell from posts.models import Post Post.objects.all() Post.objects.filter(title__icontains=“example”) Post.objects.create(title=“Djangohead”, content=“Born to raise shell, born to raise shell, we know how to do it and we do it real well”) Post.objects.all() queryset = Post.objects.all() for obj in queryset: print obj.title print obj.content print obj.updated print obj.timestamp print obj.id print obj.pk I got correct results, including the first one <[<Post: title example>]> Then I exited, ran the server, and did the same thing directly into views.py and index.html. For practice, I deleted what I did in these two files and ran the commands again. Now, after typing python manage.py shell from posts.models import Post Post.objects.all() I'm getting "QuerySet" printed before the list: <QuerySet [<Post: title example>]> Why does it suddenly happen, and how do I reverse it back to the way it was? The only thing I did between the two is change my home folder name, but I hardly see how it could be related. -
Filter django admin many to one editor
How can I filter the contents of a dropdown field in django's admin pages when editing an object? Example: class Question(models.Model): creator = models.ForeignKey(User) body = models.CharField(max_length=200) category = models.ForeignKey(Category) class Category(models.Model): name = models.CharField(max_length=200) creator = models.ForeignKey(User) class QuestionAdmin(TeacherModelAdmin): fieldsets = [ (None, {'fields': ['body', 'category']}), ] #Filter by request.user == creator ?