Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there a way to convert a view function to a celery task?
task.py @task(name="send_mail_to_custormer") def order_created(order_id): order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {} {},\n\nYou have successfully placed an order. Your order id is {}'.format(order.first_name, order.last_name, order.id) from_email = settings.EMAIL_HOST_USER to_email = [order.email] mail_sent = send_mail( subject, message, from_email, to_email, fail_silently=False ) return mail_sent views.py def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: try: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) except: pass cart.clear() order_created.delay(order.id) return render(request,'orders/order_created.html', {'cart': cart, 'order': order}) else: form = OrderCreateForm() return render(request, 'orders/order_create.html', {'cart': cart, 'form': form}) cart.py class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True Now the celery task sends mail and view function creates order after taking values from cart and order form. How I can change the task to create order? Is it a good practice doing so. Hope somebody can help me, thank you. -
Django save override recursion not working
I'm trying to set up a promo code system that automatically gets claimed by eligible users/students (specified either by a M2M or comma separated string of emails). Here's the relevant code from the model: class PromoCode(models.Model): students_claimed = models.ManyToManyField('Student', blank=True, related_name='promo_codes_claimed') claimable_by = models.ManyToManyField('Student', blank=True, related_name='claimable_promo_codes') claimable_by_emails = models.CharField(max_length=10000, null=True, blank=True) def save(self, *args, **kwargs): if self.claimable_by_emails: for email in self.claimable_by_emails.split(','): try: student = Student.objects.get(user__email=email) student.claim_promo_code(self) except Student.DoesNotExist: pass for student in self.claimable_by.all(): student.claim_promo_code(self) super().save(*args, **kwargs) The claim_promo_code method within Student is as follows: def claim_promo_code(self, promo_code): if promo_code.is_claimable_by(self): promo_code.students_claimed.add(self) promo_code.save() print('TEST') I know the claim_promo_code method is being called because the print statement is running; however, the user is not being added/saved to students_claimed. Calling the claim_promo_code method through other means (outside of the save method) works as intended. Is there a problem with calling an object's save method within itself, as is the case here? How should I approach solving this? -
CSS styling got ruined while sending html mail using python via sendgrid
When I send HTML template as a mail, all the styling got ruined. The html is created using sendgrid templating but all the styling got ruined when I send this email. Here is my code. main.py from django.template.loader import render_to_string def send_mail(receiver_email, subject, email_template): sendgrid_object = sendgrid.SendGridAPIClient(apikey = credentials.sendgrid_API_key) data = { "personalizations": [ { "to": [ { "email": receiver_email } ], "subject": subject } ], "from": { "email": "support@xyz.net", "name": "Support" }, "content": [ { "type": "text/html", "value": email_template } ] } response = sendgrid_object.client.mail.send.post(request_body=data) send_mail(email,subject, render_to_string("welcome.html")) -
AttributeError in views.py: type object 'Transaction' has no attribute 'objects'
I am a first-time poster here and I have run into an issue using Django. I am creating a finance app which tracks deposits and withdrawals.Unfourtanently I have run into an issue using models. Here is the relevant code Views.py from django.shortcuts import render from .models import Transaction # Create your views here. class Transaction: def __init__(self, name, description, location, amount): self.name = name self.description = description self.location = location self.amount = amount def sum(totals): sum = 0 for i in range(len(totals)): if totals[i].name.lower() == 'deposit': sum += totals[i].amount else: sum -= totals[i].amount return sum #transactions = [ # Transaction('Deposit', 'Allowance', 'Home', 25.00), # Transaction('Withdrawl', 'Food', 'Bar Burrito', 11.90), # Transaction('Withdrawl', 'Snacks', 'Dollarama', 5.71) #] def index(request): transactions = Transaction.objects.all() balance = sum(transactions) return render(request, 'index.html', {'transactions':transactions, 'balance': balance}) Models.py from django.db import models # Create your models here. class Transaction(models.Model): name = models.CharField(max_length = 100) description = models.CharField(max_length = 100) location = models.CharField(max_length = 100) amount = models.DecimalField(max_digits = 10, decimal_places = 2) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Transaction # Register your models here. admin.site.register(Transaction) Let me know if there is any other code you need to look at and thanks in … -
Django login using email
I want to login on website, using user's email. I have: models.py class User(models.Model): email = models.EmailField() password = models.CharField(max_length=200) client_id = models.IntegerField() role = models.CharField(max_length=200) So, as far as I understand it will be hard to create Customer User model, after migrations to db. Can I just use this code to login, or I need to change user's model? P.s. It's not standart login user's model, can I logout using standart auth.logout? urls: url(r'^admin/', admin.site.urls), url(r'^main/$', MainPage, name="main"), url(r'^login/$', UserLogin, name="login"), url(r'^$', HomeView, name="home"), url(r'^logout/$', Logout, name="logout"), views.py def UserLogin(request): email = request.POST.get('email',False) password = request.POST.get('password',False) user = authenticate(email=email,password=password) if user is not None: return HttpResponseRedirect('Main.html') else: return HttpResponseRedirect('Index.html') def Logout(request): auth.logout(request) return render_to_response('Login.html') Html code: <form class="m-t" role="form" action="/login" method="post"> <div class="form-group"> <input type="email" class="form-control" placeholder="Username" required=""> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" required=""> </div> <button type="submit" class="btn btn-primary block full-width m-b">Login</button> <a href="password.html"> <small>Forgot password?</small> </a> <a class="btn btn-sm btn-white btn-block" href="reg.html">Create an account</a> </form> After running server with url .8000/login, every try program returns user = None, and redirects to Index.html. I thought, that I have this mistake because I'm already logged in, but now I'm not sure. Also, When I try to logout from … -
Error installing psycopg2==2.6.2
I have problems when I try installing psycopg2==2.6.2 . I have installed postgresql 9.6. and I am using a virtualenv.Any help is welcome. Collecting psycopg2==2.6.2 (from -r requirements.txt (line 21)) Downloading psycopg2-2.6.2.tar.gz (376kB) 100% |████████████████████████████████| 378kB 281kB/s Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: could not determine PostgreSQL version from '10.0' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-k7nulk7r/psycopg2/ -
DRF: Database not updating
Following are my files. It is simply adding products based on subcategories and categories. Everything is working fine but the data is not being saved in the database. I am not sure where I am going wrong. models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') class Meta: unique_together = ('parent' , 'category') def __str__(self): return self.category class SubCategory(models.Model): subcategory = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren') class Meta: unique_together = ('parent' , 'subcategory') def __str__(self): return self.subcategory class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) subcategory = models.ForeignKey('SubCategory', null=True, blank=True) def __str__(self): return self.name views.py class AddProducts(APIView): serializer_class = AddProductsSerializer def post(self, request, format=None): data = request.data serializer = AddProductsSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) serializers.py class AddProductsSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'subcategory') def create(self, validated_data): return Product.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.category = validated_data.get('category', instance.category) instance.subcategory = validated_data.get('subcategory', instance.subcategory) instance.save() return instance -
Celery 4 not auto-discovering tasks
I have a Django 1.11 and Celery 4.1 project, and I've configured it according to the setup docs. My celery_init.py looks like from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings.settings' app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') #app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # does nothing app.autodiscover_tasks() # also does nothing print('Registering debug task...') @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) However, when I launch a worker with: .env/bin/celery worker -A myproject -l info it shows no tasks being found except for the sample "debug_task", even though I have several installed apps with Celery tasks, with should have been found via the call to app.autodiscover_task(). This is the initial output my worker generates: -------------- celery@localhost v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.13.0-16-generic-x86_64-with-Ubuntu-16.04-xenial 2017-10-31 15:56:42 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: myproject:0x7f952856d650 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: amqp:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . myproject.celery_init.debug_task [2017-10-31 … -
Django Channel Group send then discard
I want to send a message to a Group and immediately afterwards discard one of the reply channels. It doesn't work due to the consumer_finished signal not sending until the incoming message is fully dealt with, I gather from debugging the code and witnessing when the message is sent to the frontend. The result is that my message doesn't get sent on the channel that I delete afterwards. Am I doing anything wrong, or is this a Channel bug/feature? Group(room_id).send({'text': json.dumps({'command': 'leave', 'room': {'id': room_id}, 'user': {'id': str(message.user.id)}})}) Group(room_id).discard(message.reply_channel) -
Django Rest Framework - 'ModelBase' object is not iterable
Struggling to understand this error message. I think it means that somewhere I'm trying to iterate over the Base class, instead of an instance or instances of the class? I also believe I wouldn't be able to iterate over a single instance anyway, but all I want to do is use DRF to show all Actions that FK to the object with the id in the URL. views.py: class ActionDetailListView(core.views.MixedListAPIView): resource_types_list = [ { "model": ActionDetail, "serializer": ActionDetailSerializer, "filter": ActionDetailFilter } ] def get_queryset(self, *args, **kwargs): pk = kwargs.get('pk', None) return ActionDetail.objects.filter(action__parent__grandparent_id=pk) filters.py class ActionDetailFilter(django_filters.FilterSet): pass serializers.py class ActionDetailSerializer(core.serializers.HalModelSerializer): class Meta: model = ActionDetail -
python 3.6 JsonResponse issue
So i recently migrated to Python 3.6 and Django 1.11 and my JsonResponse code looked like this: return JsonResponse({'status': '1'}) it worked fine but after the migration i started getting this error: TypeError: Object of type 'bytes' is not JSON serializable After printing the type of the data passed to JsonResponse i realized python 3.6 changed this from dict to byte. So i changed the code to make sure i was passing a dict. I still get the same error after trying all of this: data = dict([('status', 0)]) print(data) print(type(data)) # print(type(json.dumps(data))) # data = {"status": '0'} # data = json.dumps(data) # json.dumps(data.decode("utf-8")) #response = json.JSONEncoder().encode({"status": 0}) #JsonResponse(data, safe=False) # response = json.dumps(data) print(JsonResponse(data, safe=False)) return JsonResponse(data, safe=False) Prints: {'status': 0} <class 'dict'> <JsonResponse status_code=200, "application/json"> with the json.dumps options y get this error instead AttributeError: 'str' object has no attribute 'get' Any help would be much appreciated -
How to use mezzanine together with allauth?
I commented mezzanine mezzanine.accounts from settings.INSTALLED_APPS and use allauth as AUTHENTICATION_BACKEND settings.py AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend" ) urls.py: urlpatterns += [ url(r"^$", include("movies.urls")), url("^blog2", blog_post_list, name="home"), url(r"^admin/", include(admin.site.urls)), url(r"^movies/", include("movies.urls", namespace="movies")), url(r"^faq/", include("fack.urls")), url(r"^accounts/", include("allauth.urls")), url(r'^captcha/', include('captcha.urls')), url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), url(r'^tz_detect/', include('tz_detect.urls')), url(r"^h/", include("home2.urls", namespace="home2")), url(r"^profile/", include("profile.urls", namespace="profile")), url("^", include("mezzanine.urls")), ] The problem is that when I go to https://localhost/blog2, that I see the base.html of allauth.accounts. Maybe mezzanine confuses allauth accounts/base.html with its own accounts/base.html? Or maybe I'm missing something else. -
ajax function throwing HTTP 200 immediately followed by HTTP 500 error
Why do I get a HTTP 200 followed immediately by a HTTP 500? I have the impression the Ajax function is called twice in a row. The objects that I expect to be created are actually created though... my ajax function is called on a form submit: $(document).on('submit','#like_form_reading_list{{ article.pk }}', function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "userprofile:like" %}', data: { journal: '{{ journal.pk }}', section: '{{ section.pk }}', article: '{{ article.pk }}', csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function showAlertLike() { $("#success_like").show().delay(2000).fadeOut(); }, error: function showAlertPin() { $("#error_like").show().delay(2000).fadeOut(); } }); }); In my view: class LikeView(generic.FormView): """ A view that creates a LikedArticles object when a user clicks on the like badge under each article displayed. """ def post(self, request): if request.method == 'POST': user = request.user journal_pk = request.POST.get('journal') section_pk = request.POST.get('section') article_pk = request.POST.get('article') journal = Journal.objects.get(pk=journal_pk) section = Section.objects.get(pk=section_pk) article = Article.objects.get(pk=article_pk) print('IN LIKE VIEW ', user, journal_pk, section_pk, article_pk) LikedArticles.objects.create( user=user, journal=journal, section=section, article=article ) return HttpResponse('') In my terminal: Internal Server Error: /like/ Traceback (most recent call last): [SOME ERROR MESSAGE] "/Users/benoitkoenig/Desktop/projet_web/harrispierce_django/hpdjango/lib/python2.7/site-packages/django/db/models/fields/init.py", line 966, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' ('IN LIKE VIEW ', at … -
Extending User Model to an Existing DB table?
I'm having issues getting my User model to extend to an existing database table. I have a feeling i'm getting close. I don't receive any errors with my following code, but anytime I login it doesn't pull in the additional information. First of all I'm using LDAP authentication with python 3.6 and Django 1.11, once a user is validated as an AD user the username and password is written to my User table. Second my existing table is not to be changed or modified and its called AllEeActive. I have a primary key that is the username in my user table called employee_ntname. I'm trying to use a signal handler to write to connect the two models. Below is my code... What am I doing incorrectly?: from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.db.models.signals import post_save from django.dispatch import receiver import django_filters class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, … -
which is the best way to deploy django web app
I have created one dummy test app in django python. So that how am I deploy on any web server in its cost free hosting. -
Cant access server media files in django + angular project
Because I wanted to do my routing in angular side I have added this url in my urls.py: url(r'^.*$', Home.as_view(), name='home'), in which my home view I just specify my base.html: class Home(TemplateView): template_name = "base.html" So that I can specify my <ng-view></ng-view> in base.html Now my issues the requests to get pictures in server side like localhost:8000/media/logo.png are going to the defined url for Home. How can I overcome this issue? Thank you. -
Unable to run local Celery worker, no module named myapp
I have a Django 1.11 project, with Celery 3.1.25, laid out like: env myproject myapp myotherapp settings settings.py __init__.py celery_init.py My __init__.py contains: from .celery_init import app as celery_app and my celery_init.py contains: from __future__ import absolute_import import os import sys import traceback from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.settings') from django.conf import settings app = Celery('myproject') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) When I go to start a local Celery worker for development testing, with: env/bin/celery worker -A myproject -l info -n sr@%h -Q somequeue it fails with the exception: ImportError: No module named myapp What's causing this? I assume it's some path problem and not being able to properly load my project's settings, but I don't see the problem with my configuration. I just upgraded to Django 1.11, and these settings were working fine in the prior version. What am I doing wrong? I tried adding print statements at the end of my celery_init.py, to ensure it's loading everything, and every line completes without error. -
Template Tag values not rendering
I am creating a blog as practice for learning how to use django. I have created the blog list and created links to the blog detail page. On the blog detail, along with the blog_Content, post_date, blog_Title information that should be on the page I am to also attempting to render the comments attached to the specific blog created by the writer/user Issue : The comments attached to the specific writer/user are not being rendered. Here is the repository if you care to take a look Here is all the code : models.py from django.db import models from datetime import date from django.urls import reverse from django.contrib.auth.models import User class Writer(models.Model): user = models.ForeignKey(User, on_delete = models.SET_NULL, null = True) writer_description = models.TextField(max_length = 400, help_text = "Enter your description here.") def get_absolute_url(self): return reverse('blog:writer-detail', args = [str(self.id)]) def __str__(self): return self.user.username class Blog(models.Model): blog_Title = models.CharField(max_length = 200) writer = models.ForeignKey(Writer, on_delete=models.SET_NULL, null=True) blog_Content = models.TextField(max_length = 2000, help_text="Create content here.") post_date = models.DateField(default = date.today) class Meta: ordering = ['-post_date'] def get_absolute_url(self): return reverse('blog:blog-detail', args = [str(self.id)]) def __str__(self): return self.blog_Title class Comment(models.Model): writer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) comment = models.TextField(max_length=1000, help_text="Create comment here.") post_date = models.DateTimeField(auto_now_add=True) class … -
launch sphinx commands "make clean" and "make html" from django.core.management call_command
Is there any way to launch sphinx commands "make clean" and "make html" from from django.core.management call_command? I need to refresh docs generated by sphinx every day, so I was thinking to use django-crontab to set a daily job. This job would call "make clean" and "make html" to automatically generate doc. But, maybe there is a simpler way to refresh docs generated by sphinx every day? Thanks! -
Django, get initials data from field in formset with shell
I'm using formset in Django 1.11, and in template rendering all works done. Now I want test formset in python shell. So I make a simple form and then a formset (2) with initials data: >>> from django import forms >>> class my_formset(forms.Form): ... my_field_1=forms.IntegerField() ... my_field_2=forms.IntegerField() ... >>> values=[{'my_field_1':10,'my_field_2':15}, {'my_field_1':84,'my_field_2':6}] >>> values [{'my_field_2': 15, 'my_field_1': 10}, {'my_field_2': 6, 'my_field_1': 84}] Building formset: >>> from django.forms import formset_factory >>> formset=formset_factory(my_formset,extra=0) >>> my_data_fs=formset(initial=values) Result formset: >>> my_data_fs <django.forms.formsets.my_formsetFormSet object at 0x7fdb688dda90> >>> my_data_fs.forms [<my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)>, <my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)>] Now I want get initials data: >>> my_data_fs.forms[0] <my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)> >>> my_data_fs.forms[0].fields OrderedDict([('my_field_1', <django.forms.fields.IntegerField object at 0x7fdb688dd7b8>), ('my_field_2', <django.forms.fields.IntegerField object at 0x7fdb688dd710>)]) but if I see single field, I get this: >>> my_data_fs.forms[0].fields['my_field_1'] <django.forms.fields.IntegerField object at 0x7fdb688dd7b8> >>> my_data_fs.forms[0].fields['my_field_1'].value Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'IntegerField' object has no attribute 'value' And if I use initials I get empty response >>> my_data_fs.forms[0].fields['my_field_1'].initial >>> What I have to do for get my initials data? -
Displaying ForeignKey attributes in DRF
When I run the api, instead of getting category name and subcategory name, I get their id, [ { "id": 1, "name": "StrawBerry", "category": 1, "subcategory": 1 } ] I actually want something like this: [ { "id": 1, "name": "StrawBerry", "category": "Fruits", "subcategory": "Berries" } ] Note: I already have category and subcategory. I just want to know how to access them. models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') class Meta: unique_together = ('parent' , 'category') def __str__(self): return self.category class SubCategory(models.Model): subcategory = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren') class Meta: unique_together = ('parent' , 'subcategory') def __str__(self): return self.subcategory class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) subcategory = models.ForeignKey('SubCategory', null=True, blank=True) def __str__(self): return self.name serializers.py class GetProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'subcategory') views.py class GetProductViewSet(viewsets.ModelViewSet): serializer_class = GetProductSerializer queryset = Product.objects.all() -
Django formset: Unable to to submit formset due to errors
Following is my model: class ContentLineConfig(models.Model): content_template = models.ForeignKey(ContentTemplate, null=False, verbose_name="Content template") line_x_start_cord = models.IntegerField(null=False, verbose_name="Line start X cordinate") line_y_start_cord = models.IntegerField(null=False, verbose_name="Line start Y cordinate") line_x_end_cord = models.IntegerField(null=False, verbose_name="Line end X cordinate") line_y_end_cord = models.IntegerField(null=False, verbose_name="Line end Y cordinate") line_fill_color = models.CharField(max_length=10, default="WHITE", choices=COLOR_CHOICE, verbose_name="Line fill color") line_width = models.IntegerField(null=False, verbose_name="Line width") archive = models.BooleanField(default=False) Form: class ContentLineConfigForm(ModelForm): class Meta: model = ContentLineConfig fields = '__all__' exclude = ['id','archive','content_template',] View: class ContentLineConfigView(ModelFormSetView): model = ContentLineConfig form_class = ContentLineConfigForm success_url = reverse_lazy('content_templates_list') template_name = 'formtemplates/test_formset.html' def form_valid(self,form): instance = form.save(commit=False) instance.content_template_id = self.kwargs.get('pk') return super(ContentLineConfigView, self).form_valid(form) def form_invalid(self,form): return super(ContentLineConfigView, self).form_invalid(form) Template: <div class="container"> <form action="." method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.as_p }} {% endfor %} <input type="submit" value="Submit" /> </form> </div> URL: url(r'^ct/(?P<pk>[\w-]+)/lines/create/$', ContentLineConfigView.as_view(), name='content_line_create') When I am submitting the formset I get the following error: NOT NULL constraint failed: contenttemplates_contentlineconfig.content_template_id But when I see the error page in detail, I see the following: formset <django.forms.formsets.ContentLineConfigFormFormSet object at 0x10821e3d0> kwargs {'pk': u'1'} Why this error? Also, If I submit empty formset, I get redirected to success_url, there is not validation happening at all, why are the validations being skipped? -
So how can I do when user clicked like button to return only value of the post
11** and python3 I was trying to add my web site like button when I add like button I worked but when someone click like button It returns same value for every post. So how can I do when user clicked like button to return only value of the post. MY HTML CODE: <button id="" data-catid="{{ post.id }}" class="btn btn-primary likes" type="button"> <span class="glyphicon glyphicon-thumbs-up"></span> Like </button> <strong class="" id="like_count">{{ post.votes }}</strong> people like this category MY JS CODE: $(document).ready(function() { $('.likes').click(function(){ var catid; catid = $(this).attr("data-catid"); $.get('/home/like_post/', {post_id: catid}, function(data){ $('#like_count').html(data); }); return false; }); }); I use this URL.PY url(r'^like_post/$', views.like_post, name='like_post'), And this VIEWS.PY: def like_post(request): cat_id = None if request.method == 'GET': cat_id = request.GET['post_id'] likes = Post.votes if cat_id: cat = Post.objects.get(pk=cat_id) if cat: likes = cat.votes + 1 cat.votes = likes cat.save() return HttpResponse(likes) ANY IDEA? -
How to use django-registration with hashed email addresses?
I am developing a website that requires users are anonymous. I want users to log in with email address and password but I want to store them both as hashes to achieve anonymity. Is this straightforward to achieve using django-registration? I understand how to set django-registration up to use email address and password for log in and I know the password is hashed by default but I do not know if I will run into lots of problems if I want to store the email address as a hash too. I don't particularly care what hashing algorithm is used at this stage; I just need a simple example for now. At the very least I know I will need to set up a custom user class, a custom user form, and a custom authentication backend. I am unsure whether I will encounter big problems with getting django-registration to verify email addresses with its hmac workflow. Can anyone give me a simple example of how to do this or tell me the steps I need to take to get hashed email addresses working? Alternatively, I am not wedded to django-registration so please feel free to recommend a different approach if there … -
How to pass a custom schema to a drf detail_route?
I have the following route: @detail_route(methods=['post'], permission_classes=[IsOperator], schema=AutoSchema(manual_fields=[ coreapi.Field('size', location='query', schema={'type': 'number', 'example': 1024}), coreapi.Field('filename', location='query', schema={'type': 'string', 'example': 'telemetry.tlog'}) ])) def get_upload_url(self): # ... When I go to a view that shows my schema, I get: I get the following error: AttributeError: 'AutoSchema' object has no attribute '_view' Stack trace: File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework_swagger/views.py" in get 32. schema = generator.get_schema(request=request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/generators.py" in get_schema 279. links = self.get_links(None if public else request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/generators.py" in get_links 317. link = view.schema.get_link(path, method, base_url=self.url) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/inspectors.py" in get_link 166. fields = self.get_path_fields(path, method) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/inspectors.py" in get_path_fields 237. view = self.view File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/inspectors.py" in view 123. assert self._view is not None, "Schema generation REQUIRES a view instance. (Hint: you accessed `schema` from the view class rather than an instance.)"