Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Serializer for Players and their associated sessions
I have a model that keeps track of sessions for each player class PlayerSession(models.Model): player = models.ForeignKey(Player, on_delete=CASCADE) session = models.ForeignKey(Session, on_delete=CASCADE) Where the player model is class Player(models.Model): name = models.CharField(max_length=1024) email = models.EmailField(max_length=1024) and Session model is from from django.contrib.sessions.models import Session How can I create a serializer for PlayerSession? Right now I've got class PlayerSessionSerializer(serializers.Serializer): player = serializers.PrimaryKeyRelatedField(queryset=Player.objects.all()) session = serializers.PrimaryKeyRelatedField(queryset=Session.objects.all()) def create(self, validated_data): return PlayerSession.objects.create(**validated_data) -
How to inherit from another view in Django
I am trying to make a simple website where user can order someting to eat. So I've got a view with lots of methods - 'pizza_sizes' is only one of them: class PizzaOrderView(TemplateView): template_name = 'pizza/pizza_order.html' pizza_type = ProductType.objects.filter(name='Regular Pizza').values_list('id', flat=True)[0] def post(self, request): to_return = add_to_cart(request) return to_return def pizza_sizes(self): sizes = Product.objects.filter(type=self.pizza_type).values_list('size__name', flat=True).distinct() return sizes I also have a ListView displaying all products that user has in cart. class CartView(ListView): template_name = 'orders/cart.html' From this page user can either delete or update product. So I am using UpdateView to let him update it, but then again I need all those methods (that I use in PizzaOrderView). I could rewrite those methods to this view, but it doesn't make much sens, I tried to inherit it like this: class ProductUpdateView(UpdateView, PizzaOrderView): model = CartItem fields = '__all__' pizza_type = list(ProductType.objects.filter(name__contains='Pizza').values_list('id', flat=True)) def post(self, request, **kwargs): cart_id = self.kwargs.get('pk') to_return = update_user_cart(request, cart_id) return to_return def get_template_names(self): product_type = CartItem.objects.filter(id=self.kwargs.get('pk')).values_list('product__type', flat=True)[0] if product_type in self.pizza_type: self.template_name_suffix = '_pizza_update' else: self.template_name_suffix = '_form' return super().get_template_names() And then use it in my template, but then it throws an AttributeError: 'ProductUpdateView' object has no attribute 'object' As if it somehow lost its 'object' … -
Database configuration in Django
How do I use a database connection URL in setting up database config in Django as opposed to using a dictionary? Instead of using: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'PORT': os.getenv('DB_PORT'), 'HOST': os.getenv('DB_HOST') } } I want to use: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgresql://DB_USER:DB_PASSWORD@localhost:5432/DB_NAME' } } -
Is there a library for integrating django and AI?
i have a source code of a ai that analyze face pattern and show the feeling of people in image i want to integerate it with a django project for example a client send a image to django server and that give it to ai to analyze the image or send result of the analyze to client with the django server is there any library to do this ? if you can say this in websocket programming is better (ASGI instead of WSGI for IoT) the AI uses scikit-learn -
How to create an input field to change the parameters of the yelp fusion api?
I cannot create a POST request without interrupting how my entire page is rendered when I want to change my parameters. Currently, I am only able to change the yelp fusion api parameters manually, but I want the user to be able to change them. However, I cannot make a form to accept it. I want to go from manually putting them in, to something like this params = {'categories': user_input, 'location': Pre_set} where the user can change it and store in the database or anything along those lines views.py def yelp_query(request): business_id = secret1 YELP_API_KEY = secret YELP_SEARCH = 'https://api.yelp.com/v3/businesses/search'.format(business_id) headers = {'Authorization': 'Bearer %s' % YELP_API_KEY} params = {'categories': 'Sushi', 'location': 'Boston'} ****** #params = {'categories': user_input, 'location':'Boston}***** WHAT I WANT req = requests.get(YELP_SEARCH, headers=headers, params=params) parsedData = [] jsonList = json.loads(req.text) print(json.dumps(jsonList, indent=4)) businesses = jsonList["businesses"] for yelp in businesses: yelpData = {} yelpData['name'] = yelp["name"] yelpData['location'] = yelp["location"]["display_address"] yelpData['rating'] = yelp["rating"] yelpData['price'] = yelp["price"] yelpData['phone'] = yelp["phone"] parsedData.append(yelpData) print(yelpData) print(parsedData) context = {'parsedData' : parsedData, 'form':form} return render(request,'Trends/yelp.html', context) yelp.html {% extends 'Trends/base.html' %} {% block body %} <h2>Yelp Recommendations </h2> <form action="#" method="post"> {% csrf_token %} <input type="text" class="form-control" id="yelp" placeholder="" value="" name='yelp'> <input type="submit" … -
Python / Django - Mypy: expression has type "Type[ModelInstance]", variable has type "ModelInstance"
I'm working on a Django app that provides a GraphQL api for the frontend. I'm using mypy for typechecking and when running mypy I'm encountering errors that I do not understand When running I get the following errors: api/schema.py:50: error: Incompatible types in assignment (expression has type "Type[Academy]", variable has type "Academy") api/schema.py:57: error: Incompatible types in assignment (expression has type "Type[School]", variable has type "School") api/schema.py:64: error: Incompatible types in assignment (expression has type "Type[AcademyGroup]", variable has type "AcademyGroup") This is the code that mypy is checking class AcademyType(DjangoObjectType): class Meta: model: Academy = Academy filter_fields: List[str] = ['name', 'domain', 'slug'] interfaces: Tuple = (relay.Node,) class SchoolType(DjangoObjectType): class Meta: model: School = School filter_fields: List[str] = ['name', 'academy'] interfaces: Tuple = (relay.Node,) class AcademyGroupType(DjangoObjectType): class Meta: model: AcademyGroup = AcademyGroup filter_fields: List[str] = ['name', 'academy'] interfaces: Tuple = (relay.Node,) So the lines that keep failing are variants on model: AcademyGroup = AcademyGroup, but that is just a 'Django model as type' definition that is happening all over my code (and does not seem to be generating errors) As such I'm not really sure what I am doing wrong here, so any help would be greatly appreciated. -
django User authentication via LDAP
I'm trying to check the user login in my django project against our AD via ldap. I found a lot of tutorials online that I've tried so far. For some reason the authenticate(username, password)-function returns None. Here is my Code so far: views.py (login) def login_view(request): if not request.user.is_authenticated: if request.method == 'POST': login_form = Login_form(request.POST) if login_form.is_valid(): username = login_form.data.get('username') password = login_form.data.get('password') domain_name = "@my.domain.com" if domain_name not in username: username += domain_name try: user = authenticate(username=username, password=password) print(user) # this gives me None if user is not None: if user.is_active: login(request=request, user=user) return redirect('index') else: form = AuthenticationForm() messages.error(request, 'Try again!') return render(request, 'myapp/login.html', {'form': form}) except ldap.LDAPError as e: print(e) # no error is displayed here form = AuthenticationForm() messages.error(request, 'Try again!') return render(request, 'myapp/login.html', {'form': form}) ### Some more funcs to ### redirect to login.html ### if the login fails settings.py: AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', ) AUTH_LDAP_SERVER_URI = "ldap://my.domain.com:389" AUTH_LDAP_BIND_DN = "CN=Users,DC=my,DC=domain,DC=com" AUTH_LDAP_BIND_PASSWORD = "" # I tried with blank password for anonymous bind or # with "%(password)s" as template but I don't know if that's possible # and also without the AUTH_LDAP_BIND_PASSWORD setting AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0} AUTH_LDAP_USER_ATTR_MAP = {'group': "memberof", "first_name": "givenName", "last_name": … -
How to create a view for details of a single post and url in django?
I am creating a website with a blog application in django 2.2. I only have a problem with the last step, which is to create a view for a single post. Unfortunately, I don't know how to finish it. I created the simplest view I can, but after entering it, I get a 500 error from the server. def single_post(request): return render(request=request, template_name="posts/single_post.html") This is my model, view and url: models.py # Post models from django.db import models from datetime import datetime from django.utils.text import slugify class Post(models.Model): title = models.CharField(max_length=150, verbose_name="Tytuł") content = models.TextField(verbose_name="Zawartość") lead = models.CharField(max_length=35, verbose_name="Skrót artykułu") published = models.DateTimeField(verbose_name="Data publikacji", default=datetime.now()) slug = models.SlugField(unique=True) cover = models.ImageField(upload_to='images/') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = "posts" urlpatterns = [ path("wpisy/", views.posts_list, name="posts_list"),] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Post # Create your views here. def posts_list(request): return render(request=request, template_name="posts/posts_list.html", context={"posts": Post.objects.all}) def single_post(request): return render(request=request, template_name="posts/single_post.html") I would like visitors to the site to be able to read the entire article. Currently, I was able to create only … -
django: Ajax POST response not loading in template
In my django template, An AJAX call is being made for a POST Request (to create an object instance). Template file (making ajax call): <script> $(document).on('submit', '#xyz-form', function(){ $.ajax({ type: 'POST', url: '{% url "xyz" %}', data: $("#xyz-form").serialize(), context: this, success: function(data, status) { $('#xyz-container').html(data); }, error: function (err) { alert(err.status + " " + err.statusText); } }); return false; }); </script> Views.py file: class XYZCreateView(LoginRequiredMixin, CreateView): model = XYZ def post(self, request, *args, **kwargs): # condition returns false hence I commented it # if request.is_ajax(): xyz_form = XYZForm(request.POST) xyz_list = XYZ.objects.all() if xyz_form.is_valid(): xyz_form.save() xyz_form = XYZForm() return render(request, 'ajax_data.html', {'xyz_form': xyz_form, 'xyz_list': xyz_list}) The template invoking the AJAX call is 'xyz.html' and the response data is being sent to 'ajax_data.html' file, which should get loaded as an html content in the #xyz-container that is present in the former html file. However, while the result is getting sent, it is not getting loaded in the original template. Where am I going wrong with this. -
How to inspectdb postgresql certain table in django?
I am trying to use this command for a specific table, but django does not see it. Judging by the logs, he is trying to look into another schema(public) Command: python3 cabinet/manage.py inspectdb processing.transaction > hm.py Error: Unable to inspect table 'processing.transaction' The error was: Error: relationship "processing.transaction" does not exist How to fix this?