Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assigning class name to static property of a class
folks! How can I assign a class (in the example bellow, 'A') to a static property of another class explicitly? The interpreter is not recognizing 'A'. See code sample bellow: class A: """ Generic class -- nothing special about this particular one """ def __init__(self): pass class B: """ Option 1, not allowed. Interpreter does not recognize 'A'. Why? Is there a way to circumvent this? """ var = A def __init__(self): pass class C: """ Option 2, allowed; however, terrible for readability. """ var = None def __init__(self): C.var = A My idea was for the class to look nice and simple just like when declaring a Django model, where you simply specify the schema as static properties. In this case, though, the property is a class. Thank you! -
Django rest PUT request serializer fails to update model with foreign key
I have two models like following: class Task(models.Model): user = models.ForeignKey(User, blank=True) what_task = models.CharField(max_length=100, ) #This helps to print in admin interface def __str__(self): return u"%s" % (self.what_task) class Step(models.Model): task = models.ForeignKey(Task, related_name='steps', on_delete=models.CASCADE, ) what_step = models.CharField(max_length=50, blank=True, ) #This helps to print in admin interface def __str__(self): return u"%s" % (self.what_step) And I have written serializers: class StepSerializer(serializers.ModelSerializer): class Meta: model = Step exclude = ('task',) class TaskSerializer(serializers.ModelSerializer): steps = StepSerializer(many=True) class Meta: model = Task fields = '__all__' def create(self, validated_data): steps_data = validated_data.pop('steps') task = Task.objects.create(**validated_data) for step_data in steps_data: Step.objects.create(task=task, **step_data) return task def update(self, instance, validated_data): steps_data = validated_data.pop('steps') instance.what_task = validated_data.get('what_task', instance.what_task) instance.how_often = validated_data.get('how_often', instance.how_often) instance.how_important = validated_data.get('how_important', instance.how_important) instance.why_perform = validated_data.get('why_perform', instance.why_perform) instance.why_important = validated_data.get('why_important', instance.why_important) instance.possible_improvement = validated_data.get('possible_improvement', instance.possible_improvement) instance.existing_solutions = validated_data.get('existing_solutions', instance.existing_solutions) instance.how_important_improvement = validated_data.get('how_important_improvement', instance.how_important_improvement) instance.advantages_of_improvement = validated_data.get('advantages_of_improvement', instance.advantages_of_improvement) instance.save() for step_data in steps_data: Step.objects.update(task=task, **step_data) return instance My view: @api_view(['GET', 'POST']) def task_list(request): """ List all tasks, or create a new task. """ if request.method == 'GET': print(request.user) tasks = Task.objects.filter(user=request.user.id) serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.data) print(request.data) if serializer.is_valid(): serializer.save(user=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, … -
Django URL with arguments pointing to the same page using "with as template"?
This is the weirdest problem I have ever come across. Here is it: URLS.py from django.conf.urls import url from . import views app_name = 'discussions' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>Q[0-9]+)$', views.question, name='question'), ] Views.py def index(request): return render(request, 'discussions/discussion.html', {"questions": Question.objects.all(), "activities": Activity.objects.all()[:10]}) #details for this function question are not neccessary but still I have added them. def question(request, question_id): question_id = int(question_id[1:]) question = get_object_or_404(Question, id=question_id) questions = Question.objects.all() related = [] answers = Answer.objects.filter(QID=question) for q in questions: score = (similar(q.title, question.title)) if score > 0.3 and score != 1: related.append(q) votes = Vote.objects.filter(username=User.objects.get(username=request.user.username)).filter( Q(QID=question_id) | Q(AID__in=Answer.objects.filter(QID=question_id).values_list('id', flat=True))) return render(request, 'discussions/question.html', {"question": question, "votes": votes, "related": related, "answers": answers, "activities": Activity.objects.all()[:7], "form": AnswerForm()}) Models.py class Question(models.Model): title = models.CharField(max_length=200 , default="") description = models.CharField(max_length=1055, default="") date = models.DateTimeField(default=datetime.now, blank=True) username = models.ForeignKey(User, on_delete=None) votes = models.IntegerField(default=0) count = models.IntegerField(default=0) def __str__(self): return self.title discussion.html {% for question in questions|dictsortreversed:"votes" %} <li class="list-group-item justify-content-between" data-toggle="tooltip" data-placement="top" title="asked by {{ question.username }} on {{ question.date }} has {{ question.count }} answers"> <a href="{% url 'discussions:delete' with 'Q'|add:question.id as template %}" style="color: black"><h5>{{ question.id }}{{ question.title }}</h5></a> <span class="badge badge-default badge-pill bg-{% if question.votes >= 0 %}success{% else %}danger{% … -
django-import-export KeyError: u'CUSTOM_PRIMARY_KEY'
class ProductResource(resources.ModelResource): class Meta: model = Product exclude = ('pub_date','modified_date',) import_id_fields = ('CD-SKU',) class ProductAdmin(ImportExportModelAdmin): resource_class = ProductResource The error is: Line number: 1 - u'CD-SKU' 0H041501, VOL3380235300029, 3380235300029, B00FIZJI0K, 11.59, None, None, None, None, None, None, None, None, None Traceback (most recent call last): File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/resources.py", line 434, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/resources.py", line 258, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/resources.py", line 252, in get_instance return instance_loader.get_instance(row) File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: u'CD-SKU' After reading related questions, I removed the native auto generated id and used my own field as the primary. Mentioned it in the Resource class. But still its not able to import. Would appreciate all the help. Thanks! -
Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am using sphinx and was trying to generate documentation for my Django project. I decided to first try to document the models so in my .rst file I did this wdland\.models ============== .. automodule:: wdland.models :members: :undoc-members: :show-inheritance: But the get the following errors WARNING: /home/fabou/wdlandenvpy3/source/docs/wdland.rst:9: (WARNING/2) autodoc: failed to import module 'wdland.models'; the following exception was raised: Traceback (most recent call last): File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 657, in import_object __import__(self.modname) File "/home/fabou/wdlandenvpy3/source/wdland/models.py", line 35, in <module> class Device(models.Model): File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/db/models/base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class wdland.models.Device doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. After some google search I found a solution here Django 1.9 deprecation warnings app_label see comment from Роман Арсеньев on “Jan 11 '16 at 14:54” I went in my models.py and added “class Meta: app_label” as per above post to every single class I had in models.py. This fixed the problem and I was able to generate the documentation for my models using the sphinx-build script. Now I wanted to do the same for views.py and did this in my .rst file wdland\.views ============= .. automodule:: wdland.views :members: :undoc-members: :show-inheritance: But on compile I get … -
Redis backend not working?
I'm using Celery with redis in my django project. I'm trying to call the expire function with a delay of 10 seconds from my celery_app. Whenever the function executes, the page just says localhost did not respond. I assume its because my backend is not working? Can anyone please help? P.S. the get method works if I remove the 2 lines with result celery_app.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IrisOnline.settings') app = Celery('IrisOnline', broker='redis://localhost:6379/0',backend="redis://localhost:6379/0",include=[ "IrisOnline.tasks", "order_management.tasks" ]) app.conf.update( task_serializer='json', accept_content=['json'], result_serializer='json', timezone='Asia/Manila', ) app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'IrisOnline.tasks.printthis', 'schedule':(crontab(hour=13,minute=33)), }, } app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(name="expire") def expire(): print("object expired") views.py def get(request): if "approved_cart" not in request.session or not request.session["approved_cart"]: return redirect("/checkout/cart/") cart = request.session["cart"] customer = Customer.objects.get(user=request.user) order = Order.objects.create(customer=customer) result = expire.apply_async(countdown=40) #these causes the errors result.get() for product_id, quantity in cart.items(): # Deduct from inventory product = Product.objects.get(id=product_id) product.quantity -= quantity product.save() # Add quantity to order OrderLineItems.objects.create( product=Product.objects.get(id=product_id), quantity=quantity, parent_order=order ) request.session["cart"] = {} # Empty cart request.session["approved_cart"] = False request.session.modified = True context = make_context(request) context["total_price"] = order.total_price … -
How to set virtualenvironent in Django so it redirects to proper Location
I am virtuallenvwrapper to isolate my Django Projects, but I can't point it to the required location on Workon my_project How to fix this Issue ? I reffered this site for installation:http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/ -
How to list the objects that aren't as fk in other tables
I have a table Users, and an user can be in a Student table or Teacher table. How can I list only the users that aren't in none of the 2 tables ? list = models.Users.objects.all('') -
PyPDF2.utils.PdfReadError: Could not find xref table at specified location
I have one problem after creating Django migration with the addition of validation of the file field. my model is: class TextItemSourceFile(models.Model): FILE_TYPE = 'text_source' BASE_DIR = 'text_source' EXT_WHITELIST = ('.doc', '.docx', '.odt', '.pdf', '.rtf', '.djvu', '.djv') MIME_WHITELIST = ( 'application/CDFV2-unknown', # for doc and docx files 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # for odt files 'application/vnd.oasis.opendocument.text', # for pdf files 'application/pdf', 'application/x-pdf', # for rtf files 'text/rtf', 'application/rtf', # for djvu files 'image/vnd.djvu', 'image/x-djvu' ) MAX_SIZE = 10 * 1024 * 1024 uuid = models.UUIDField( verbose_name="UUID", primary_key=True, default=uuid.uuid4 ) author = models.ForeignKey( verbose_name="author", to='auth.User' ) date_created = models.DateTimeField( verbose_name="date created", auto_now_add=True ) name = models.CharField( verbose_name="original file name", max_length=200, null=False, blank=False ) file = models.FileField( verbose_name="text file", upload_to=get_file_path, max_length=200, storage=OverwriteStorage(), null=False, blank=False, validators=[ FileValidator( extension_whitelist=EXT_WHITELIST, mime_whitelist=MIME_WHITELIST, max_size=MAX_SIZE ) ] ) cover = models.OneToOneField( verbose_name="cover image", to=TextItemCoverFile, null=True, blank=True ) is_used = models.BooleanField( verbose_name="is used", default=False ) def save(self, *args, **kwargs): prev = TextItemSourceFile.objects.filter(uuid=self.uuid).first() super().save(*args, **kwargs) if attr_changed(self, prev, 'file'): file_extension = os.path.splitext(self.file.name)[1].lower() if file_extension == '.pdf': cover = TextItemCoverFile( author=self.author, is_used=True ) cover.file.save('cover.jpg', make_pdf_preview(self.file.name)) cover.save() self.cover = cover self.save(force_update=True) else: self.cover = None self.save(force_update=True) My validator is: @deconstructible class FileValidator(object): def __init__(self, extension_whitelist=None, mime_whitelist=None, max_size=None): self.extension_whitelist = extension_whitelist self.mime_whitelist = mime_whitelist self.max_size … -
Django model form data not being saved
I have a profile model for the User which has fields like "bio" and "cover" representing the General information about the profile of the user etc.. I want those two things to be able to be edited by the User. I did everything from urls.py to forms.py to views.py to template etc and it looks like I can submit the data and it looks like its validating but the data isnt being saved.. i dont know how.. here are my files, i've included more code than neeeded just to see if maybe the code somewhere else is in fault. note, the code that is not working is the one with "general" somewhere included in the name urls.py from django.conf.urls import include, url from . import views app_name = 'profili' urlpatterns = [ #profile url(r'^$', views.ProfilePage, name='profile'), url(r'^edit/$', views.EditProfile, name='edit_profile'), url(r'^edit/general/$', views.EditGeneralProfile, name='edit_general_profile'), url(r'^edit/password$', views.EditPassword, name='edit_password'), url(r'^edit/delete/$', views.DeleteProfile, name='delete_profile'), ] views.py def EditProfile(request): if request.method == 'POST': form = EditProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect('/profile') else: form = EditProfileForm(instance=request.user) formpw = PasswordChangeForm(user=request.user) generalform = EditGeneralProfileForm(instance=request.user) args = { 'form': form, 'formpw': formpw, 'generalform': generalform, } return render(request, 'profili/editprofile.html', args) @login_required def EditGeneralProfile(request): generalform = EditGeneralProfileForm(request.POST, request.FILES, instance=request.user) if generalform.is_valid(): … -
How to change status bar color in django html based on variable value
Good afternoon, Im making a django project that gets some data from an api and then renders it in a table. I have this html table, one of the cells is <td>{{status}}</td> where status is the status of a service running on a remote server. Started or stopped. Its contained within an html for loop so that each row is generated dynamically based on the data results. Currently the way the table is set up the status is just simply displayed in the table as plain text "Started" or "Stopped". I would like to replace that with a progress bar instead of the text. something like <td><progress value="100" max="100" style="background-color:green; width:60px; height:20px" ></progress></td> However i want the bar to be red if the status is stopped and green is the status is started. Is there any way to do this? i know python decently but i dont really have any front end experience. Any help would be greatly appreciated. Thanks! -
Using my own template beside django rest framework one to upload a file
I did the upload of an image with some information using a form with Django Rest Framework, it works but displayed using DRF default template, I want to use my own template so that i can add more button and link. When i looked at that, it's about creating my template "api.html" in a folder rest_framework in my folder of templates but i don't know what i can put in the template content that i want to create. My views : class ImageViewSet(viewsets.ModelViewSet): queryset = Video.objects.all() serializer_class = ImageWatermarkSerializer filter_backends = (filters.DjangoFilterBackend,filters.OrderingFilter,) filter_fields = ('completed',) ordering = ('-date_created',) For the serializer : class ImageWatermarkSerializer(serializers.ModelSerializer): image = serializers.FileField(max_length=None,use_url=True) class Meta: model = Image fields = ('id', 'image_name', 'image_desc', 'date_created', 'image', 'completed', 'size') My models : class Video(models.Model): image_name = models.CharField(max_length=50) image_desc = models.TextField(max_length=200) completed = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now=True) image = models.FileField(upload_to='imgs', default='/home/None/No-image.mp4') size = models.IntegerField(default=10) def __str__(self): return "%s" % self.image_name In my urls.py: router = routers.DefaultRouter() router.register(r'upl', views.ImageViewSet) urlpatterns = [ url(r'^upload/', include(router.urls)), ] -
I am a beginner in Django and facing a syntax error in urls.py
Here is my personal/urls.py. I have been trying to solve this for quite a few days. I know it must be a really silly error but help would be appreciated. from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$',views.index, name='index'), url(r'contact/',views.contact, name='contact') url(r'about/',views.about, name='about') ] And here is the views.py def index(request): return render(request, 'personal/home.html') def contact(request): return render(request, 'personal/basic.html', {'content': ['https://www.facebook.com/arjunkashyap30']}) def about(request): return render(request, 'personal/about.html', {'content': ["This is an abut page"]}) -
Django query many-to-many field
I have these two models. class Tickets(models.Model): id = models.CharField(primary_key=True, max_length=12) recipients = models.ManyToManyField(CustomUser) title = models.CharField(blank=True, max_length=100) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(primary_key=True,) user_name = models.CharField(blank=False, max_length=20) In Tickets model, recipients may include multiple users. I'm trying to 1. Read how many tickets does specific user has. 2. Regroup Tickets by recipients to get this kind of output in template. user_name1 Ticket.id Ticket.title user_name2 Ticket.id Ticket.title user_name3 Ticket.id Ticket.title I was trying really hard on "regroup", but not much result... Could someone give me some guidance? -
Django template two ifequal in chain
My problem is in the last template with ifequal chain. In the last template I have to select from model Contract acording to two parameters identified from privious two templates. I think that something is wrong in code sintax of the ifequal chain. Each ifequal separatly are also does not work. I feel myself like inside a wall. 1.template: valoare_list.html {% for valoare in valoares %} <a href="{% url 'valoare_detail' valoare=valoare.tip_valoare %}"> Contracte de valoare {{ valoare.tip_valoare }} </a><br> {% endfor %} 2. template: valoare_detail.html {% for tip in tips %} <a href="{% url 'contract_list' valoare=valoare.tip_valoare tip=tip.tip_contract %}"> Tip Contracte de {{ tip.tip_contract }} </a><br> {% endfor %} template: contract_list.html {{ valoare.tip_valoare }} <br> {{ tip.tip_contract }} <br> <br> {% for contract in contracts %} {% ifequal contract.valoare valoare.tip_valoare %} {% ifequal contract.tip tip.tip_contract %} {{ contract }} <br> {% endifequal %} {% endifequal %} {% endfor %} models.py from django.db import models class Valoare(models.Model): VALOARE_CHOICES = ( ("MICA","mica"), ("MARE","mare"), ) tip_valoare = models.CharField(max_length=4, choices=VALOARE_CHOICES, default="MICI", verbose_name='valoarea contractului') file_name = models.FileField(null=True, blank=True, upload_to='contracte/templates/contracte/img/', verbose_name='img path') def __str__(self): return self.tip_valoare class Tip(models.Model): TIP_CHOICES = ( ("BUNURI","bunuri"), ("SERVICII","servicii"), ("LUCRARI","lucrari"), ) tip_contract = models.CharField(max_length=8, choices=TIP_CHOICES, default="BUNURI", verbose_name='tipul contractului') file_name = models.FileField(null=True, blank=True, upload_to='contracte/templates/contracte/img/', … -
Django field that stores a list as a comma separated string
I'm looking for a solution to store a Python list as a comma-separated string in the database. After doing some research and concluding that Django does not come with something like this out of the box, I decided to write this myself. This is the model field I've come up with: class CommaSeparatedStringsField(models.CharField): description = "Stores list as string of comma-separated strings" def from_db_value(self, value, *args): if not value: return [] return value.split(',') def to_python(self, value): if isinstance(value, list): return value return self.from_db_value(value) def get_prep_value(self, value): return ','.join(value) def value_to_string(self, obj): return self.get_prep_value(self.value_from_object(obj)) def formfield(self, **kwargs): defaults = {'form_class': ListField} defaults.update(kwargs) return models.Field.formfield(self, **defaults) Pretty simple stuff, and so far, no problems. The form field and widget associated with this model field should be a multiple select box. Every element in the list is an option in the select field. In case you're wondering why I want this this way, it's for Bootstrap Tags Input, a input widget for entering 'tags' (multiple values). This can work using a textbox but I'd rather represent this field in Python as a list. Now there's MultipleChoiceField (which uses the MultipleSelect widget) but that has a pre-defined list of options. That's not what I … -
Trying to get sum of values in a for loop but filter is returning 0 - Django
I am just trying to get a "Thanks" count for my user based on the thanked field in this Advice model: class Advice(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) content = models.TextField() slug = models.SlugField(max_length=200, unique=True) thanked = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='adviceliked') question = models.ForeignKey(Question, null=True, blank=True, on_delete=models.CASCADE, default=1, related_name='advices') In my views I have tried thanked = Advice.objects.filter(user__username=requested_user) \ .aggregate(total_thanks = Sum('thanked')) and it works for the first "thank" but then every one after that the count gets infinitely larger. So then I tried it with annotate: thanked = Advice.objects.filter(user__username=requested_user).annotate( total=Count('thanked') ) and in my template: {% for advice in thanked %} {{ advice.total }} {% endfor %} This gets the correct "thank" count for each advice, but I need the sum of all the thanks, not just a list of "thank" counts for each advice. So then I tried this answer https://stackoverflow.com/a/5275944 to total the counts of every item in the for loop. I created the filter: @register.filter def total_thanks(thanked): a = sum(advice['thanked'] for advice in thanked) return a and in my template: {{ advice|total_thanks }} but it is only returning a sum of "0". I'm pretty sure the error is with the template tag, but when I use {{ … -
TypeError: __init__() takes 2 positional arguments but 3 were given (django-material)
I'm trying to recreate a form with Inline using django and django-stuff. I already got it once but this one is not being easy! I wish to create a form that can register a Client and its addresses, or something similar to this link here. Example 1:Adding contacts Example 2:Adding addresses I'm trying like this: Forms.py from django import forms from material import Layout, Row, Fieldset from .models import Client class Address(forms.Form):# TA FEITO public_place = forms.CharField(label='Logradouro') number = forms.CharField(label='Número') city = forms.CharField(label='Cidade') state = forms.CharField(label='Estado') zipcode = forms.CharField(label='Cep') country = forms.CharField(label='País') phone = forms.CharField(label='Fone') class Meta: verbose_name_plural = 'endereços' verbose_name = 'endereço' def __str__(self): return self.profissao class ClientModelForm(forms.ModelForm): class Meta: model = Client fields = '__all__' layout = Layout( Fieldset("Client", Row('name', ), Row('birthday','purchase_limit'), Row('address1', ), Row('compra_sempre', ), ), ) Views.py import extra_views from braces.views import LoginRequiredMixin from extra_views import CreateWithInlinesView, NamedFormsetsMixin from material import LayoutMixin, Fieldset from material.admin.base import Inline from danibraz.persons.forms import * from .models import Address class ItemInline(extra_views.InlineFormSet): model = Address fields = ['kynd', 'public_place','number','city','state','zipcode','country','phone']#campos do endereço extra = 1# Define aquantidade de linhas a apresentar. class NewClientsView(LoginRequiredMixin,LayoutMixin, NamedFormsetsMixin, CreateWithInlinesView): title = "Inclua um cliente" model = Client #print('Chegou na linha 334') layout = Layout( Fieldset("Inclua um … -
How add Authenticate Middleware JWT django?
I am trying to create a middleware to authenticate with JWT but in the view the request.user is always AnonymUser. When I verify that the middleware changes the request.user by the User Model, it does, but upon reaching the view, for some reason the request.user is always anonymousUser I'n using Django 1.11 # coding=utf-8 from django.utils.functional import SimpleLazyObject from django.utils.deprecation import MiddlewareMixin from django.contrib.auth.models import AnonymousUser, User from django.conf import settings from django.contrib.auth.middleware import get_user from rest_framework_jwt.authentication import JSONWebTokenAuthentication import jwt import json class JWTAuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): request.user = SimpleLazyObject(lambda: self.__class__.get_jwt_user(request)) @staticmethod def get_jwt_user(request): user_jwt = get_user(request) if user_jwt.is_authenticated(): return user_jwt token = request.META.get('HTTP_AUTHORIZATION', None) user_jwt = None if token is not None: try: user_jwt = jwt.decode( token, settings.SECRET_KEY, algorithms=['HS256'] ) user_jwt = User.objects.get( id=user_jwt['user_id'] ) except Exception as e: user_jwt = AnonymousUser return user_jwt MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'user.middlewares.JWTAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
How to create multiple forms in django according to user input?
I want user to enter an input. Based on the input I want to create same form that many times and process them. -
Bulk clear ManyToMany after object traversal
I have the following data models: class ArticleSet(Model): pass class Article(Model): article_set = ForeignKey(ArticleSet, related_name = 'articles') attachments = ManyToManyField(Attachment, related_name='articles') Now I have an ArticleSet and want to clear (not delete!) all attachments from them. The following will work: for article in article_set.articles.all(): article.attachments.clear() However, this will cause a database query per article in the article_set. Is there a way to do the same in a single call to the database? I am using Django 1.11. p.s. This question is related to How do I remove multiple objects in a ManyToMany relationship based on a filter?, but in that question there is no model traversal before deleting relations. -
command: `heroku run python manage.py createsuperuser` not working
I tried running heroku run python manage.py createsuperuser command on a basic python with django project but it give me error. I've done git push heroku master and then heroku run python manage.py migrate and then heroku run python manage.py createsuperuser. I don't know what is wrong with my project. Can anyone tell me what's wrong? Thank you very much! here is a screenshot of what error it gives me when i try to run the said command above: screenshot text: WARNINGS: blog.Comment.created_date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` You have 19 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, blog, contenttypes, sessions. Run 'python manage.py migrate' to apply them. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
Django Rest Framework nested objects create with request.user
I want my visitors to have function for creating and get list of Proposals. User sends all of the data except the author of Proposal (because the auth is user himself), so I'm trying to extend request.data with request.user like this: # proposals/views.py class ProposalsList(ListCreateAPIView): permission_classes = (IsAuthenticatedOrReadOnly,) queryset = SeekerProposal.objects.all() serializer_class = SeekerProposalSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data={ **request.data, "author": request.user.id, }) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Although, I want to GET the proposals list with serialized author (user), so my serializer looks like: # proposals/serializers.py class ProposalSerializer(serializers.ModelSerializer): author = UserSerializer() class Meta: model = SeekerProposal fields = ('text', 'author') The problem is that I'm getting users correctly (serialized to dict), but I can't create new Proposal because it wants to "author" be a dict. Questions: Is there a way to let view be ListCreateAPIView and author = UserSerializer() while GET list with serialized data and create proposal by request.user.id? Maybe there is another way to add authorized user to Proposal author field? Also, this is my model: # proposals/models.py class SeekerProposal(models.Model): text = models.TextField(blank=False, null=False) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user), ) -
Django Error---'ZipCode' is an invalid keyword argument for this function
i received this error while trying to update my first database evercreated in django :D I am happy about that, but i need your help with my error: Traceback (most recent call last): File "<input>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py", line 571, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'ZipCode' is an invalid keyword argument for this function This is the code i used in order to update the DB. c = BusinessName(AccountingCode="0002", RefID="0001101002", FullName="Johny Cohen", Aliases="The Wolfies", Address="Florilor Street 42", City="IF", ZipCode="89899", State="Romania", Country="Romania", TypeofSanctions="SDN",Monitoring="Y", BatchNumber="1", FileName="mybeloved", UploadDate="2017-01-26", UploadBy="cohen", Decision="Noneed", Status="noneed", EngineDecision="noneed", WhoAdjudicated="cohen",DateOfAdjudication="2017-01-26", SdnType="Entity") And here is my Model: class BusinessName(models.Model): AccountingCode = models.CharField(max_length=50) RefID = models.CharField(max_length=50, default="") FullName = models.CharField(max_length=250) Aliases = models.CharField(max_length=250) Address = models.CharField(max_length=500) City= models.CharField(max_length=50) ZipCode= models.IntegerField State = models.CharField(max_length=250) Country= models.CharField(max_length=250) TypeOfSanction= models.CharField(max_length=250) Monitoring= models.CharField(max_length=50) BatchNumber= models.IntegerField # tr pus automat FileName= models.CharField(max_length=250) # tr pus automat1 UploadDate = models.DateField(max_length=250) # tr pus automat UploadBy= models.CharField(max_length=250) # tr pus automat Decision= models.CharField(max_length=250) # tr pus Ulterior Status= models.CharField(max_length=250) # tr pus automat EngineDecision= models.CharField(max_length=250) # tr pus automat WhoAdjudicated= models.CharField(max_length=250) DateOfAdjudication= models.CharField(max_length=250) SdnType = models.CharField(max_length=250) #Entity or Individual Thank you in advance, Cohen -
Django Generic Views Usage Error
I just imported generic views successfully and here comes the problem when I want yo use them in views the server just gives an error directed to "." (period) in generic.ListView... Here is the code I am currently working on. def IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'question_list' def get_qureyset(self): return Question.objects.order_by('-published_date')[:5]