Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - How to retrieve model properties (field name, field type) and input into Rest API as data to be collected?
I am currently working on a project that uses Django as the backend, with the rest framework acting as an API endpoint for the frontend (ReactJS) to collect data and ultimately, using ReactJS to render the entire UI. However, right now, I am facing the issue of rendering the form in ReactJS as I do not want to manually type in the field names and field types into the form tag in the ReactJS component. Hence, I am hoping that I would be able to extract the model properties from Django, and pass the field names and field types to the API endpoint, so that the ReactJS frontend would be able to get the data and render the form fields accordingly. I have thought about passing in data through a model Serializer, but in that case, if there are no instances of that model, then the JSON object returned would be empty. Alternatively, if there is no way to extract the model properties in Django, then would it be possible for me to pass in the data manually by creating a new Serializer and View? and manually type in the required field names and field properties to be sent over … -
Permission denied error with django-celery-beat despite --schedulers flag
I am running Django, Celery, and RabbitMQ in a Docker container. It's all configured well and running, however when I am trying to install django-celery-beat I have a problem initialising the service. Specifically, this command: celery -A project beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler Results in this error: celery.platforms.LockFailed: [Errno 13] Permission denied: '/usr/src/app/celerybeat.pid' When looking at causes/solutions, the permission denied error appears to occur when the default scheduler (celery.beat.PersistentScheduler) attempts to track of the last run times in a local shelve database file and doesn't have write access. However, I am using django-celery-beat and appying the --scheduler flag to use the django_celery_beat.schedulers service that should store the schedule in the Django database and therefore not require write access. What else could be causing this problem? / How can I debug this further? -
How to expire a session in django?
There are some things i do not understand and i am not using in django, Like Serialize. From another question :How to expire Session in 5 mins? The sessions is confusing me.The sessions are active added in my installed apps and middle ware but.. I am using a simple login from the URL like this : path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), It generates a login form and work. How can i keep using this and now set Session expire time dynamically bases on user request to Remember Me Or what should i change and start over again to implement this whole idea ? -
How to get a queryset with first child product of a parent product?
I have this table(https://prnt.sc/s1ssxx), where I want to fetch all the products with structure standalone and only first variant(child) of a parent product. i.e(excluding all the products with structure "parent", and just keeping first child product of all parent products). from django.db.models import Count, F, Value parent_ids = Product.objects.filter(user_id=user_id,structure=Product.PARENT).values_list('id', flat=True) qs = Product.objects.filter(user_id=user_id).exclude(structure=Product.PARENT).annotate(p=F('parent_id')).distinct('parent_id') I tried this query, but I am using MySQL as Database backend, so it complains about error: "DISTINCT ON fields is not supported by this database backend" , it can only be used this way by other database backends such as Postgres so I can not use distinct with any field name. How can I fetch these records in an optimized way with minimum hits on DB? -
Django Model's Value Error while inserting data into model
I am trying to insert form-data into models User and UserGroup using APIView. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = 'email' class UserGroup(models.Model): user = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE, blank=False) role = models.ForeignKey(Role, related_name='role_id', on_delete=models.CASCADE, blank= False) I am able to insert data into model User but when I try to do the same with the model UserGroup it returns an error. ValueError: Cannot assign "17": "UserGroup.user" must be a "User" instance. I want this API to create a user and assign a role immediately to the newly created user by inserting role_id and user_id in model UserGroup. I have created two different serializer UserSerializer and UserGroup serializer and both has its own create method to push an instance into model. Also, in post request payload I am accepting all the fields of User model but for UserGroup model I am just accepting role field and not the user field as its value needs to be generated once the user is created. I will have to use transaction as well to roll back if in case a … -
NoReverseMatch at /checkout/ - Django Website
django.urls.exceptions.NoReverseMatch: Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\/(?P[^/]+)$'] [18/Apr/2020 14:05:02] "GET /checkout/ HTTP/1.1" 500 157543 <--- this is the error message I am getting in terminal when I try to go onto the checkout page. view.html {% for item in cart.products.all %} <tr><td> {{ item }} </td><td>{{item.price}}</td> <td><a href='{% url "update_cart" item.slug %}'> Remove</a></td></tr> {% endfor %} </table> <br/> <a href='{% url "checkout" %}'>Checkout</a> {% endif %} </div> </div> {% endblock content %} views.py for orders from django.urls import reverse from django.shortcuts import render, HttpResponseRedirect # Create your views here. from carts.models import Cart def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("fuisce-home")) context = {} template = "fuisce/home.html" return render(request, template, context) urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('cart/', cart_views.view, name='cart'), path('cart/<slug>', cart_views.update_cart, name='update_cart'), path('checkout/', order_views.checkout, name='checkout'), ] I can't figure out where the problem is occurring. Any solutions would be greatly appreciated! -
Failed to connect to server postgres django
I configured postgresql on the server as I was told by technical support, but when I go to the page and try to send mail, an error appears: OperationalError at /decision/livingrooms/kitchen/provans/ не удалось подключиться к серверу: В соединении отказано Он действительно работает по адресу "caparolcenterspb.ru" (217.107.219.83) и принимает TCP-соединения (порт 5432)? -
Modify login.html file in Django
{% extends '_base.html' %} {% load crispy_forms_tags %} {% block title %}Log In{% endblock title %} {% block content %} <section id="homeSection" style="width: 1250px;height: 1080px;padding: 40px;background-repeat: no- repeat;background-position: top center;background-size: cover;"> <div > <h2>Log In</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success" type="submit">Log In</button> </form> </div> </section> {% endblock content %} This HTML code is used for the login page. I need to modify the login page with CSS and bootstrap files. I am a beginner to DJANGO. Please suggest me how to modify the this login.html. -
Error in base_name argument in register() in Django Rest Framework
I'm working in Django Rest Framework.And I have defined a view set in the views.py file like this: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from profiles_api import serializers class HelloApiView(APIView): """Test API View""" serializer_class = serializers.HelloSerializer def get(self,request,format=None): """Returns a list of APIView features""" an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your logic', 'Is mapped manually to URLs', ] return Response({'message': 'Hello!', 'an_apiview': an_apiview}) def post(self, request): """Create a hello message with our name""" serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.validated_data.get('name') message = f'Hello {name}!' return Response({'message': message}) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) def put(self, request, pk=None): """Handle updating an object""" return Response({'method': 'PUT'}) def patch(self, request, pk=None): """Handle partial update of object""" return Response({'method': 'PATCH'}) def delete(self, request, pk=None): """Delete an object""" return Response({'method': 'DELETE'}) class HelloViewSet(viewsets.ViewSet): """Test API ViewSet""" def list(self, request): """Return a hello message.""" a_viewset = [ 'Uses actions (list, create, retrieve, update, partial_update)', 'Automatically maps to URLS using Routers', 'Provides more functionality with less code', ] return Response({'message': 'Hello!', 'a_viewset': a_viewset}) And I have … -
How to serialize a list of strings
I'm having an rather easy problem with my serializer. My view: @api_view(['GET']) def get_recipes_list(request): recipes = Recipe.objects.all() serializer = RecipeListSerializer(recipes, context={'request': request}, many=True) return Response(serializer.data) My serializer: class RecipeListSerializer(serializers.Serializer): name = serializers.CharField() Output I'm getting: [ { "name": "Gelato1" }, { "name": "Gelato2" }, ] What I desire is: [ 'name': [ 'Gelato1', 'Gelato2', ] ] I tried: recipes = Recipe.objects.all().values_list('name', flat=True) So that the QuerySet has a list of names, but I'm getting an AttributeError. I'll be grateful for any advices. -
How to implement the tags in django similar to stackoverflow tags in django?
Im learning django 3(can build simple blogs) and trying to develop problem registering application. i was curios what things are involved to create tags like shown in screenshot (CCs email, tags) , when i enter email address and press enter it gets set , similarly when i enter some string and press enter the string is saved in Tag section. what is the field type used(in database model) for such and how relationship is handled (so far my understanding is it must be many to many as multiple Tag string can be associated to multiple issue but is it so simple like this ? ), how effective search can be implemented based on the tags and other bits/pieces of library implemented you know/use - I would appreciate suggestions and helpful links -
scroll websites with django
I'm currently working on a simple scroll website with nothing really difficult (I could almost use plain html/css/javascript but it's a bit of practicing and I will maybe add a blog). And as it is simple I was wondering how to do it properly with Django. So here is my question, I have a homepage template that is actually the website and I don't really get how I split my different part in different apps. For exemple I have a contact form, do I need to split it in another app and then include it in the basic template ? I want to add a galery with image in a database, do I create an app for that ? And the other question that goes along is how do I code an app that is not returning httpresponse but just html to put it in another template and do I still need views ? I would like to do a bit like a standard form in django where you do : form.as_p or form.as_table so maybe: galery.as_slideshow So my questions are quite novice and open but someone could give me some reading to get going, I would be really happy … -
Django-allauth does not use custom socialaccount templates
I copied the django-allauth account and socialaccount templates under my_django_project/templates/account my_django_project/templates/socialaccount respectively. Allauth successfully reads the overwritten account templates but it does not read templates/socialaccount/snippets/provider_list.html my settings.py looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Deployed Django app on heroku and got heroku log error
I have built a Django app and deployed it to Heroku but when I try to run Heroku open I get an error. It is showing me error=h10, desc="App Crashed" and also showing me [info] Worker failed to boot. I don't know how to solve it? here are my Procfile web: gunicorn DEMOPROJECT.wsgi:application --log-file - and here are my settings.py and wsgi.py file settings.py """ Django settings for DEMOPROJECT project. Generated by 'django-admin startproject' using Django 2.2.4. import os from django.contrib.messages import constants as messages # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^8&=+ce4*v^g#q&+%ougrid$7&4y2yc2%%=a5uer7#yc6i#ez7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['letsdoit-s.herokuapp.com', '127.0.0.1:8000'] # Application definition INSTALLED_APPS = [ 'DEMOAPP.apps.DemoappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'DEMOPROJECT.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'DEMOPROJECT.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } … -
How to add User objects to manytomany fields?
I am trying to add the currently logged in user to a m2m field in my model: class(models.Model): name = m.cfield(...) admin = m.m2m(User, related_name="admin+",...) members = m.m2m(User, related_name="members+",...) creator = m.FKEY(User, related_name="creator+",...) While I'm trying to create an object using this views: if request.method == "POST": user = User.objects.get(id=request.user.id) clss = Class() clss.creator = user clss.admin.add(user) clss.members.add(user) clss.save() return redirect('...') I am thrown with FOREIGN KEY constraint failed error. The traceback is: Traceback (most recent call last): File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 243, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\mowli\Desktop\Projects\gcepac\app\views.py", line 49, in new_classroom clss.admin.add(user) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 951, in add self._add_items( File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\transaction.py", line 232, in __exit__ connection.commit() File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 267, in commit self._commit() File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 243, in _commit return self.connection.commit() File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) … -
rendering plotly dash in Django template
I am using https://django-plotly-dash.readthedocs.io/en/latest/ to serve my plotly dash in Django. At the moment the chart is rendered ok in my template. However, it displays very small, I try to adjust the size of the div but it doesn't seem to work. {%load plotly_dash%} <div style="height: 100%; "> {%plotly_app name="simple_example" %} </div> -
Django 2.1.5: Storing the current username in a blog entry
I am very new to Django and try to build a little app for my family with some basic features, one of which is a blog app. In this now I want to store the author of a blog entry in the article model to save it in the database. In the end in the blog entry I want a header that displays the author and the datetime. I found several approaches to that but some how none of them worked for me so far. The last thing I did now was to try and grab the username in the view with requests.user.get_username() and then populate the field in my form with this string as initial value. Somehow it just doesn't come through, I always get the "field is required" error message... Here is my blog-create-view.py: def blog_create_view(request): user = request.user.get_username() data = {'author': user} form = BlogForm(request.POST, data) if form.is_valid(): form.save() return HttpResponseRedirect('/blog/blog-create/thanks') else: print(form.errors) form = BlogForm() context = { 'articleform' : form, } return render(request, "blog-create.html", context) this is the form: class BlogForm(forms.ModelForm): title = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder":"Titelfeld"})) text = forms.CharField( label='', widget=forms.Textarea( ) ) author = forms.CharField(widget=forms.HiddenInput()) class Meta: model = Article fields = [ 'title', 'text', … -
Remove 1 Form from Formset Dynamically Django
I am using the below to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> <tr> <td width = 17.5%>{{form2.ProductCode}}</td> <td width = 32.5%>{{form2.DescriptionOfGoods}}</td> <td width = 12.5%>{{form2.UnitQty}}</td> <td width = 12.5%>{{form2.Type}}</td> <td width = 12.5%>{{form2.Price}}</td> <td width = 12.5%>{{form2.Amount}}</td> </tr> </table> {% endfor %} </div> <button id="add_more" class="btn aqua-gradient">Add</button> <button id="delete" class="btn aqua-gradient">Delete</button> <div id="empty_form" style="display:none"> <table class='table table2' width=100%> <tr> <td width = 17.5%>{{form2.empty_form.ProductCode}}</td> <td width = 32.5%>{{form2.empty_form.DescriptionOfGoods}}</td> <td width = 12.5%>{{form2.empty_form.UnitQty}}</td> <td width = 12.5%>{{form2.empty_form.Type}}</td> <td width = 12.5%>{{form2.empty_form.Price}}</td> <td width = 12.5%>{{form2.empty_form.Amount}}</td> </tr> </table> </div> $('#add_more').click(function() { var counter=0; var form_count = $('#id_form-TOTAL_FORMS').val(); counter++; $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_count)); $('#id_form-TOTAL_FORMS').val(parseInt(form_count) + 1); }); This works perfectly - however I need to be able to delete a line dynamically as well when the Delete button is clicked, and I'm struggling with working through the best way to do that. Any suggestions? I had tried this below - but of course that will only delete all forms and only if they are empty. I want to just delete one form at a time. I feel I may need to add a counter to the id above? Please … -
IntegrityError at /collection/order/ FOREIGN KEY constraint failed error while adding a new object
Hi I was just learning django and trying to create a model form with manaytomany relationship between item and order below is my code snippet. models.py class Item(models.Model): name = models.CharField(max_length=25,default="",primary_key=True) weight = models.FloatField() def __str__(self): return self.name class Order(models.Model): customername = models.CharField(max_length=25,default="") item = models.ManyToManyField(Item,default="") metal = models.ForeignKey(Material,on_delete=models.CASCADE) price = models.IntegerField() place = models.CharField(max_length=25) orderdate = models.DateTimeField(auto_now_add=True) def __str__(self): return self.customername forms.py: from django import forms from .models import Order, Material, Item class ItemForm(forms.ModelForm): class Meta: model = Item fields = '__all__' class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' views.py: def ItemSaveorUpdate(request): if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() messages.add_message(request,messages.SUCCESS,"Movie rating submitted succesfully") else: form = ItemForm() return render(request,'addItem.html',{"form":form}) def OrderSaveorUpdate(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() messages.add_message(request,messages.SUCCESS,"Order added succesfully") return redirect('material') elif request.method == 'PUT': item = Item.objects.get(pk=id) form = OrderForm(instance=item) form.save() else: #item = Item.objects.get(pk=id) form = OrderForm() return render(request,'addOrder.html',{"form":form}) Template additem.html: <form action="{% url 'item' %}" request="post"> {% csrf_token %} {{form.as_p }} <input type="submit" value="add"> </form> urls.py: urlpatterns = [ path('item/', views.ItemSaveorUpdate, name="item"), path('material/', views.MaterialSaveorUpdate, name="material"), path('order/', views.OrderSaveorUpdate, name="order"), I am trying to select multiple items while creating an order and after clicking add it is … -
Django+Supervisor+NGINX on Ubuntu server 18.04. Problems with dynamic content
I am trying to deploy my website in Django+Supervisor+NGINX on Ubuntu server 18.04 from Hetzner. gunicorn.conf.py bind = '127.0.0.1:8000' workers = 3 user = "nobody" Here is my .conf (supervisor): [program:ako] command=/home/oleg/dj/venv/bin/gunicorn ako.wsgi:application -c /home/oleg/dj/ako/ako/gunicorn.conf.py directory=/home/oleg/dj/ako user=nobody autorestart=true redirect_stderr=true stdout_logfile=/home/oleg/dj/ako/ako_supervisor.log stderr_logfile=/home/oleg/dj/ako/ako_supervisor.log autostart=true autorestart=true startsecs=10 conf. NGINX server { listen 80; server_name 95.217.187.37; access_log /var/log/nginx/example.log; location /static/ { root /home/oleg/dj/ako/rsf/; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } with a stopped supervisor: sudo service supervisor stop When I try to launch gunicorn on the root of my project gunicorn ako.wsgi:application everything properly works : Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-91-generic x86_64) (venv) root@t-20200417:~/dj/ako# gunicorn --bind 0.0.0.0:8000 ako.wsgi [2020-04-18 13:44:15 +0200] [1768] [INFO] Starting gunicorn 20.0.4 [2020-04-18 13:44:15 +0200] [1768] [INFO] Listening at: http://0.0.0.0:8000 (1768) [2020-04-18 13:44:15 +0200] [1768] [INFO] Using worker: sync [2020-04-18 13:44:15 +0200] [1771] [INFO] Booting worker with pid: 1771 the test website can be properly reached in browser under http://95.217.187.37/rsf/f_size_water/ and it properly works. When I start supervisor sudo service supervisor start the website is still reachable http://95.217.187.37/rsf/f_size_water/, static links are still working, but the dynamic content does not work. In Menu "homepage language change" the … -
Wagtail form file upload
I have an issue when I add file upload field to Wagtail Forms Builder I get this error: Exception Type: TypeError Exception Value: Object of type InMemoryUploadedFile is not JSON serializable This is my code: class FormField(AbstractFormField): CHOICES = FORM_FIELD_CHOICES + (('fileupload', 'File Upload'),) page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields') field_type = models.CharField( verbose_name='field type', max_length=16, # use the choices tuple defined above choices=CHOICES ) api_fields = [ APIField('page'), ] class CustomFormBuilder(FormBuilder): def create_fileupload_field(self, field, options): return forms.FileField(**options) class FormPage(AbstractEmailForm): form_builder = CustomFormBuilder intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] # Export fields over the API api_fields = [ APIField('intro'), APIField('thank_you_text'), ] This is my template: {% load wagtailcore_tags %} <html> <head> <title>{{ page.title }}</title> </head> <body> <h1>{{ page.title }}</h1> {{ page.intro|richtext }} <form action="{% pageurl page %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </body> </html> Wagtail version 2.8.1 Django version 3.0.5 any idea with this issue ? -
Will I be able to use celery tasks during model migrations in Django?
I have a requirement to modify an existing db model called Alert and create new alerts with new functionality. I also need to take care of the existing alerts in the data base which were created with old model fields. After adding the new fields to Alert model, I'm trying to re-create the alerts with new functionality which has new columns. Basically taking existing rows and re-inserting them in data base with updated new columns with some extra information in the new columns. For this I'm trying to run a celery task in the function which is called as soon as the migration is applied. migrations.RunPython(function which does some operation and then run celerytask.delay(with_some_args) to create new alerts) I'm really concerned whether I can run a celery task inside the function which is passed to migrations.RunPython(). Even for testing this functionality, I don't have an existing data in our lower environment and the required migrations are already applied before even including this function. I don't want to mess with existing DB as everyone is using already. Can someone please confirm if I can actually run long running celery tasks when applying the migrations? in python manage.py migrate appname? Django: 1.11.15 … -
Print django filter context to template
I have a django view as follows tabledata = Entity.objects.filter(id=2) context = { 'table_data': tabledata, } return render(request, 'viewer.htm', context) I tried printing the values in viewer.htm like so {{table_data}} This gives the output <QuerySet [<Entity: Entity object (6)>]> I also tried printing the values using {{table_data.A}} which is one of the fields. This simply gives a blank output. 1.How do I print the values? 2.If the filter returns multiple rows, how do I print them individually in the template? -
Open Edx Third Party Login Integration with Keycloak
I am using edx-ironwood.2-6 in ubuntu 18.08. I am also running keycloak 9.0.0. To enable third-party login using Keycloak I am using the python-social-auth library suggested in edx documentation. Since by default keycloak.py was not available in the edx-ironwood, I copied this keycloak.js file at the location edx-ironwood.2-6/apps/edx/venvs/edxapp/lib/python2.7/site-packages/social_core/backends Followed all steps written in comments to setup keycloak and added following information in keycloak.py SECRET = 'client secret' PUBLIC_KEY = 'publick key from keycloak' AUTHORIZATION_URL = 'http://127.0.0.1:8080/auth/realms/neoscript/protocol/openid-connect/auth' ACCESS_TOKEN_URL = 'http://127.0.0.1:8080/auth/realms/neoscript/protocol/openid-connect/token' USER_DETAILS_URL = 'http://localhost:8080/auth/realms/neoscript/protocol/openid-connect/userinfo' Added following line in the lms.env.json "THIRD_PARTY_AUTH_BACKENDS":[ "social_core.backends.keycloak.KeycloakOAuth2", "social_core.backends.google.GoogleOAuth2", "social_core.backends.linkedin.LinkedinOAuth2" ] In the Django Admin App, Added a Provider Name: Keycloak slug: keycloak site: localhost:81 backend: keycloak client Id: 'mooc' Client Secret: 'secret key' Also Added client secret in lms.auth.json "SOCIAL_AUTH_OAUTH_SECRETS": { "keycloak":"14f89ef1-02ff-48ad-825f-8160e515ec8e" } In Keycloak client settings, added access type 'confidential', and redirect uri 'http://localhost:81/auth/complete/keycloak/' After server restart, In edx login page, login button for keycloak appearing but when I am clicking on it in the browser a message is coming There has been a 500 error on the Open Edx Server In the apache2 log file following error is coming [Sat Apr 18 17:09:21.212377 2020] [:error] [pid 8143] Traceback (most recent call last): [Sat Apr 18 … -
Query to get related data from a multiple tables using foreign key in Django 2.2
I've below models and I want to get all products of the logged in user(vendor) and the product variant and image of the related products. I've heard about the select_related, but don't know how to use it. What will be my query to get all products of vendor and its related images and variants. models.py class Product(models.Model): vendor = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'products') name = models.CharField(max_length = 250) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_images') image = models.FileField(upload_to = 'products') class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_variants') name = models.CharField(max_length = 250) Thanks