Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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", … -
How can I restream an h264 live stream with Python?
I have several IP cameras that produce h264 live streams. The cameras are located at a remote location with a metered internet connection. I have a Django/Python website that users can login to, and watch the cameras. I need to do this: If no clients are watching Cam 2 or Cam 3, the metered connection isn't being used to transfer those streams at all If at least one client is watching Cam 1, my server connects to Cam 1's h264 stream, and grabs the data, restreaming it to the client If 3 clients are all watching Cam 1, I'm restreaming the h264 stream from my HQ, rather than having all 3 streams coming directly from the metered connection Right now, I have this working using this project: https://datarhei.github.io/restreamer/ It works, but it's a little complex, as my Django code has to automatically start and stop docker containers that restream each video stream. This also introduces delay - when the first client hits "Cam 1" on the website, there's a good 10-15 seconds before they can watch the video, as docker is starting a new restreamer container, and restreamer is connecting to the source stream. The second client that wants to … -
Multiple Parameters on Django Validator
I have problems with the parameters, when The validator is written used this way: cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias]) It automatically gets the value of the respective field in the validator.py def insumo_existencias(value): #Por alguna razon, me esta devolviendo un string insumo = models.Insumo.objects.get(id=1) if (insumo.cantidadexistencias < value): raise ValidationError( _('Error no hay existencias suficientes'), ) So, I just have to call it value and thats it, but I want to pass another parameter,but when the function has another parameter it does not longer get the value of the field. I tried this: cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias(cantidadusada,idinsumo)]) It is not working. Obviosuly the validator function was changed to acept to parameters -
Protect a GET and POST endpoint?
I'm trying to protect a GET and a POST endpoint on my backend. The user is not logged in, but I want to prevent ppl from accessing the API endpoint unless they're using my app. I'm using React and axios to make the request, with Django and Python accepting the request. I'm trying to use a CSRF decorator: class ClassView(View): @method_decorator(csrf_protect) def get(self, request): # Protected endpoint. @method_decorator(csrf_protect) def post(self, request): # Protected endpoint. This doesn't work because I can still go directly to the API endpoint and make requests. I've also tried @requires_csrf_token and @csrf_protect without success. -
Django - Sending Form Data View and Back to template
I'm trying to capture data from my form and send it to my view so I can do some business logic there. I have a "booking" website project, I want the user to pick start and end dates( i have a jquery date picker in my template), and on form submit send it to my view (and the db). My view then compares the dates to the prices stored in the database so it knows the price for each day, and on redirect after form submit, data is shown in the website. Hope that makes sense. Here is my view: def apartment_view(request, apartment_id): reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) unavailable = [] for start, end in apartment.reservations.values_list('start_date', 'end_date'): while start <= end: unavailable.append(start.strftime('%-d-%m-%Y')) start += datetime.timedelta(days=1) form = ReservationForm() if request.method == 'GET': form = ReservationForm() date = request.GET.get('reservation.start_date') print(date) elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): reservation = form.save(commit=False) reservation.apartment = apartment reservation.save() form.save() return HttpResponseRedirect(reverse('booking:apartment', kwargs={'apartment_id': apartment.pk})) context = {} context['form'] = form context['apartment'] = apartment context['unavailable_dates'] = json.dumps(unavailable) my form: class ReservationForm(forms.ModelForm): class Meta: model = Reservation fields = [ 'start_date', 'end_date', 'name', ] widgets = { 'start_date': TextInput(attrs={'id': 'datepicker'}), 'end_date': TextInput(attrs={'id': 'datepicker2'}), } … -
Django- how to merge this the StudentsEnrollmentRecord and ScheduleOfPayment in admin-site
\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 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 ScheduleOfPayment(Education_Levels) and StudentsEnrollmentRecord(Education_Levels), but i dont know if i am doing it right.. can you guys help me with solutions? please -
run django multiple application on different ports
How to run multiple apps in different port in django? i am using gunicorn. i want to run the multiple applications on same domain. my Procfile: web: gunicorn DCMS_API.wsgi:application i have app1 and app2 in DCMS_API. How do i host the multiple applications on same domain name as i am new to django, i am facing issue while hosting the application. my django project is uploaded with different domain names apps name getting added in the domain name. -
How to place css and html files in single directory in django
I am working on a django web application where users login to the application and create web pages. Each page can have different themes, just like a wordpress themes. Problem: I am able to create themes(templates) and dynamically load them depending upon the user choice. My problem is all the css and html files of a single theme are not located in single folder. css files are in 'static' directory and html are in 'templates' directory. I want to segregate these files. I want to create a single directory called 'Themes' in which mutliptle directories will be there for each theme like 'theme A' and 'theme B'. In each theme directory again there will be 'css' and 'js' directories. How to implement thesevand load them?