Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement auth0 loging, register, authorization, permission in Django?
I am looking for learning auth0 with Django. but not getting any resources for register, login, authorization, and permission. Can anyone help me with that? -
How to receive data from user Django Rest Framework
I want to receive data from users and pass the processed version. For example user passed JSON: {"first number": 3, "second number": 4}, and the web API should response addition of numbers like {"result": 7}. How to do it without writing to the database? My serializer.py looks like: class AdditionSerializer(serializers.Serializer): first = serializers.CharField() second = serializers.CharField() views.py: class AdditionView(APIView): @action(detail=False) def get_addition(self, request): try: serializer = AdditionSerializer(data=request.data) if serializer.is_valid(): first = serializer.validated_data(['first']) second = serializer.validated_data(['second']) response = {'result': first+second} return Response(response, status=status.HTTP_200_OK) else: return Response({"message":"error"}) except: None""" but it's doesn't work -
How to serialize a Join query set from several tables in Django Rest Framework
Sometimes, frameworks make things more complicated instead of simplify them. I would like to serialize a join like this one queryset = Cities.objects.raw("SELECT 1 as id, cities.name as ci, states.name as s, countries.name as co FROM cities JOIN states ON states.id = cities.state_id LEFT OUTER JOIN countries ON countries.id = states.country_id WHERE cities.name = %s", [city]) or like this one, if raw queries are not recommended city = self.request.query_params.get("cityname") As you can see this is a reverse join. The idea is to serialize a result set like this one 0: name: "Guadalajara" state: "Castilla La Mancha" country: "Spain" 1: name: "Guadalajara" state: "Jalisco" coutry: "Mexico" Two cities having the same name, but belonging to different states and countries. I need this to implement a sort of autocomplete feature. This is actually a pseudocode but it gives an idea about the kind of JSON result I would like to get. I read the documentation and I searched the internet, I found nothing clear about how to do this. I'm new to Django and I'm completely lost, this is a simple task that would be easy to do manually, but I have no idea about how to achieve this using Django Rest … -
rest framework gotten Request has no attr user
I have a problem when I using delete_product_view with api in post man I got this error: AttributeError: 'Request' object has no attribute 'uesr' [16/Jul/2021 22:25:33] "DELETE but actually when I using creat_product_view that have same code user = request.user ( after debugging i realized that problem comes from this piece of code) this is my urls.py from django.urls import re_path from .views import * app_name = 'product' UUID_REGEX = '[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}' urlpatterns = [ re_path(r'product/(?P<slug>[0-9a-zA-Z-_]+)/', product_view, name='product api'), re_path(r'product/create/', product_view, name='product create api'), re_path(r'category/',category_view, name='category api') ] serializer : from rest_framework import serializers from product.models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'title', 'cost', 'description' ] class ProductGetterSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( read_only=True, slug_field='email' ) category = serializers.SlugRelatedField( read_only=True, slug_field='slug' ) class Meta: model = Product fields = [ 'title', 'cost', 'description', 'user', 'category', 'slug', ] viwes.py from rest_framework import status from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from product.api.serializer import * @api_view(['PUT', 'DELETE', 'GET', 'POST']) @permission_classes([IsAuthenticated, ]) def product_view(request, slug=None): method = request.method if method == 'PUT': return update_product_view(request, slug) elif method == 'DELETE': return delete_product_view(request, slug) elif method == 'GET': return get_product_view(request, slug) elif method == 'POST': return … -
Form field for a foreign key in ModelForm with too many choices for ModelChoiceField?
I have a simple foreign key relationship I want to use in a ModelForm, but without a ModelChoiceField. class Sample(models.Model): alt = IntegerField(db_index=True, unique=True) class Assignment(models.Model): sample = models.ForeignKey(Sample, on_delete=models.CASCADE) I want to have the AssignmentForm select the sample based on the contents of the sample's alt field. With a ModelChoiceField it would be like this: class SampleSelect(ModelChoiceField): def label_from_instance(self, obj): return obj.alt class AssignmentForm(ModelForm): sample = SampleSelect(queryset=Sample.objects.all()) class Meta: model = Assignment fields = ['sample'] The ModelChoiceField documentation says to use something else if the number of choices is large. Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for ModelChoiceField becomes impractical when the number of entries increases. You should avoid using it for more than 100 items. I think I need a custom form field, but I cannot figure out how to do this. class SampleBAltField(IntegerField): def clean(self, value): try: return Sample.objects.get(alt=value) except Sample.DoesNotExist: raise ValidationError(f'Sample with alt {value} does not exist') This existing code should take an integer from the form and map it back to a foreign key, but I cannot figure out what to override to populate the field for a bound form from … -
Wagtail initDateChooser is defined for one app but not the other app?
I'm creating a portfolio site and I've deployed my code to an Ubuntu server on DigitalOcean. I have two apps within my project: a blog app and a portfolio app. For the page models I created in the blog app, the DateField works fine and the little calendar picker shows up when the page is created. For the portfolio app, however, the calendar picker doesn't activate. The error in the console reads: Uncaught ReferenceError: initDateChooser is not defined <anonymous> http://MYIPADDRESS/admin/pages/14/edit/:759 I checked the Network tab to see if all the stylesheets were loading. I don't see any 400 or 500 errors. Just 200 and 304. I've tried changing the field models to DateTimeField and the same problem occurs. Deleting and re-adding the models and re-migrating also does not fix the issue. So I'm not sure what else to check at this point. Could something have gone wrong during collectstatic? Should I run that again to see if that makes a differences? Any tips you can offer would be very much appreciated. -
How to add new line inside a <p> tag in html when using Django to pass data?
I have model of Players in Django which looks like this: class Player(models.Model): name = models.CharField(max_length=200, null=False, blank=False, default='') description = models.TextField(max_length=1000, null=True, blank=True) I pass the Player objects in the context: class playerView(request): players = Player.objects.all() context = {'players':players} return render(request, 'base/players.html', context) Now, I render the description in p tag of html using below code: players.html {% for player in players %} <p>{{player.name}}</p> <p>{{player.description}}</p> {% endfor %} But when I try to add description with newlines in it like: This is line one. This is line two. It renders data like this: This is line one.This is line two. I tried adding &#13 &#10 which I found in one of the answers is a new line character, but it doesn't work. I also tried adding \n and also tried adding br tag, but that also didn't work. Please help me with a solution. -
how filter posts for django-modeltranslation
I used Django ModelTranslation how can I filter language model.py class post(models.Model): title = models.CharField(max_length=255) text = models.TextField() views.py def home(request): all_posts = Post.objects.filter( ) -
Django form ignore validations on save vs submit
I am trying to create a Django form in which the user will have two options Save the form (temporarily) Submit the form What I am trying to do is to allow the users to save the form temporarily and after they have all the data they can come back, edit the form and make the final submission. The problem is that the form validation will not allow partially filled form to be saved. Is there any way I can ignore validations when "Save" is pressed whereas perform all the validations when "Submit" is pressed? I do not want to have 2 views. I want the same view with two buttons "Save" and "Submit" if Save is pressed some of the validations will be ignored (i.e. required field left empty due to the fact that the user might not currently have the information). But if the "Submit" is pressed, all the date should be validated. Please note that all the validations takes place backend with Django. Thanks -
How to save data to multiple models with one form?
a pretty noob here. I am trying to create a user profile at the time when the account is created using signals. I want all the fields of the user profile to be filled in sign up page. This is the user profile that I am trying to populate: class UserProfile(models.Model): user = models.ForeignKey(get_user_model(), verbose_name='user', on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) contact_number = models.CharField(max_length=11, default="0331232132") def __str__(self): return self.name This is my custom user model here: class CustomUserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **kwargs): kwargs.setdefault("is_staff", False) kwargs.setdefault("is_superuser", False) return self._create_user(email, password, **kwargs) def create_superuser(self, email, password=None, **kwargs): kwargs.setdefault("is_staff", True) kwargs.setdefault("is_superuser", True) if kwargs.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if kwargs.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **kwargs) class User(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() This is my user creation form that I am sending to template: class CustomUserCreationForm(UserCreationForm): password2 = forms.CharField( label=_("Confirm Password"), widget=forms.PasswordInput, ) name = forms.CharField() contact_number = forms.CharField( max_length=11 ) class Meta: model … -
cant save to a datebaseby use createview
cant save to a datebaseby use createview also del is not working too and url want it make all in one page It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. view.py from django.shortcuts import render , redirect from main_app.models import Widget from django.views.generic import ListView from django.views.generic.edit import CreateView, DeleteView from .forms import ADDForm def home(request): widget = Widget.objects.all() print(widget) count = Widget.objects.values('quantity') total = [{"quantity":0},] quantity =0 for c in count: quantity += c['quantity'] total[0] = quantity ADD_Form = ADDForm() return render(request,'main_app/widget_list.html', {'widget':widget,'ADD_Form': ADD_Form,'total':total}) class WidgetList(ListView): model = Widget class WidgetCreate(CreateView): model = Widget fields = '__all__' success_url = '/' def form_valid(self, form): form.instance.user … -
Django collectstatic Permission denied with docker-compose
I'm making a Django app and I'm using Docker por production deployment, the application almost runs fine on the VPS(Ubuntu 20.04) except that when I try to run collectstatic with this command: sudo docker-compose -f docker-compose.prod.yml exec web python manage.py collectstatic --no-input Always throws this error: PermissionError: [Errno 13] Permission denied: '/home/app/web/staticfiles/img/app_logo.png' This is my docker-compose: version: '3' services: db: restart: unless-stopped image: "postgres:13.2-alpine" container_name: db ports: - "5432:5432" # HOST:CONTAINER env_file: - ./.env.prod volumes: - ./pgdata:/var/lib/postgresql/data web: container_name: web restart: unless-stopped build: context: . dockerfile: ./docker/production/Dockerfile environment: DJANGO_SETTINGS_MODULE: MyApp.app_settings.production command: gunicorn MyApp.wsgi:application --bind 0.0.0.0:8000 expose: - "8000" env_file: - ./.env.prod volumes: - .:/app # Enable code reload - ./run/static:/home/app/web/staticfiles - ./run/media:/home/app/web/mediafiles depends_on: - db nginx: container_name: nginx restart: unless-stopped build: docker/production/nginx volumes: - ./run/static:/home/app/web/staticfiles - ./run/media:/home/app/web/mediafiles ports: - "80:80" - "443:443" depends_on: - web and this is my Dockerfile: # pull official base image FROM python:3.8 # create directory for the app user RUN mkdir -p /home/app # create the app user #RUN addgroup -S app && adduser -S app -G app RUN adduser --system --group app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME # Own … -
Using subqueries with UPDATE in Django's ORM
Say I have two models, which I'll call ModelA and ModelB. Both models have a few fields in common, (represented by field_one, field_two, and field_three). Additionally, ModelB has a foreign key to ModelA. class ModelA(Model): field_one = models.IntegerField() field_two = models.TextField() field_three = models.BooleanField() class ModelB(Model): field_one = models.IntegerField() field_two = models.TextField() field_three = models.BooleanField() model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) I need to update all instances of ModelB to update the field's values to the values of the associated ModelA instances. I need to do this operation entirely in the database, without needing to instantiate any model instances (NOT using .save() or bulk_update()). I know how I can accomplish this in PostgreSQL using subqueries: UPDATE model_b SET (field_one, field_two, field_three) = (SELECT field_one, field_two, field_three FROM model_a WHERE model_b.model_a_id = model_a.id); How can I express the above query in Django's ORM? This is the closest I have been able to get: ModelB.objects.update( field_one=Subquery(ModelA.objects.filter(id=OuterRef('model_a_id')).values(field_one)[:1]), field_two=Subquery(ModelA.objects.filter(id=OuterRef('model_a_id')).values(field_two)[:1]), field_three=Subquery(ModelA.objects.filter(id=OuterRef('model_a_id')).values(field_three)[:1]) }) However, this results in a subquery for every single field: UPDATE model_b SET field_one = (SELECT model_a.field_one FROM model_a WHERE model_a.id = model_b.model_a_id LIMIT 1), field_two = (SELECT model_a.field_two FROM model_a WHERE model_a.id = model_b.model_a_id LIMIT 1), field_three = (SELECT model_a.field_three FROM model_a WHERE model_a.id … -
Correct way to replace Django Model class with an equivalent+decorated subclass
I'm writing a decorator intended to add functionality to decorated Django Model classes. Something like this: class NewFunctionality: @classmethod def fun1(cls): ... @property def prop1(self): ... def add_functionality(Decorated): class NewClass(Decorated, NewFunctionality): class Meta(getattr(Decorated, 'Meta', object)): app_label = Decorated._meta.app_label NewClass.__name__ = Decorated.__name__ NewClass.__doc__ = Decorated.__doc__ return NewClass @add_functionality class MyModel(models.Model): ... This seems to work until there are two decorated model classes, when I get an error Conflicting 'modelclass' models in application 'my_app'. This is apparently due to the registry of models that Django keeps, which clearly has some automagic that doesn't appreciate new model classes being made, even if they are direct replacements of the existing one. Is there anything I can do to accomplish this, other than by monkeypatching the decorated class, adding each needed method? -
How to find relationship between two objects Django in large codebase
I'm working on a new large codebase. There are a ton of models with foreign key relationships and I'm having a hard time keeping them all in my head as I click through the different foreign key relationships. I'm using PyCharm so it's nice to be able to click through the different relationships. The problem is if I have two objects that I'm are connected, i'm basically reduced to clicking down seemly endless relationship paths, which is time consuming and confusing. A lot of times I'll find my self many levels deep from the object I started at and run into a dead end, then I'll have to chase back up the tree and try another path. I tried to use this tool in an attempt to auto draw a uml, but the uml has so many lines between the different objects, I can't tell which ones are connected and it also outputs a png, so I can't search for a model. Does anyone have a recommendation on how I can do this more easily? -
Django rest framework ajax form submit error 403 (forbidden)
When i try to submit my ajaxified form that's working with the DRF API i get in the browser console POST http://localhost:8000/api/texts/ 403 (Forbidden) here is my html file : <form id="text-form" method="POST" action=""> <input type="text" name="title" placeholder="Title" class="form-control mb-3 pb-2" maxlength="200" required id="title"> <input type="date" name="deadline" placeholder="Deadline" autocomplete="off" class="form-control mb-3" id="myflatpickr"> <textarea name="requirements" cols="40" rows="4" placeholder="requirements" class="form-control col mt-3" maxlength="200" required id="requirements"></textarea> <textarea name="document" cols="40" rows="10" placeholder="document" id="editor" class="form-control" required></textarea> <button type="submit">Submit</button> </form> here is my javascript file $("#text-form").submit(function (event) { event.preventDefault(); $textData = $("#text-form").serialize() $.ajax({ url: "http://localhost:8000/api/texts/", method: "POST", data: $textData, success: function() { console.log($textData) }, error: function() { console.log("there is an error") } }) }); in serializers.py: from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from .models import * class TextSerializer(serializers.ModelSerializer): author = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Text fields = '__all__' in my views.py file: class ApiTextList(generics.ListCreateAPIView): queryset = Text.objects.all() serializer_class = TextSerializer permission_classes = [ permissions.AllowAny ] class ApiTextDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): http_method_names = ['get', 'head'] queryset = Text.objects.all() serializer_class = TextSerializer permission_classes = [ permissions.AllowAny ] def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, … -
Python send_email() results in "socket.gaierror: [Errno -3] Temporary failure in name resolution"
Introduction I'm hosting a Django application with Nginx and Gunicorn on a Digital Ocean droplet (Ubuntu 20.04) with a domain name and mail bought at NameCheap. I will use the following example values in my code snippets: domain = example.com email = info@example.com droplet ip address = digital_ocean_droplet_ip When sending out a confirmation mail I get the following error: gunicorn[97049]: self.connection = self.connection_class(self.host, self.port, **connection_params) gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 1043, in __init__ gunicorn[97049]: SMTP.__init__(self, host, port, local_hostname, timeout, gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 255, in __init__ gunicorn[97049]: (code, msg) = self.connect(host, port) gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 339, in connect gunicorn[97049]: self.sock = self._get_socket(host, port, self.timeout) gunicorn[97049]: new_socket = socket.create_connection((host, port), timeout, gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 1049, in _get_socket gunicorn[97049]: File "/usr/lib/python3.8/socket.py", line 787, in create_connection gunicorn[97049]: for res in getaddrinfo(host, port, 0, SOCK_STREAM): gunicorn[97049]: File "/usr/lib/python3.8/socket.py", line 918, in getaddrinfo gunicorn[97049]: for res in _socket.getaddrinfo(host, port, family, type, proto, flags): gunicorn[97049]: socket.gaierror: [Errno -3] Temporary failure in name resolution socket.gaierror: [Errno -3] Temporary failure in name resolution Django settings.py ALLOWED_HOSTS = os.environ.get('example.com,www.example.com,digital-ocean-droplet-ip') EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_USE_SSL=False EMAIL_USE_TLS=True EMAIL_PORT=587 EMAIL_HOST="mail.privateemail.com" EMAIL_HOST_USER="info@example.com" EMAIL_HOST_PASSWORD="***" DEFAULT_FROM_EMAIL="info@example.com" Django views.py from django.core.mail import send_mail # Send confirmation email send_mail( # Subject 'Subject', # Message 'Message', # Sender 'info@example.com', # … -
How to cache iframe in django
I am building a django app and one of my templates has a mapstore iframe on it. That iframe is kind of heavy. Is there any way to cahce that iframe, or all the template, i dont have to wait so long every time the page is loaded. this is the iframe <iframe src="http://tedcap.denebinc.com/mapstore/#/viewer/openlayers/1" frameborder="0" width="100%" height="400" allowtransparency ></iframe> -
How to get all form field data in Django UpdateView when working with many-to-many model field?
For some reason my UpdateView is not displaying the selected associated. The form is pre-populated with only the first form field data results, username, and none of the other field data. I suspect this is due to the ManytoMany field being queried. I've searched for and tried possible solutions but nothing has worked. Any ideas? Models.py class Company(models.Model): """All company specific details. For each main manager, a company is created. The main manager can then add company members, creating for them their user accounts.""" members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='teams', through='CompanyMembership' ) ... class CompanyMembership(models.Model): """Acts as a gateway between User model and Company model""" STAFF = "STAFF", "Staff" MANAGERS = "MANAGERS", "Managers" my_company = models.ForeignKey(Company, on_delete=models.CASCADE) my_identity = models.ForeignKey(User, on_delete=models.CASCADE) my_role = models.CharField(max_length=100, choices=MemberTypes.choices, default=None) class User(models.Model): """Users can be main managers or staff. Each main manager has their own Company. Many staff can belong to a single Company associated with a main manager.""" username = models.CharField(_("Login Name"), blank=True, null=True, max_length=155, unique=True) ... Views.py class TeamMembersView(LoginRequiredMixin, CompanyMembershipCheckMixin, UserPassesTestMixin, ListView): """Lists all the company team members for the specific company""" model = Company template_name = 'users/dashboard/team.html' def test_func(self): user_obj = User.objects.get(id=self.request.user.id) return user_obj.groups.filter(name='Company_Main_Manager').exists() def get_context_data(self, **kwargs): context = super(TeamMembers, self).get_context_data(**kwargs) user_obj … -
Django Rest Framework - test uploading image for nested serializer
Serializers class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('image', ) class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True) flat_info = FlatPostSerializer(read_only=True) class Meta: model = Post fields = '__all__' Test @override_settings(MEDIA_ROOT=tempfile.gettempdir()) def test_crud_operations_for_post(self): *_, flat = self.init_house_structure() url_create = reverse('main:posts-list') with open(self.temp_media_image_path, 'rb') as file: response_create = self.client.post(url_create, data={'flat': flat.pk, 'price': 100000, 'payment_options': 'PAYMENT', 'images': [ {'image': file} ]}, format='json',) self.assertEqual(response_create.status_code, 201) View is just a regular ModelViewSet This test returns error with: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I tried to user 'SimpleUploadedFile' and got error: The submitted data was not a file. The same error if i try to generate new temporary file using 'Pillow' and 'temporary' package. I think the problem with "format='json'", because if remove it - the problem disappears. Also, i have lots of another test with images(but without json format) .but i cant remove it. Nested serializer requires json format to be serialized in right way. So, i really don`t understand how can i test it. 'self.temp_media_image_path' is a path to local image. This is real image which i store in project`s folder P.S. Not a native, sorry -
Django 'AnonymousUser' object is not iterable after passing user context in context processor
I need to show few user info in my nav bar such as number of notification, user name etc. So I am passing context in my context processor. My nav bar located in my base.htm and I am extending my base.html in my all html page. I am getting this error if user isn't login 'AnonymousUser' object is not iterable.here is my code: settings.py 'context_processors': 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'notifications.views.Count_Notifications', #passing context from notifications app views.py def Count_Notifications(request): count_notifications_comment = 0 count_notifications_author = 0 blog_author = Blog.objects.filter(author=request.user) if request.user.is_authenticated: count_notifications_comment = Notifications.objects.filter(sender=request.user,is_seen=False).count() count_notifications_author = Notifications.objects.filter(user=request.user,is_seen_author_noti=False).count() return {'count_notifications_comment':count_notifications_comment,'count_notifications_author':count_notifications_author,'blog_author':blog_author} -
Useage of CSV for Django Rest Framework
I've been trying to build a website with a backend via Django and a frontend via React. I would like to make it so users can see the contents of a CSV file. The Django rest framework site recommends using the following: https://github.com/mjumbewu/django-rest-framework-csv#readme I was wondering if anyone had any examples of how to use this to turn into an api that can then be used on the frontend with react. I can't seem to find any examples of how to do this. -
Django admin inline module is not rendering form's widget
I tried to use a custom widget of the library django-ace and pretty-json, but I don't know why it's not rendering these widgets when I put it into the inline module and it's rendering a texarea by default. I think it's an issue of django inline module, but I don't know if someone has recommendation to solve this. from django_ace import AceWidget from django import forms from django.forms import formset_factory, BaseInlineFormSet from prettyjson import PrettyJSONWidget from django.contrib import admin class StatementForm(forms.ModelForm): class Meta: model = Statements fields = ['query', 'executed', 'logs'] widgets = { 'logs': PrettyJSONWidget(attrs={'initial': 'parsed'}), 'query': AceWidget(mode='sql') } StatementFormSet = formset_factory(StatementForm, formset=BaseInlineFormSet, can_order=True) class StatementTabularInline(admin.StackedInline): model = Statements formset = StatementFormSet readonly_fields = ['executed', 'logs', ] @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): inlines = [StatementTabularInline] links: Django ace: https://pypi.org/project/django-ace/ Pretty json: https://pypi.org/project/django-prettyjson/ result: result of the render of the form -
Value Error: ModelForm has no model class specified
I am getting this error message: Value Error: ModelForm has no model class specified. and have spent a few hours trying to fix it with no progress, i started getting the error and after i added my forms.py part . I will show my forms.py then my views.py from django.forms import ModelForm from .models import Found class FoundForm(ModelForm): class Meta: model: Found fields = ['date', 'type'] ```from django.shortcuts import render ```from .models import Rock #main app.models, models attribute. even photo models ```from .forms import FoundForm ```# Create your views here.views send data to our context dictionary ```def home(request): return render(request, 'home.html') ```def about(request): return render(request, 'about.html') ```def rocks_index(request): rocks = Rock.objects.all() return render(request, 'rocks/index.html', {'rocks': rocks}) ```def rocks_detail(request, rock_id): rock = Rock.objects.get(id=rock_id) found_form = FoundForm() return render(request,'rocks/detail.html', { 'rock': rock, 'found_form': found_form }) ```class RockCreate(CreateView): model = Rock fields = '__all__' #class based view generate html5 forms -
return random models in json format - django
I need to return random data from models in json format but when I try random.choice I got the error 'Joke' object is not iterable . views.py def random_page(request): random_joke = random.choice(Joke.objects.all()) jokes_list = serializers.serialize('json', random_joke) return HttpResponse(jokes_list, content_type="text/json-comment-filtered") models.py from django.db import models class Joke(models.Model): joke = models.TextField(max_length=1000) author = models.CharField(max_length=100, null=True) def __str__(self): return str(self.joke)