Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix this 400 bad status error while accessing my pache on apache sever?
I'm deployed my django app on server and when I'm trying to get the page on my web browser, then "Bad Request (400)" is all I can see on the page. No errors in sudo tail /var/log/apache2/error.log artifai-website.conf <VirtualHost *:80> DocumentRoot "/home/artifai/artifai_website/" WSGIScriptAlias / /home/artifai/artifai_website/src/artifai_website/wsg$ WSGIDaemonProcess artifai_website python-path=/home/artifai/artifai_web$ WSGIProcessGroup artifai_website <Directory /home/artifai/artifai_website/src/artifai_website> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /home/artifai/artifai_website/src/static <Directory /home/artifai/artifai_website/src/static> Require all granted </Directory> </VirtualHost> -
Django:Admin List_display is not working for one specific model
I am building an app. I am trying do display fields for 2 different model. Consultation and Consultationserie. The list_display function works for consultationserie but not for consultation. It only shows one field (start_date). There is a foriegnkey of linking to a consultationserie type in the consultation model. I wonder if it is causing a problem. I added to create a parent to child relationship between consultationserie and consultation. Thank you in advance for your help I tried to use different register method (With the decorator, with admin.site.register, admin.site.register(Consultation,ConsultationAdmmin)). Models.py: from django.contrib.auth.models import User from django.db import models import uuid from datetime import date from django.urls import reverse # Used to generate URLs by reversing the URL patterns class ConsultationSerie(models.Model): """Model representing a consultation process (define by the relationship between a patient and a doctor) but notr a specific consultation""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular Consultation process' ) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) patient = models.ForeignKey('Patient', on_delete=models.SET_NULL, null=True) doctor = models.ForeignKey('Doctor', on_delete=models.SET_NULL, null=True) def __str__(self): "Number representing the consultation process" # return str(self.id) return self.patient.lastname + "&" + self.doctor.lastname def get_absolute_url(self): """Returns the url to access a detail record for this consultation process""" return … -
How to divide my app and make extensions?
So, a while ago i have made a web application and now i want to improve it and put some premium content. The problem is that i have no idea how to do that. The application is used by different roles(for example: students, professors, administrators, etc.) and i want to make a normal package, premium package and custom package that i will sell optionally. Normal package would contain only base functionalities, premium would contain all of them and custom would contain only functionalities that customer wants. Imagine it like this, the application is made for an University and a professor is using it. There is an index page for his role and if he is using a normal package he can see only timetable of his lessons, if he is using a premium package than he can see his timetable, students who go to his class, grades, etc. How can i achieve that? Do i need to make numerous versions of an applications for every combination of functionalities? I hope there is a way to achieve this by separating functionalities and somehow disabling and enabling them optionally. P.S. I am using Django framework for backend and React js for frontend. -
Bidirectional OneToOne relation - Django
I have two models (Slot, Appointment). On the appointment one, I have defined a OneToOne relation with the slot model, so good so far; thanks to the RelatedManager I can access the appointment from the slot object but this's done at python level and I need (for some future changes) appointment_id column to be created on the Slot table. class Slot(models.Model): start_at = models.DateTimeField() end_at = models.DateTimeField() duration = DateTimeRangeField( null=True, blank=True ) # Bidirectional appointment = models.OneToOneField( "appointments.Appointment", on_delete=models.SET_NULL, related_name="slot", blank=True, null=True ) class Appointment(models.Model): slot = models.OneToOneField( Slot, on_delete=models.SET_NULL, related_name="appointment", null=True, blank=True, ) The code above will raise some errors when trying to create the migrations like: appointments.Appointment.slot: (fields.E302) Reverse accessor for 'Appointment.slot' clashes with field name 'Slot.appointment'. HINT: Rename field 'Slot.appointment', or add/change a related_name argument to the definition for field 'Appointment.slot'. Basically, due to the python part of the ORM, you can't define the same field on both models. Any idea of how to achieve this. I guess I will have to overwrite some parts of the RelatedManager. I could make this throw SQL but then it won't be clear on the code level. -
How to send object from django template to view function?
I want to send objects from a list in django template to view function. Basically what I want to do is that whenever user hits "view" button in code then I send a post request and send "sel" as data to a view function because I have to use "sel" in view function. search.html {% for sel in selections %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="../static/listhome/media/images/house2.jpg" width="100%" height="225" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" ><rect width="100%" height="100%" fill="#55595c"/></svg> <div class="card-body"> <h3>Price: </h3> <p> {{sel.address}}<br> Bedrooms: <br> Baths: <br> Square Feet: {{sel.approximate_square_footage}} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> ## THIS IS BUTTON TO BE USE TO SEND DATA <button type="submit" class="btn btn-sm btn-outline-secondary">View</button> </div> <small class="text-muted">Days listed: </small> </div> </div> </div> </div> {% endfor %} 'Selections' is a list containing some elements from my database. It is the filtered result of my database passed to this template earlier through the following code: views.py def search(request): value = request.POST.get('searchvalue') selections = Listing.objects.filter(address__contains=value) context={ 'selections':selections, 'value':value, } return render(request, 'search.html',context) -
Saving ManyToManyFields using ModelForms
I am a very new to Django. I am trying to create a Django app. It has portlist and internalapp models. I am using ModelForm to create Internalapp entry. However,the problem is that ports in internalapp model is a ManyToManyField. When I create new entry of internalapp, the ports field( ManyToManyField) does not save data into database.Below,I provide my modles.py,forms.py and views.py code snippets. Any help would be appreciated. models.py class portList(models.Model): PROTOCOL = (("tcp","TCP"),("udp","UDP"),("icmp","ICMP")) appName = models.CharField(max_length=50) serviceName = models.CharField(max_length=50) protocol = models.CharField(max_length=10, choices=PROTOCOL, default= "TCP") reviewDt = models.DateField(default=date.today) status = models.CharField(max_length=20,null=True) def __str__(self): return self.serviceName class internalapp(models.Model): PERIMETER_DOM = (("All","All"),("ECN","ECN"),("GIZ","GIZ"),) plAppConfig = models.CharField('PaloAlto Application Config',max_length=1000, blank=False, null=True) comment = models.CharField('Comments',max_length=500, blank=False, null=True) createdDt = models.DateField('Creation Date',default=date.today) # Automatically set the field to now when the object is first created. ports = models.ManyToManyField(portList,blank=True) def __str__(self): return self.servGrpNm forms.py class InternalappModelForm(forms.ModelForm): groupInd = forms.IntegerField(label='Group Index',min_value=0) appGrpNm = forms.CharField(label='Application Group Name',help_text="This field consists of Perimeter Dom, Group Index and Appliction Function name" ) servGrpNm = forms.CharField(label='Service Group Name',help_text="This field consists of Perimeter Dom, Group Index and Appliction Function name") comment = forms.CharField(widget=forms.Textarea(attrs={'cols': 50, 'rows': 3}),required=False) ports = forms.ModelMultipleChoiceField(queryset=portList.objects.all(),required=False) class Meta: model=internalapp fields = ['appGrpNm', 'servGrpNm', 'perimeter', 'groupInd', 'appGrpFunc', 'comment', 'ports'] views.py … -
Inbuilt User form access
We know there is inbuilt model in django named User, but how to access inbuilt form for that User model in django 2.2? Is there a similar UserCreationForm in django 2.2 as in django 1.10 ? if yes then which directory ? -
Cannot access running django server?
I've created a docker image for django rest project, with following Dockerfile and docker-compose file, Dockerfile FROM python:3 # Set environment variables ENV PYTHONUNBUFFERED 1 COPY requirements.txt / # Install dependencies. RUN pip install -r /requirements.txt # Set work directory. RUN mkdir /app WORKDIR /app # Copy project code. COPY . /app/ EXPOSE 8000 docker-compose file version: "3" services: dj: container_name: dj build: django command: python manage.py runserver 0.0.0.0:8000 volumes: - ./django:/app ports: - "8000:8000" And docker-compose up command bring up the server like this, but in web browser i can't access the server. -
Need examples of how to use djangorestframework-api-key
So I am trying to get comfortable using api-keys and this is a package I found and it seems promising. I added the from rest_framework_api_key.permissions import HasAPIKey permission_classes = [HasAPIKey] Also in settings changed the custom header with API_KEY_CUSTOM_HEADER = "HTTP_API_KEY" and looked at the documentation, but no matter what I pass in as an argument in my url it seems to not work. I pass in http://127.0.0.1:8000/api/questions/API-KEY:********/ with my prefix key and it doesn't work. Any help? -
Django Registration and Login on Same Index Page
I'm trying to have a registration and login form both on my index page (NOT separate login/register urls). I'm able to display the forms, but having trouble with submission. At first I just had the registration form and submission for account creation worked just fine, but adding the Login form has started to cause some issues. Relatively new to Django and can't seem to find the documentation to fit my use case. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import UserRegisterForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages import datetime from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required def index(request): if request.method == 'POST': if request.POST.get('submit') == 'login': login_form = AuthenticationForm(request.POST) username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: return HttpResponse("Invalid login details given") elif request.POST.get('submit') == 'register': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('index') else: form = UserRegisterForm() login_form = AuthenticationForm() now = datetime.datetime.now() cur_year = now.year context = { 'login_form': login_form, 'form' : form, 'year' : … -
Access a custom made list in django template
In my view I created a list as below: dict = {"visited": "positions"} try: positions = Position.objects.filter(company=request.user.userprofile.company, status='ACTIVE') positions_dict = {} for k, position in enumerate(positions): try: hiringPos = HiringPosition.objects.get(position=position) except HiringPosition.DoesNotExist: hiringPos = None positions_dict[k] = {"position": position, "hiringPos": hiringPos} except Position.DoesNotExist: positions_dict = None dict['positions'] = positions_dict print(dict['positions']) return render(request, 'user_view.html', context=dict) It returns like this as i printed into console: {0: {'position': <Position: Position object (1)>, 'hiringPos': None}} Can someone tell me how do i iterate in my user_view.html template? There I have: {% for obj in positions %} {% endfor %} But any try didnt printed anything such as obj.position or positions[obj] or positions.obj ... My Django version: 2.2.2 and python version: 3.6.4 -
Ajax + Django : Ajax is not recognized
I don't understand why my AJAX request is not executed by JQUERY when the method is well executed. I have a form, linked to a JQuery function event with AJAX method that send data to Django function. When I click on the save button, my page reloads while browsing the function to capture the event. It displays the alert well but does not send any information with AJAX. Is my function correct? Is this a problem with Django? This is my html form : <form method="post" id="insert_idea__form"> {% csrf_token %} <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="insert_idea__titre">Titre de votre idée</label> <input type="text" class="form-control" id="insert_idea__title" required=""> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="insert_idea__content">Contenu de l'idée</label> <textarea class="form-control" rows="5" id="insert_idea__content" name="centent"></textarea> </div> </div> </div> <button type="submit" class="btn btn-sm btn-primary">Sauvegarder</button> </form> This is my JQUERY function : <script type="text/javascript"> $("#insert_idea__form").on('submit',(function(e) alert("Stop"); $.ajax({ url: '{% url "insert_idea" %}', type : 'POST', data: { 'title': $("#insert_idea__title").val(), 'content': $("#insert_idea__content").val() }, dataType: 'json', success: function (data) { alert('success'); } }); })); </script> This is my url.py on Django : urlpatterns = [ url(r'^ajax/insert_idea/$', ideas.insert_idea, name="insert_idea"), ] This is my view : def insert_idea(request): title = request.GET.get('title') centent = request.GET.get('centent') return JsonResponse() If … -
Overriding an UpdateView's get_form_kwargs() method
I'd like to override an UpdateView's get_form_kwargs() method, and have something similar to the following: class GroupRatingView(UpdateView): model = Group fields = ['rating'] def get_form_kwargs(self, *args, **kwargs): kwargs = super(GroupRatingView, self).get_form_kwargs(*args, **kwargs) import ipdb; ipdb.set_trace() However, if I try this out, I get the following error: File "/venv/lib/python2.7/site-packages/django/views/generic/edit.py" in post 181. form = self.get_form() File "/venv/lib/python2.7/site-packages/django/views/generic/edit.py" in get_form 45. return form_class(**self.get_form_kwargs()) Exception Type: TypeError at /groups/5/rate Exception Value: ModelFormMetaclass object argument after ** must be a mapping, not NoneType It seems that self.get_form_kwargs() is returning None, whereas I would expect to drop into the debugger. Why am I getting an error instead of hitting the debugger trace? -
Python vs PHP and Laravel vs Django, what is easy to learn?
I heard of people say python is the easiest language and that is why i started learning it. but most of the people think PHP is the easiest language over python.. even laravel more easier than Django, is it true? I guess you are bored with my post but it is may something someone can be inspired by your opinion... Let's open discussion -
Django Foreign key field validation in a forms or models ( getting info created by only that user from foreign key)
I'm trying to build courses and add lessons to a course later and the problem I encounter is that every user can choose to add courses to another person created courses. Like if you create some courses, another user will see as an option to add his lesson to it View file ''' def creatingLessonsForm(request): form = CreatingLessonsForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.CreatedBy = request.user post.save() form = CreatingLessonsForm() context = {'form': form} return render(request, 'courses/creatingLessonsForm.html', context) ''' Model file ''' class CreatingCourses(models.Model): NameOfTheCourses = models.CharField("Name of the courses", max_length=60, blank=False) Category = models.ForeignKey(Subject, on_delete=models.CASCADE) CreatedBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) Document = models.ForeignKey(Document, on_delete=models.SET_NULL, verbose_name= "Select document for courses introduction", blank=True , null=True) IncludeTest = models.ForeignKey(GenaratedTest, on_delete=models.SET_NULL, verbose_name= "Include test for courses", blank=True , null=True) AdditionalInfo = models.TextField("Additional info for courses introduction", max_length=300, blank=False) Note = models.TextField("Notes", max_length=180, blank=True) Show_the_courses = models.BooleanField(verbose_name= "Show the courses for everyone?",default=True) def __str__(self): return str(self.NameOfTheCourses) if self.NameOfTheCourses else '' class CreatingLessons(models.Model): Courses = models.ForeignKey(CreatingCourses, on_delete=models.SET_NULL, null=True) NameOfTheLesson = models.CharField(max_length=60, verbose_name= "Name of the lesson", blank=False) Document = models.ForeignKey(Document, on_delete=models.SET_NULL, verbose_name= "Document for lesson", blank=True , null=True) CreatedBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) Lesson = models.TextField(max_length=250, verbose_name= "Lesson", blank=False) Note = models.TextField("Notes", max_length=100, … -
Wagtail - Revisions for Non-Page Objects
I use vanilla django models (they do not inherit from Page) and the modeladmin module of wagtail to replace the standard django admin with the wagtail admin interface. This is all working great, but I now wish to add revision history and rollback to these models. Wagtail of course has it's own system for managing revisions of objects that inherit from Page, but they would not apply to standard django models. On the other hand, I have been looking at using the django-revisions app to have this functionality. Although this works, django-revisions only provides a standard django admin view, which is not compatible with wagtail, and I would prefer to not have users switching between the two completely different looking admin areas. Does anybody have experience with managing revisions and rollbacks of standard model instances within the context of wagtail? -
Django message is not cleared on web-page reload, causing previous pop up to redisplay
I have a web-page that shows a contact-form. Details are entered and using this an email is sent. To indicate success of sending the email I used Django messages framework, which adds a message with text content 'success'. The html-template checks 'messages' list in a for loop and if met with a message with content 'success', defines a div that contains an ok button (to click and remove this div). I could not find a way to get a JS alert pop up box to trigger after comparison met, so this is why Im defining an absolute position div box myself. I have managed to get the pop up to be removed on click on 'OK', and to bring a new pop up on sending new email, but after I have cleared the pop up and then reload the page, the pop up returns. I suspect the message list containing 'success' message from previous form submit persists on the new page and template has matched it with its condition again. I've tried to use body tag onload to trigger a JS function to clear 'messages' but nothing happened. Not sure 'messages' can be accessed. Tried putting some code found online … -
Model Object from Database not returning Iter
I'm trying to query my Postgresql DB and it's not returning something I can work with. I keep getting Employee object, not Iterable. I've tried adding the iter() function to my Model build up but that also doesn't work models.py class Employee(models.Model): first_name = models.CharField(max_length = 200) last_name = models.CharField(max_length = 200) name = models.CharField(max_length = 200 , blank=True, null=True) employee_id = models.IntegerField(null=False, blank=False, unique=True) email = models.CharField(max_length = 200) address = models.CharField(max_length = 200) employment_type = models.CharField(max_length = 200) employment_status = models.CharField(max_length = 200) role = models.CharField(max_length = 200) marital_status = models.CharField(max_length = 200) gender = models.CharField(max_length = 200) join_date = models.DateField() end_date = models.DateField(blank=True, null=True) location = models.CharField(max_length = 200) hod = models.CharField(max_length = 200) phone_number = models.CharField(max_length = 200, null=False, blank=False) date_added = models.DateTimeField(default = datetime.now, blank=True) date_of_birth = models.DateField() department = models.ForeignKey(Department, on_delete = models.DO_NOTHING) credentials = models.ImageField(upload_to = user_directory_path ) passport = models.ImageField(upload_to = user_directory_path1) views.py def edit(request, pk): employee = get_object_or_404(Employee, id=pk) logging.info(type(employee)) departments = Department.objects.all() # field_values = { 'first_name':employee.first_name,'last_name':employee.last_name,'email':employee.email,'employee_id':employee.employee_id,'department':employee.department,'address':employee.address,'employment_type':employee.employment_type, # 'employment_status':employee.employment_status,'role':employee.role,'marital_status':employee.marital_status,'gender':employee.gender,'join_date':employee.join_date, # 'end_date':employee.end_date,'location':employee.location,'credentials':employee.credentials,'passport':employee.passport,'hod':employee.hod, # 'phone_number':employee.phone_number,'date_added':employee.date_added,'date_of_birth':employee.date_of_birth } # form = AddEmployeeForm(field_values) context = { 'employee': employee, 'departments':departments } if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] name = last_name +' '+first_name … -
read csv file saved in static folder
I have some javascript in index.html that visualizes data stored in population.csv. But nothing is displayed. My directory and the javascript code is listed below. I think I need to change the directory to reach the population.csv but what I have tried hasn't worked. I have tried /static/population.csv. -
How to calculate call @property method from models.py in template in Django?
I have posted the question referred in the link below. How to calculate total price of a product in models in Django? Can anyone please help in this regard i shall be really grateful? Thanks in advance -
Wanting to display csv page with django-rest-framework
I'm trying to display a csv file like I would normally do with Json or XML with Django Rest. Here's an example of what I have. I did what the documentation told me and I have my setting.py set up as REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_xml.renderers.XMLRenderer', 'rest_framework_csv.renderers.CSVRenderer', but whenever I click on the 'csv' it automatically downloads. Anyway to show the csv file on the browser? -
Create a new app in a Django project with multiple databases
I currently have a PostgreSQL database setup using Django which contains a bunch of loans and different attributes. I am now looking to grab a subset of these loans, perform some operations (randomize attributes using a distribution), and load these into a separate database. I am also looking to keep a mapping of the original loans to their new counter parts, should I be creating a new app in my project or starting a new project? I have been looking into using multiple databases as I don't see a way around this and have started with a new app in my current project but am stuck on creating the mapping and choosing which database to select data from and which one to write the updated data to. I'm fairly new to Django and the original database and Django files were created by another person, any help or advice is greatly appreciated. -
Extra field is not showing in Django administration user creation form
I have written forms.py and admin.py. but extra field such as email, full name is not showing in Django administration user creation form. -
how to edit the particular user details in profile page of User module in django
I created the signup form and login form.Now I want to edit and delete the particular details of signup form.I tried it with below code but it is not working.It is allowing me only to edit the admin panel user details only. Here is my code models.py from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.user.username forms.py from django import forms from .models import UserProfileInfo from django.contrib.auth.models import User class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = [ ] class editProfile(forms.ModelForm): class Meta(): model = User fields = ['first_name','last_name','username','email','password'] help_texts={ 'username': None } views.py from django.shortcuts import render from .forms import UserForm,UserProfileInfoForm,editProfile from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required def edit_profile(request): if request.POST: user = User.objects.get(pk=request.user.id) user.username=request.POST.get('user') user.email=request.POST.get('email') user.first_name=request.POST.get('first_name') user.last_name=request.POST.get('last_name') user.password=request.POST.get('password') user.save() return HttpResponseRedirect(reverse('signupapp:index')) user_profile = request.user.get_profile() return render_to_response('edit.html',{'profile':user_profile },context_instance=RequestContext(request)) Can anyone help me to solve this. -
Incorrect path rendering during the update
I've developed a custom form for upload a file using custom-file-input class of Bootstrap 4. It happen something strage when I try to update an existing file as you can see on the image below. The file's path is not correct rendered. I don't understand where is the problem. What I've wrong? forms.py class FileUploadForm(forms.ModelForm): name = forms.CharField( max_length=50, help_text="<small>Write file name here. The name must be have max 50 characters</small>", widget=forms.TextInput( attrs={ "placeholder": "Titolo", "type": "text", "id": "id_title", "class": "form-control form-control-lg", } ), ) description = forms.CharField( max_length=200, help_text="<small>Write a short description here. The description must be have max 200 characters.</small>", widget=forms.Textarea( attrs={ "placeholder": "Descrizione", "type": "text", "id": "id_description", "class": "form-control", "rows": "2", } ), ) publishing_date = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], label="Data di pubblicazione", help_text="<small>Write data and hour of publication. You can use also a past or a future date.</small>", widget=forms.DateTimeInput( attrs={ "id": "publishing_date_field", 'class': 'form-control datetimepicker-input', 'data-target': '#publishing_date_field', } ), ) file = forms.FileField( help_text="<small>Upload the file here.</small>", widget=forms.ClearableFileInput( attrs={ "placeholder": "Carica il file", "type": "file", "id": "id_file", "class": "custom-file-input", } ), ) class Meta: model = FileUpload fields = [ 'name', 'description', 'publishing_date', 'file', ] views.py def createFile(request): if request.method == 'POST': form = FileUploadForm(request.POST or None, …