Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queryset and serializer is giving the error 'int' object is not iterable
I have two models. A model which contains the students and teamnames and the other model (Tester) contains the rate (1 until 10) the gave for the fields QA1 and QA2. Every team has its own page, where they can find the average rates for QA1 and QA2 per team. For this, i need a queryset that is filtering the team and calculates the averages for each team. The code was working until I tried to create the filters. This is the documentation I used: https://www.django-rest-framework.org/api-guide/generic-views/#listapiview https://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-url I already tried to delete or add arguments, I also tried to change get_queryset. So far without succes. Im getting the same error or different errors. I really don't know how to solve this. serializers.py class TesterSerializer(serializers.ModelSerializer): slug_teamname = serializers.SlugRelatedField( slug_field='slug_teamname', read_only=True, many=True) queryset = serializers.SerializerMethodField() lookup_field = 'slug_teamname' extra_kwargs = {'url': {'lookup_field': 'slug_teamname'}} class Meta: model = Tester fields = ('slug_teamname','queryset') views.py class TesternieuwListView(generics.ListAPIView): serializer_class = TesterSerializer template_name = 'tester/tester_list.html' # filter_backends = (DjangoFilterBackend) lookup_field = 'slug_teamname' lookup_url_kwarg = 'slug_teamname' def get_queryset(self): slug_teamname = self.kwargs['slug_teamname'] return Tester.objects.filter(slug_teamname__slug_teamname=slug_teamname).values('slug_teamname').annotate( QA1__avg=Avg('QA1'), QA2__avg=Avg('QA2'), A snippet of my models.py created_by = models.ForeignKey(User, on_delete=models.CASCADE) slug_teamname = models.ForeignKey(Team, on_delete=models.CASCADE) QA1 = models.DecimalField(max_digits=4, decimal_places=0) QA2 = models.DecimalField(max_digits=4, decimal_places=0) My … -
Need Nginx proxy to forward Authorization to django backend, How?
I will be very precise on this, as i have tried every solution on the web. I am in desperate need of help. I am attatching my default.conf file for my nginx. I am able to use the django apis successfully without nginx. Please help me. Anyone ? It says 401: unauthorized, meaning i am not able to pass the authorization token to django backend through nginx. I am sure someone would have gone through this process because it is a common use case. HELP location ~ /backend/(?<section>.+) { proxy_pass http://10.128.0.5:8001/$section; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header Authorization "9ca0c2c79b1acab6c1b2a699a391f08f7aa68bdf"; } -
Jinja custom extension: parse arguments in any order they are written
I've built a custom Jinja extension that, when used inside a template, looks something like this: {% field "text" name="color" value="Yellow" class="bold" %} And once it's been interpreted by Jinja, the resulting HTML is: <div class='bold'>Yellow</div> It works fine, except for the fact that the parameters must be written in exact order (name, then value, and finally class). I would like to make it handle the parameters in a more flexible way, ie. that that can be specified in any order. This is how I've implemented it: def parse(self, parser): lineno = parser.stream.__next__().lineno context = jinja2.nodes.ContextReference() tag = parser.parse_expression().value if tag not in self.environment.supported_tags: raise TemplateSyntaxError(f'Unexpected template tag {tag}. ' f'Expected one of {self.environment.supported_tags}.', lineno, tag) value = css_class = '' if parser.stream.current.test('name:name'): parser.stream.skip(2) parser.parse_expression() # parse the field name parser.stream.skip_if('comma') if parser.stream.current.test('name:value'): parser.stream.skip(2) value = parser.parse_expression() parser.stream.skip_if('comma') if parser.stream.current.test('name:class'): parser.stream.skip(2) css_class = parser.parse_expression() parser.stream.skip_if('comma') args = [value, css_class, context] call = self.call_method('_create_field', args) return jinja2.nodes.Output([call], lineno=lineno) I understand why it's behaving the way it is, but I don't know how to parde the parameters in any given order. Any idea how to make it accept the parameters in any order? -
tcp serwer with django
For easy understanding, I simplify description of my app. App has two main features: 1. show data from database in a beautiful way :) 2. save data provide by POST or GET request (json) I want to speed up the application and relieve network, to do that I want to make able to send data to the app by tcp. Have you any suggestions on how to do it? I want to have as much as its possible common code. In ma app I have a method "parse_and_save_to_db(json)", which is used by the view and I want to use it in tcp server. -
Update Static JSON file from Django page
I'm building an app at work for part number creation/management with Django. I current use a json file to inform/enforce some of the part number rules on the part number creation page. I'd like to be able to update this json file from the web page so that when we need to edit or add to the current part number schemes the person doing so doesn't need a technical background. To do this I want to send a json object to the view and use it to update/replace the original json file. I've tried to access it using the static url static('/javascript/json_file_name.json') I've also tried to access it using its file path. both have not been successful. This is a tool used inside a private network hosted on a raspberry pi and won't be public. Thanks in advance! -
How to subscribe a celery task to an existing RabbitMQ exchange?
I'm currently writing a chat messenger using GRPC/RabbitMQ for group chats. I have an API in Django/DRF that handles authentication/message logs/text and email alerts etc. To do this I would like to create a celery task that subscribes to each group message exchange but I'm unclear if there is there a way to bind a celery task to the message exchanges. Is it realistic/possible to create celery tasks that subscribe to the chat exchanges I create? If not how would you solve/handle these duties? -
Selenium - Python/Django - Count records for a model
I newbie in Django/Python and moreover in functional testing I use selenium I try to test "add" in a model so I try to calculate record number (number = MyModel.objects.count()) before and after adding to compare but my count return 0 even if there is 8 records in my database it is not possible to count from a class test? -
How to handle multiple dynamic user types in Django?
I have a problem I have been stuck on for days now and can't seem to find the solution. In my models I have Companies. Each company has 2 Group's for authentication and authorization: Supervisor and Non-Supervisor. Of these 2 Group's there will be several dynamic sub-groups for each company, which I call Employee Type. These EmployeeType's will be able to be created by the Company Admin within the Admin panel then assigned to one of the Groups. class Company(models.Model): .... group = models.ManyToManyField( Group, related_name='companies_group' ) class EmployeeType(models.Model): .... employee_type = models.CharField( max_length=32, default='Server' ) group = models.ForeignKey( Group, on_delete=models.CASCADE, null=True ) class User(AbstractUser): .... company = models.ForeignKey( Company, on_delete=models.CASCADE, null=True ) group = models.ForeignKey( Group, on_delete=models.CASCADE, null=True ) employee_type = models.ForeignKey( EmployeeType, on_delete=models.CASCADE, null=True, ) I have several questions: Should the UserProfile be handling the user's Group and Employee Type? Should the CompanyProfile be handling the companies' Groups? Is this the correct way to model the dynamic user type creation? Each company will have different EmployeeTypes. Do I need to add EmployeeTypes to Company? Apologies if it seems very simple but I am confused when the EmployeeTypes become dynamic. I end up having circular logic when I try … -
how to extend templates in djangi
I created blog page. while clicking on a post title it will opemsin single page. but i created new html page , views and added path in urls Events page html code: this is page it will displays all posts below images are added {% extends 'polls/base_1.html' %} {% block content %} <p>Events page </p> <div> <h2><a href="{% url 'event_detail' pk=event.pk %}">{{ event.event_title }}</a></h2> <p>published: {{ event.event_release_date }}</p> <p>{{ event.event_description|linebreaksbr }}</p> {% for author in event.event_author.all %} <p>{{ author }}</p> {% endfor %} </div> {% endblock %} events detail page code: this is page page where open while clicking on post {% extends 'polls/base_1.html' %} {% block content %} <div class="post"> <div class="date"> <p>published: {{event.event_release_date }}</p> </div> <h2>{{ event.event_title }}</h2> <p>{{ event.event_description|linebreaksbr }}</p> </div> {% for author in event.event_author.all %} <p>{{ author }}</p> {% endfor %} {% endblock %} -
Django: Set pk from own model as default value in own column
What do I have to do, to assign the pk as a default value? This doesn't work: from django.db import models class TeamMember(models.Model): id = models.AutoField(primary_key=True) order_listing = models.IntegerField(default=id) -
Django error [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
When I try to add the path of the app in the urls.py it creates this error. I am using Django 2.2.6 I have checked INSTALLED_APP = [], they are all fine. The urls.py code outside the app. urlpatterns = [ path('', admin.site.urls), path('/primaryDetails/', include('manipulate.urls')) ] The urls.py code inside the app. urlpatterns = [ path('/primaryDetails/', views.loginDetails, name='loginDetails'), ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Django.manipulate', 'corsheaders', 'rest_framework' ] The errors are :- ModuleNotFoundError: No module named 'manipulate' and OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
Minimise code repetition by creating a reusable template
I have a template which includes 4 different paginators that only differ in context variables (tasks_today, tasks_tomorrow, ... etc.), and I want to minimise code repetition so I don't have 4 different paginator templates. Template: <div class="wrapper"> <h3>Today</h3> <table> {% if tasks_today %} {% for task in tasks_today %} {% include 'todo/task_table_row.html' %} {% endfor %} {% include 'todo/paginator_today.html' %} {% else %} <p>No tasks for today.</p> {% endif %} </table> <h3>Tomorrow</h3> <table> {% if tasks_tomorrow %} {% for task in tasks_tomorrow %} {% include 'todo/task_table_row.html' %} {% endfor %} {% include 'todo/paginator_tomorrow.html' %} {% else %} <p>No tasks for tomorrow.</p> {% endif %} </table> <h3>Upcoming</h3> <table> {% if tasks_upcoming %} {% for task in tasks_upcoming %} {% include 'todo/task_table_row.html' %} {% endfor %} {% include 'todo/paginator_upcoming.html' %} {% else %} <p>No upcoming tasks.</p> {% endif %} </table> <h3>Past</h3> <table> {% if tasks_past %} {% for task in tasks_past %} {% include 'todo/task_table_row.html' %} {% endfor %} {% include 'todo/paginator_past.html' %} {% else %} <p>No tasks in the past.</p> {% endif %} </table> </div> paginator_*: {% load url_replace %} {% if tasks_today %} <div class='paginator'> <nav aria-label="Page navigation"> <ul class="pagination"> {% if tasks_today.has_previous %} <li class="page-item"> <a class="page-link" href="?{% url_replace … -
How to POST an empty ForeignKey field in Django?
I'm fairly new to this. I have an app that is basically a check in/check out form. The form has 3 fields, two of which are required and one that is optional. One of the required fields in an "Area" and the only field that is not required is the "Station" because not every area has a station, so sometimes there will be no option to choose from station. It currently works fine if you fill out all 3 fields, but not if the station is empty, even if the area doesn't have a station. I get this error: ValueError: invalid literal for int() with base 10: '' I'm pretty sure the problem lies in my views.py, in one of my if statements for both the enter/leave because it happens on both actions, but I'm not sure what exactly it could be. The point of those if statements is that: If a person entered an area and forgot to leave and then entered another area, the program would create a new entry and not touch the previous area entry after the person leaves the new area (a person can enter and leave same area/station multiple times), so when they leave … -
Need to keep selected option with if conditional on template
I've a list of options in my template. I need to keep selected month after the "Buscar" button is pressed and has returnd the correct value. I've heard that forms in Django keep the last selected option automatically, but mine doesn't. <form method="get" action="{% url 'order:ingresos' %}"> <div class="input-group"> <div class="input-group-prepend"> <label class="input-group-text" for="inputGroupSelect01">Mes</label> </div> <select class="custom-select" searchable="Search here.." value={{filtromes}} name="filtromes"> <option value="0" disabled>Elegir mes</option> <option value="1">Enero</option> <option value="2">Febrero</option> <option value="3">Marzo</option> <option value="4">Abril</option> <option value="5">Mayo</option> <option value="6">Junio</option> <option value="7">Julio</option> <option value="8">Agosto</option> <option value="9">Setiembre</option> <option value="10">Octubre</option> <option value="11">Noviembre</option> <option value="12">Diciembre</option> </select> <div class="input-group-append"> <input class="btn btn-outline-secondary" type="submit" name="buscar" value="Buscar" style="margin-bottom: 0px;" /> </div> </div> </form> I've search and found that I can return the value of the selected option and do a if condition to find what option was selected and add the selected attribute to it, like this: <option value="0" disabled>Elegir mes</option> <option value="1" {% if filtromes == "1" %}selected{% endif %} >Enero</option> <option value="2" {% if filtromes == "2" %}selected{% endif %} >Febrero</option> But now I'm getting this error: TypeError at /ordenes/ingresos float() argument must be a string or a number, not 'NoneType' ... revenue = float(revenue['revenue']) #necessary to properly render in template / not as Decimal views.py: from … -
Get total amount of items in for loop
<div class="imageCounter"> {% for item in page.blogpage_images.all %} {{ forloop.counter }} of {{ forloop.counter }} {% endfor %} </div> of {{ forloop.counter }} is the part that I would like to display the number of items in the list if possible? -
Post data has form input but Django modelform is not saving it
I've looked through a bunch of the other posts - but I can't find anything quite fitting to my scenario. I've got a bit of data that is coming across in the POST but then when I save the form - the data is not appearing in the database. I'm a bit perplexed as to why this is and I've tried various things, but none of them really seem to apply to my situation. Most have to do with the data not being posted, my data is posted, it's just not saving. I've got the following model: class Payment(models.Model): METHODS = ( ("Cash", "Cash"), ("Check", "Check"), ("Credit Card", "Credit Card") ) amount = models.DecimalField(decimal_places=2, max_digits=6) method = models.CharField( max_length=15, choices=METHODS, default="Credit Card" ) stripe_id = models.CharField(max_length=255, blank=True, null=True) check_number = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) Here is my PaymentForm: class PaymentForm(forms.ModelForm): method = forms.CharField( max_length=25, widget=forms.TextInput(attrs={ "class": "form-control", "readonly": "True", }) ) amount = forms.DecimalField( decimal_places=2, max_digits=6, widget=forms.TextInput(attrs={ "class": "form-control", "readonly": "True", }) ) stripe_id = forms.CharField( widget=forms.HiddenInput(), required=False ) check_number = forms.IntegerField( widget=forms.TextInput(attrs={"class": "form-control"}), required=False ) class Meta: model = Payment fields = ( 'amount', 'method', 'stripe_id', 'check_number', ) def clean_check_number(self): method = self.cleaned_data["method"] check_number = self.cleaned_data["check_number"] if method … -
django fail migrations with mysql - TypeError: int() argument must be a string, a bytes-like object or a number, not 'CustomUser
we had our project working with sqlite, but when tried to use mysql as db, we encountered this problem: PS C:\GitHub\Javagochi\javagochi-server> python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, authtoken, contenttypes, items, javagochi, sessions, sites, trades, users Running migrations: Applying javagochi.0003_auto_20190330_1208...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Program Files\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Program Files\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\operations\fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\schema.py", line 523, in alter_field old_db_params, new_db_params, strict) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\schema.py", line 627, in _alter_field new_default = self.effective_default(new_field) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\schema.py", line 239, in effective_default return field.get_db_prep_save(default, self.connection) … -
In Python, how can I convert a Docx to a PDF or Image and a PDF to an Image without using ghostscript or ImageMagick?
So, I have a use case for needing to convert documents that come in different formats (docx and pdf) and I need to convert them to an image. I have looked into PDF2Image, WAND, and PYMUPDF. I've also searched all over stack overflow, reddit, and quora. My google fu is failing me in this en-devour. The environment I am using would be on pythonanywhere, so I don't believe I could use ghostscript or imagemagick on these scripts. I could be wrong, I don't know. What are my options for converting these documents into images? -
What is the @property in Django?
What is the @property in Django? Here is how I understand it: The @property is a decorator for methods in a class that gets the value in the method. But, as I understand it, I can just call the method like normal and it will get it. So I am not sure what exactly it does. Example from the docs: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" @property def full_name(self): "Returns the person's full name." return '%s %s' % (self.first_name, self.last_name) What is the difference of if it is there vs if it isn't? -
how do i show the products that are uploaded by the logged in user only?
here's my problem, when an user logs in they can see the products uploaded by the other user also but i am trying to show when an user logged in they can see the products uploaded by them only views.py from django.shortcuts import render, get_object_or_404, redirect from .forms import ProductForm from .models import Product from django.contrib.auth.models import User prodcut create or upload def product_create_view(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() form = ProductForm() context = { 'form': form } return render(request, "products/product_create.html", context) product update def product_update_view(request, id=id): obj = get_object_or_404(Product, id=id) form = ProductForm(request.POST or None, instance=obj) if form.is_valid(): form.save() context = { 'form': form } return render(request, "products/product_create.html", context) tried by changing in the list view but getting this error product_list_view() missing 1 required positional argument: 'user' def product_list_view(request, user): queryset = Product.objects.filter(user=request.user) context = { "object_list": queryset } return render(request, "products/product_list.html", context) **product detail ** def product_detail_view(request, id): obj = get_object_or_404(Product, id=id) context = { "object": obj } return render(request, "products/product_detail.html", context) product delete def product_delete_view(request, id): obj = get_object_or_404(Product, id=id) if request.method == "POST": obj.delete() return redirect('../../') context = { "object": obj } return render(request, "products/product_delete.html", context) this is product list template page template/product.list.html … -
How to add extending template for single page (need to display post in single page)
i developed a blog app and i want one display one post on single page. please any body share the process for displaying posts new single page Views code: def index(request): return render(request, 'polls/home.html', {}) def Event(request): events=Events.objects.all() return render(request, 'polls/events.html', {'events':events}) template code: {% block content %} <p>Events page </p> {% for abc in events %} <div> <h2><a href="{% url 'event_detail' pk=event_title.pk % }">{{ abc.event_title }}</a></h2> <p>published: {{ abc.event_release_date }}</p> <p>{{ abc.event_description|linebreaksbr }}</p> {% for author in abc.event_author.all %} <p>{{ author }}</p> {% endfor %} </div> {% endfor %} {% endblock %} urls code: urlpatterns = [ path('', views.index, name='Home-Page'), path('events', views.Event, name="Events-Page"), ] by clicking first event title or second title new page will open and display post details: -
How i can change my query to work in django?
I want to make a request from two tables at once, I registered dependencies in the class. But the request does not work for me. What is wrong with him? views.py def payments(request): paymentsss = Transaction.objects.select_related("currency_id")[:5] return render(request, "payments.html", {"paymentsss": paymentsss}) models.py class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency_id = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal_id = models.ForeignKey(Deal, null=True, related_name='deal', on_delete=models.CASCADE) service_instance_id = models.ForeignKey(ServiceInstance, null=True, related_name='service_instance', on_delete=models.CASCADE) payment_source_id = models.ForeignKey(PayerPaymentSource, null=True, related_name='payment_source', on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = '"processing"."transaction"'`enter code here` My Error: I would be glad if there is an example of how to make a larger request. From 3-4 tables. -
How to specify custom authentication and permissions for specific actions in django rest framework
I have the below code defined in django rest framework viewset: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer def list(self, request): return self.queryset.filter(user=self.request.user, is_published=True).order_by('-title') def retrieve(self, request, pk=None): queryset = Book.objects.all() book = get_object_or_404(queryset, pk=pk) serializer = BookSerializer(book) return Response(serializer.data) def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [IsAuthenticated] else: permission_classes = [] return [permission() for permission in permission_classes] def get_authenticators(self): if self.action == 'list': authentication_classes = [TokenAuthentication] else: authentication_classes = [] return [authentication() for authentication in authentication_classes] So basically what i want is someone when he wants to go to the list view of the books he has to authenticate himself with the token authentication but when someone wants to just retrieve a book he does not need to provide any authentication and he can see the details of the book. When i use this code self.action method does not work in get_authenticators for some reason. How can i get around this . Below is the error message : app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner app_1 | response = get_response(request) app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, … -
How to query foreign key in django forms to display related fields
Based on the models below, I am trying to query all products related to the GroupAccomodation it belong to so the user can select it as a dropdown option in the forms. The current one used in form __init__ must be wrong. Please see the codes below: models.py class GroupAccomodation(models.Model): ACCOMODATION_TYPES = ( ('Apartment', 'Apartment'), ('House', 'House'), ) user_group = models.ManyToManyField(User, related_name='user_groups') name = models.CharField(max_length=50) accomodation_type = models.CharField(max_length=50, choices=ACCOMODATION_TYPES) address = models.CharField('Address', max_length=60) city = models.CharField(max_length=30) postal_code = models.CharField('Zip/Postal Code', max_length=5) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) class Product(models.Model): product_group = models.ForeignKey(GroupAccomodation, on_delete=models.CASCADE, related_name='product_groups') name = models.CharField(max_length=30) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveSmallIntegerField(default=0) created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) forms.py from django.forms import ModelForm from django import forms from .models import Product, GroupAccomodation class ProductCreationForm(ModelForm): class Meta: model = Product fields = [ 'name', 'price', 'quantity', 'product_group', ] def __init__(self, *args, **kwargs): super(ProductCreationForm, self).__init__(*args, **kwargs) self.fields['product_group'].queryset = GroupAccomodation.objects.filter(name=self.instance.name) views.py def product_creation(request): form = ProductCreationForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() return redirect('snippet:list') context = {'form': form} return render(request, 'snippet/product-creation.html', context) I do not know what I am doing wrong here but the current queryset in the forms init return None -
Error Django cms return TypeError: issubclass() arg 1 must be a class
I want to start with Python and DjangoCMS, I follow this tutorial http://docs.django-cms.org/en/latest/how_to/install.html, but when I execute python manage.py cms check returns Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Jonatan\PycharmProjects\asesores2\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Jonatan\PycharmProjects\asesores2\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Jonatan\PycharmProjects\asesores2\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Jonatan\PycharmProjects\asesores2\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Jonatan\PycharmProjects\asesores2\venv\lib\site-packages\django\apps\config.py", line 142, in create if not issubclass(cls, AppConfig): TypeError: issubclass() arg 1 must be a class Pip list Package Version --------------------- ------- Django 2.2.6 django-classy-tags 0.9.0 django-cms 3.7.0 django-formtools 2.1 django-sekizai 1.0.0 django-treebeard 4.3 djangocms-admin-style 1.4.0 mysqlclient 1.4.4 pip 19.0.3 pytz 2019.3 setuptools 40.8.0 sqlparse 0.3.0