Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling a django APi in React shopping Cart
I have built a react shopping Cart application which has a login page Signup Page Products Add to Cart and other features like Checkout through Api . Now the other person from my team has build a backend api on django. I want to call that api from my react code now. How should I do it? Do I need to learn something specific? I have searched in internet and all of the sources we to make serve react and django from same project. I have a React project with me and a separate api developed by someone else. Please guide me through this. -
How to make separate database for every user in Django?
So I am new in programming in general and I am currently learning Django. I know it may be a stupid question, but I don't seem to find the answer anywhere and I really want to know it. I am making a basketball stats tracker app. How this works is you enter how many times you scored out of how many attempts and it adds it to your current accuracy percentage. Let's say last time you were 5/10 and now you are 35/90. Then the percentage goes from 50% to 40%. It works for me but I want to make it so people can sign up. I know how to do that but how do I make the stats personalized for every user? -
Many-to-Many Signals
I'm trying to use django signals to prevent many-to-many orphans from forming in my project. Consider the following models: class Attachment(models.Model): some_field = models.FileField() class ModelA(models.Model): attachments = models.ManyToManyField(Attachment) class ModelB(models.Model): attachments = models.ManyToManyField(Attachment) def attachment_relation_changed(sender, **kwargs): action = kwargs.get('action') if action == 'post_remove': ids = kwargs.get('pk_set') Attachment.objects.filter(id__in=ids).filter(modela=None).filter(modelb=None).delete() This properly deletes orphaned Attachment instances when using attachments.set() or attachments.remove() on ModelA or ModelB but doesn't handle ModelA.delete(). Do I need to manually send these signals by overriding the delete functions on ModelA and ModelB? Also, is there a way to do something along the lines of this: Attachment.objects.filter(relations=None).delete() in case any new models are registered with a m2m attachments fields? -
How to get a Permalink to a CSS when using Django-Compressor and Offline Compression
I'm using Django-Compressor with Offline Compression and I need to get a permalink to the compressed css file. {% compress css %} <link rel="stylesheet" type="text/x-scss" href="{% static 'styles/sass/main.scss' %}" /> {% endcompress %} I'm getting a file similar to this on each deploy: /static/CACHE/css/main.175851321d0a.css for the website usage it's fine but I also need to link to that css from an external tool so I need to have kind of a permalink to that file kind of: /static/CACHE/css/main-permalink.css A CSS filename that doesn't change on every deploy Is there a way to do that? Thanks in advance. -
Can I detect text input change (in form) without POST action in Django?
I have Model form with charfield of username. I want to get value of field after user stopped entering text to use it in my python code in view. How can I achieve that with Javascript? Is it possible to do it without JS? -
'ImageFileDescriptor' object has no attribute 'objects'
I'm trying to iterate through the images in my categories but I'm getting 'ImageFileDescriptor' object has no attribute 'objects' models.py class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) def get_image_path(self, filename): gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, self.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) return os.path.join(gallery_path, filename) gallery = models.ImageField(upload_to=get_image_path) def create_directory(self): gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, self.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) def save(self, *args, **kwargs): if not self.pk: self.create_directory() super().save(*args, **kwargs) def delete(self, *args, **kwargs): shutil.rmtree(os.path.join(settings.MEDIA_ROOT, self.slug)) # os.rmdir(os.path.join(settings.MEDIA_ROOT, self.slug)) super().delete(*args, **kwargs) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title views.py def category_detail_view(request, slug): category = get_object_or_404(Category, slug=slug) context = { "gallery": Category.gallery.objects.all(), } return render(request, 'main/category_detail.html', context) category_detail.html {% for image in gallery %} <div class="col-md-4"> <a href="{{ image.url }}"> <img src="{{ image.url }}" class="img-responsive img-thumbnail" width="304" height="236"/> </a> </div> {% endfor %} For some reason creating galleries in Django has been difficult for me. It seems as if there is no standard way that most people are doing this. Even if I get this to work, I don't see how one could manage the uploaded images from the admin panel. ex upload delete arrange etc If you could shed some light on this … -
How to pass instance primary key from HTML to views.py?
I have a table of model instances as following: _____________________ |1| | | |<a/>| _____________________ |2| | | |<a/>| _____________________ |3| | | |<a/>| ....................... _____________________ Django generates it with for template loop an the first column is a primary key of model instance. The last column is a link to the page fith form to edit this model instance. I have 2 functions in views.py: to render this page (edit_employee()) and to submit changes (edit_employee_action()). In the last one I need to process this primary key. How can I pass the primary key from HTML to views.py? How can I pass this key from edit_employee() to edit_employee_action()? I could create global variable, but this is not the best way I suppose. -
Queryset from queryset in Django
I have a model, Project, that contains a list of Users, with the many to many field employees. This M2M field goes through another model, ProjectEmployee and I was wondering how I can get a lit of all Projects given user belongs to? I can get a queryset of all the ProjectEmployee models that a user belongs to, but how do I get a queryset of the Projects from this? ProjectEmployee.objects.filter(user=user) -
Why is my Django SMTP not sending emails?
When I click submit it loads for a bit and returns my success message. However in the gmail I set to send there's no sent mail, and there's no email sent to the address I want either. What's going on here? Settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '465' EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = '$3cretp@$$word' EMAIL_USE_TLS = True Views.py def market(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST, request.FILES) if form.is_valid(): from_email = form.cleaned_data['from_email'] subject = form.cleaned_data['subject'] address = form.cleaned_data['address'] id_front = form.cleaned_data['id_front'] additional_details = form.cleaned_data['additional_details'] try: send_mail(from_email, subject, address, id_front, additional_details, ['emailaddres@whereIwantittogo.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "market.html", {'form': form}) def market_success(request): return HttpResponse('Success! We have received your request and will get back to you soon.') html {% extends 'base.html' %} {% block title %}Market{% endblock %} {% block content %} <p>To request to market your property with us, please fill out the form below.</p> <form method="post" enctype="multipart/form-data" class="post-form"> {% csrf_token %} {{ form.as_p }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> {% endblock %} forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) address = forms.CharField(required=True) id_front = forms.ImageField(required=True) additional_details = forms.CharField(widget=forms.Textarea, required=True) -
python3.7 django after runserver command 127.0.0.1:8000 is not available, no error message(Linux Gentoo)
I logged in via ssh to my Linux Gentoo server and tried to run my python3.7 django code with "python3.7 manage.py runserver". When I tried to visit the website with my chrome browser on "127.0.0.1:8000" I get the same message like when I didn't ran the "runserver"-command. When I ran the code on my laptop, everything worked fine! My settings.py code is: """ Django settings for ProjectCappuchino project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from django.urls import reverse_lazy # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] LOGIN_REDIRECT_URL=reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_URL= reverse_lazy('logout') SESSION_COOKIE_AGE = 60 * 60 * 8 # Application definition INSTALLED_APPS = [ 'capchine', 'crispy_forms', 'bootstrapform', 'django.contrib.humanize', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'ProjectCappuchino.urls' … -
KeyError while CreateView with two ForeignKey relationships
Models I have created two models within the Journals app. One model is for journal (to_journal) and the other one is for Journal entries (to_journal_entry). to_journal model is related to user model via "journal user" and to_journal_entry model is related to to to_journal via the journal_name. It looks something like this: models.py class to_journal(models.Model): journal_name = models.CharField(max_length = 40) slug = AutoSlugField(populate_from='journal_name') date_created = models.DateTimeField(auto_now_add=True) journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return str(self.journal_user) + " " + self.name def get_absolute_url(self): return reverse('to-journals') class to_journal_entry(models.Model): body = models.TextField() entry_date = models.DateTimeField(auto_now_add=True) journal_name = models.ForeignKey(to_journal, on_delete=models.CASCADE,) journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return str(self.journal_name) + " " + str(self.entry_date) def get_absolute_url(self): return reverse('to_journals', args=[str(self.slug)]) Views I have successfully set up the CreateView for the to_journal. On the relevant page I enter the journal name I want give my journal, press the "Add" button and the page updates, displaying the updated list of journals. This is achieve with the CreateToJournal view below. I want to achieve the same thing for journal entries. Once I am "inside" any given journal, I want to be able to enter the text and I want the page to reload and update the list of entries for that … -
How can I include an image in a Django contact form?
I need to have users send me an email through my website with the front and back of their ID for verification. Why is my form returning "This field is required." when everything is filled in? What did I do wrong? views.py def market(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): from_email = form.cleaned_data['from_email'] subject = form.cleaned_data['subject'] address = form.cleaned_data['address'] id_front = form.cleaned_data['id_front'] additional_details = form.cleaned_data['additional_details'] try: send_mail(from_email, subject, id_front, address, additional_details, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('market_success') return render(request, "market.html", {'form': form}) def market_success(request): return HttpResponse('Success! We have received your request and will get back to you soon.') forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) address = forms.CharField(required=True) id_front = forms.ImageField(required=True) additional_details = forms.CharField(widget=forms.Textarea, required=True) html {% extends 'base.html' %} {% block title %}Market{% endblock %} {% block content %} <p>To request to market your property with us, please fill out the form below.</p> <form method="post" enctype="multipart/form-data" class="post-form"> {% csrf_token %} {{ form.as_p }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> {% endblock %} -
Problem with connect Django Debug Toolbar
I connected like in instruction, when run server all is ok, but when open site I see the ERROR: 'djdt' is not a registered namespace What should I do? -
How to fix 'TypeError: expected string or bytes-like object' when using Amazon S3 with Pillow on Django
I'm trying to upload an image edited through Pillow to Amazon S3 – I have gone through all of the setup, but it doesn't seem to be working. This is my model: import uuid import qrcode from PIL import Image from io import BytesIO from django.core.files import File BOOL_CHOICES = ((True, 'Attended'), (False, 'Absent')) class Person(models.Model): userid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) first_Name = models.CharField(default=" ", max_length=50) last_Name = models.CharField(default=" ", max_length=50) email = models.EmailField() number_of_Guests = models.PositiveIntegerField(default=0) url_link = models.CharField(default=' ', max_length=200) qr_image = models.ImageField(upload_to='qrcodes', default='default.jpg') attended = models.BooleanField(default = False, choices=BOOL_CHOICES) def __str__(self): return (self.first_Name + " " + self.last_Name + " " + str(self.userid)) def save(self, *args, **kwargs): self.url_link = "mywebsite.com/" + str(self.userid) img = qrcode.make(self.url_link) canvas = Image.new('RGB', (500, 500), 'white') canvas.paste(img) blob = BytesIO() canvas.save(blob, 'JPEG') self.qr_image.save('qr-' + str(self.userid) + '.jpg', File(blob)) super().save(*args, **kwargs) Traceback: Request Method: POST Request URL: http://127.0.0.1:8000/tickets/ Django Version: 2.2.6 Python Version: 3.6.5 Installed Applications: ['event.apps.EventConfig', 'tickets.apps.TicketsConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'paypal.standard.ipn', 'storages'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', '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') Traceback: File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, … -
How to get CSRF from django in a separate React App
After researching CSRF tokens and django, it's clear that the React app has to be rendered via django in order to retrieve the CSRF token normally (i.e. injected into the DOM) The only reason I take issue with this I know instagram is using Django and React for their web app; I find it highly unlikely it's being rendered -- at least in a traditional way -- by django. I realize it will be difficult to find an answer to how they are handling it, but perhaps someone knows a way of doing this without rendering a very large enterprise-level react app with django. To give some perspective, our react application is in a separate repo & directory on a different subdomain to our django powered API. We've looked for advice in every area I can think of and have yet to find a proper solution, so I appreciate any feedback you can give -
IntegrityError at /quiz/api/quiz/ null value in column "owner_id" violates not-null constraint DETAIL
I'm trying to post quiz but getting integrity error. owner field not getting null instead of current user serializer.py class QuizSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault() ) quiz_id = serializers.CharField(read_only=True, default='q'+secrets.token_hex(8)) class Meta: model = Quiz fields = ['quiz_id', 'owner', 'title', 'description'] models.py class Quiz(models.Model): quiz_id = models.CharField(max_length=50,primary_key=True,null=False) owner = models.ForeignKey(User, on_delete=models.CASCADE,null=False) title = models.CharField(max_length=50,null=False) description = models.TextField(max_length=200,blank=True) timestamp = models.DateTimeField(default=timezone.now) is_live = models.BooleanField(default=False) views.py -
Django rest-auth: calling RegisterView from other viewset; sensitive_post_parameters didn't receive an HttpRequest
In my application powered by django-rest-framework I use django-rest-auth and allauth to handle the user registration, etc. Everything works fine. I have one API endpoint that handles users' testimonials. The idea is that if someone who has no account at my website is adding a testimonial, I want to automatically create an account for him/her (in case if an email was entered) and the welcome email should be sent, profile created, etc. So from the viewset that handles adding a testimonial, I am calling RegisterView like this: from rest_auth.registration.views import RegisterView .... RegisterView.as_view()(self.request) But I am getting an error: AssertionError at /api/auth/testimonial/add/ sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod, be sure to use @method_decorator. Seems that I should create a custom class and override some method(s) of RegisterView, dispatch likely. But can't figure out what exactly should I do. In fact the request has no sensitive data at all, just email, name, testimonial text, etc. No passwords or tokens. This is an original code from RegisterView @ rest_auth.registration.views: sensitive_post_parameters_m = method_decorator( sensitive_post_parameters('password1', 'password2') ) class RegisterView(CreateAPIView): serializer_class = RegisterSerializer permission_classes = register_permission_classes() token_model = TokenModel @sensitive_post_parameters_m def dispatch(self, *args, **kwargs): return super(RegisterView, self).dispatch(*args, **kwargs) def get_response_data(self, … -
'InLinescheduleofpayment' object has no attribute '_state'
\models class ScheduleOfPayment(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Month_Name = models.ForeignKey(MonthName, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Day = models.CharField(max_length=500, blank=True, null=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) def __str__(self): suser = '{0.Education_Levels}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) \admin.py class InLinescheduleofpayment(admin.TabularInline): model = ScheduleOfPayment.Education_Levels extra = 0 @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin): inlines = [InLinescheduleofpayment] list_display = ('Student_Users', 'School_Year','Courses','Section','Payment_Type','Education_Levels','Discount_Type','Remarks') ordering = ('Education_Levels',) list_filter = ('Student_Users',) I just want to merge the StudentsEnrollmentRecord and ScheduleOfPayment using the foreign key of EducationLevels both StudentsEnrollmentRecord and ScheduleOfPayment -
Django python setting initial values dynamically to form
i'm trying to build a small web service for inventory control where i work, i have already done most of the thing but i want to know how to send values to a form in a detail view (when accessing a specific item's) so it fills some of the data class Product_Update(forms.Form): Product_Code = forms.CharField(max_length=10,attrs={"placeholder = <ID here> Readonly = True") Name = forms.CharField(max_length=100) Description = forms.Textarea(attrs={"Rows": 3}) price = forms.DecimalField() mini = forms.IntegerField() Max = forms.IntegerField() how do i pass the form the parameters? this is my first project done in django/python -
Hide parameters in browser's url bar
I would like to hide the parameter in the browser's URL bar when I pass it through the tag form the template Template: Upload Profile Urls: path('newviewprofile/',views.newviewprofile,name='newviewprofile'), Is it possible to hide the id in the browser's URL when I use this technique? -
Is there a way to display information from a connected table if not null?
I built a table with a MySQL backend in Django that lets me store generator charts that would be useful in worldbuilding and character building, like you might find on reddit.com/r/d100. My table can account for 110 potential roll entries, but I anticipate that for some tables (such as d20 tables), a large number of the entries will not be used. Is there a way to display all of the used entries but skip the null entries? If not, I am prepared to hardcore each of the rolls to display on the webpage. I was anticipating having to plug in something like <tr> <th>Roll</th> <th>Result</th> </tr> {% if table.roll_1 is not None %} <tr> <td>1</td> <td>{{ table.roll_1 }} </tr> {% endif %} </table> This is my generator table model: class D100Generator(models.Model): d_100_id = models.AutoField(primary_key=True) field_of_interest = models.ForeignKey(FieldOfInterest, on_delete=models.CASCADE) subreddit_post_id = models.ForeignKey(Subreddit, on_delete=models.CASCADE, blank=True, null=True) module_id = models.ForeignKey(Module, on_delete=models.CASCADE, blank=True, null=True) generic_website_id = models.ForeignKey(GenericWebsite, on_delete=models.CASCADE, blank=True, null=True) table_name = models.CharField('table name', max_length=100) system = models.CharField(max_length=150) genre = models.CharField(max_length=250) chart_type = models.CharField('Die used', max_length=15) chart_instructions = models.TextField('Chart instructions & explanation') roll_1 = models.TextField('1', blank=True, null=True) roll_2 = models.TextField('2', blank=True, null=True) ... roll_109 = models.TextField('109', blank=True, null=True) roll_110 = models.TextField('110', blank=True, null=True) table_slug … -
How to Render Message Threads to Template in Django?
I'm trying to render a user's direct messages and group them into threads in the template. Each message has a "thread" field to indicate the thread. How would I render the messages to the template, grouped into their thread? Here is my model: class Thread(models.Model): transaction = models.OneToOneField( Transaction, on_delete=models.CASCADE, primary_key=True, ) create_time = models.DateTimeField(default=timezone.now, null=True, blank=True) class Message(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(get_user_model(), related_name='sender', on_delete=models.CASCADE) reciever = models.ForeignKey(get_user_model(), related_name='reciever',on_delete=models.CASCADE) text = models.TextField(max_length=4000) create_time = models.DateTimeField(default=timezone.now, null=True, blank=True) Any help is appreciated. -
Docker is building but not showing data in browser
I'm new to using Docker and this is my first project with it. I followed a tutorial to implement on a project i'm working on. I created a backend using python and django and am trying to containerize it and then deploy it. The application is building and being containerized, but when i go to see if my data is showing up, but it returns an error right now. Please take a look at the code and let me know if i've made any mistakes. # Dockerfile # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies RUN pip install pipenv COPY Pipfile Pipfile.lock /code/ RUN pipenv install --system # Copy project COPY . /code/ version: '3.7' services: db: image: postgres:11.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - POSTGRES_USER=nostaldjauser - POSTGRES_PASSWORD=nostaldja - POSTGRESS_DB=nostaldja volumes: postgres_data: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nostaldja', 'rest_framework', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'nostaldja', 'USER': 'nostaldjauser', 'PASSWORD': 'nostaldja', 'HOST': 'db', 'PORT': 'localhost' } } -
The value of list_display is not a callable, an attribute of 'newly created class'
when i run server i am facing error : (admin.E108) The value of 'list_display[1]' refers to 'Discount', which is not a callable, an attribute of 'OfferAdmin', or an attribute or method on 'products.Offer'. I tried following piece of code in a file named admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'Discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Offer, OfferAdmin) admin.site.register(Product, ProductAdmin) befor adding class OfferAdmin code was working fine. However after adding it. this is showing error -
form_add with pre-filled fields
I have a models with 3 classes: Visite, Inclusion, BilanBiologique and ExamenBiologique Inclusion is linked to Visite (OneToOne) BilanBiologique is linked to Visite (ForeignKey) ExamenBiologique is linked to BilanBiologique (ForeignKey) ExamenBiologique is a subform of BilanBiologique I use Django admin form I try to customize my Inclusion admin form to have a link that redirect user to BilanBiologique AND I would like the "vis" field (which is the ForeignKey) to be pre-filled with the corresponding value (I can retrieve this value from Inclusion) I manage to display a link from Inclusion to BilanBiologique using a method "examen" in Inclusion class I have think about using GET method but to be honest I am lost... I have no idea how to proceed... models.py class Visite(models.Model): vis_ide = models.AutoField(primary_key=True) pat = models.ForeignKey(Participante, verbose_name='Participante', related_name='visites', on_delete=models.CASCADE) vis_dat = models.DateField("Date de consultation") def __str__(self): return f"{self.pat.pat_ide_prn_cse} / {self.vis_dat}" class BilanBiologique(models.Model): bio_ide = models.AutoField(primary_key=True) vis = models.ForeignKey(Visite, verbose_name='Visite', on_delete=models.CASCADE) bio_dat = models.DateField("Date de prélèvement") def __str__(self): return f"{self.bio_ide}" @property def date_visite(self): return self.vis.vis_dat date_visite.fget.short_description = 'Date de la visite' @property def participante(self): return self.vis.pat.pat_ide_prn_cse participante.fget.short_description = 'Participante' class ExamenBiologique(models.Model): bio_exa_ide = models.AutoField(primary_key=True) bio = models.ForeignKey(BilanBiologique, verbose_name='Bilans', related_name='examens',on_delete=models.CASCADE) bio_exa_cod = models.IntegerField("Type d'examen") bio_exa_res_num = models.FloatField("Résultat numérique", …