Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add another 'Add +' button with custom URL in Django Admin
I have a model list page in /admin of my Django project. On the top right corner, there is a button to add a new object. I wish to create a new button right next to it, which takes me to my custom form. How can this be done? "Add Category +" on the top right corner I have tried editing overriding Django Admin Templates No success there. -
Django Crispy Form - Populate For after submit
I'm building a django app. I'm trying to re-populate the form after submit with the same submitted data. I'm using crispy form. It's not working. Below is my code. I would really appreciate any help. # models.py class Group(models.Model): group_name = models.CharField(max_length=220) group_location = models.CharField(max_length=220) # forms.py class CreateGroup(forms.Form): group_name = forms.CharField(label='Group Name', widget=forms.TextInput(attrs={'placeholder': 'Group Name'})) group_location = forms.CharField(label='Group Location', widget=forms.Textarea(), required=False) # views.py def create_group(request): title = "Create New Group" if request.method == 'POST': form = CreateGroup(request.POST) if form.is_valid(): print(form.cleaned_data) return render(request, 'create_group.html', {'title': title, 'form':CreateGroup, 'form_data': form.cleaned_data}) else: form = CreateGroup return render(request, 'create_group.html', {'form': form, 'title': title}) # create_group.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block body_content %} <div class="container-fluid"> <form action="/creategroup/" method="post" id="post-form"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.group_name|as_crispy_field }} {{ form.group_location|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-primary">Create Group</button> </form> </div> {% endblock %} -
How to create a DRF API to return all possible field choices available along with User list as dict
I am creating an API using DRF, and I want to send a JSONResponse which will contain a list of all users (from django User model) and available choices for few fields as a dict. I tried to create a GenericAPIView with queryset of all active users and in serializer I tried to return the field choices and list of users but the result contains field options along with each user object. I want to keep all users data under key "user_list" and field options under "field1_choices", "field2_choices". GenericAPIView: class TicketPropertiesView(generics.GenericAPIView): authentication_classes = [ CsrfExemptSessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] serializer_class = TicketPropertiesSerializer def get(self, *args, **kwargs): serializer = TicketPropertiesSerializer(data = User.objects.filter(is_active = True), many = True) serializer.is_valid() return JsonResponse(serializer.data, safe = False) Serializer: class UserPropertiesSerializer(serializers.ModelSerializer): user_list = serializers.SerializerMethodField() field_1_choices = serializers.SerializerMethodField() field_2_choices = serializers.SerializerMethodField() FIELD_1_MAP = FIELD_1_CHOICES FIELD_2_MAP = FIELD_2_CHOICES def get_user_list(self, obj): queryset = User.objects.filter(is_active = True) user = [] for obj in queryset: user.append({ "id": obj.id, "username": obj.username, "first_name": obj.first_name }) return user def get_field_1_choices(self, *args): field1_choices = [] for i in self.FIELD_1_MAP: field1_choices.append({"id": i[0], "choice": i[1]}) return field1_choices def get_field_2_choices(self, *args): field2_choices = [] for i in self.FIELD_2_MAP: field2_choices.append({"id": i[0], "choice": i[1]}) return field2_choices class Meta: model … -
Django ChromeDriver Disable Downloads
I am using Selenium and ChromeDriver in a Django application. When I navigate to a particular page it downloads a file(that I don't want). When the browser runs with the head it saves files to my downloads folder. When it runs headless it downloads files to the project folder(same level as manage.py). I want to navigate to the page, but not make any downloads. I looked at the documentation: https://cs.chromium.org/chromium/src/chrome/common/pref_names.cc?l=38 https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc?view=markup And a handful of posts on SO. It's still downloading the file. How do I stop it? Is this a chromedriver issue or a Django issue? scrape.py options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome(options=options) prefs = {"profile.default_content_settings.popups": 2, "download_restrictions": 3, "profile.default_content_setting_values.automatic_downloads": 1, "safebrowsing.enabled" : True } options.add_experimental_option("prefs", prefs) -
is there a way to save current data on another page using django?
I want to allow users to save an email on another page of my web app. for example when the user finds the email that he is looking for. he will click add to lead, and that the same email is going to be added on the leads page. I try but still can't figure it out, thanks guys in advance. url.py url(r'^lead/$', views.lead, name='lead'), what I want is that as soon as the user clicks this link, the email is going to be saved in the leads page. app index.html <a href="/app/lead" title="add lead" > views.py def lead(request): new_item=Blogger(email = request.POST["email"]) new_item.save() return render('app/leads.html',{'new_item':new_item}) -
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?