Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot pass the value from kwargs in POST method django rest framework
When I try to pass the value of course_id using perform_create method, It shows this error... ValueError at /course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/ Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance. Request Method: POST Request URL: http://127.0.0.1:8000/course/9f77f4a9-0486-44f3-8bea-4908adb7d3ca/add/ Django Version: 2.2.5 Exception Type: ValueError Exception Value: Cannot assign "'9f77f4a9-0486-44f3-8bea-4908adb7d3ca'": "Content.course_id" must be a "Course" instance. This is my views.py class ContentAdd(generics.ListAPIView, mixins.CreateModelMixin): queryset = Content.objects.all() serializer_class = ContentSerializer def post(self, request, *args, **kwargs): saveData = self.create(request, *args, **kwargs) response_data = {} response_data["data"] = saveData.data response_data["errors"] = {} return Response(response_data, status=status.HTTP_201_CREATED) def perform_create(self, serializer): id = self.kwargs.get("course_id") serializer.save(course_id=id) This is my serializers.py class ContentSerializer(serializers.ModelSerializer): class Meta: model = Content fields = [ 'title', 'description', 'serial', 'file', 'file_type', ] This is my model.py class Content(models.Model): content_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) course_id = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="content_course_id", to_field='course_id') file = models.FileField(upload_to=gen_pic_path,blank=False, null=False) file_type = models.BooleanField(blank=False, null=False) # content/attachment serial = models.IntegerField() title = models.CharField(max_length=200) description = models.TextField() This is url path path('course/<course_id>/add/', ContentAdd.as_view()), -
django, postgresql countdown and passive if payment is not made
Backend: I used Django and postgresql. Frontend: I used reactjs. I have a user table and a user profile table. I'm giving the user a date. For example, the deadline is 05.05.2019. If the user does not pay by this date, the user will be both passive and unable to login to the system. How can I make such an algorithm? This means that if the user does not pay by the specified date, he will not be able to enter the system. It will also become passive. Can you help me with this? -
Why can't Django server access the Mac Address of the client which is connected to the server
From what I have studied from my computer networks course is that the packet consists of both IP address as well as MAC address during communication. In our OSI reference model, it is the network layer that does logical addressing and data link layer that does physical addressing, the one which actually assigns the MAC addresses of sender and reciever. So if a packet already consists of both IP address and MAC address then why our application server is not able to get the MAC address from the dataload? -
categroy and subcategory not showing properly django drf
I want to show subcategory inside category only: models.py: class Category(MPTTModel): name = models.CharField(max_length = 100) slug = models.SlugField() parent = TreeForeignKey('self',blank=True, null=True, related_name='children', on_delete=models.CASCADE, db_index = True) class MPTTMeta: unique_together = ('slug', 'parent') verbose_name_plural = "categories" order_insertion_by = ['name'] def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class SubCategory(models.Model): Sub_Category = models.ForeignKey(Category, on_delete = models.CASCADE) sub_category_name = models.CharField(max_length=100) serializers.py: class CategorySerializers(serializers.ModelSerializer): children = SubCategroySerializer(many=True, required=False) class Meta: model = Category fields = ('id','name','slug','children') class SubCategroySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name','slug', 'children') views.py: class CategoryView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset = Category.objects.all() serializer_class = CategorySerializers urls.py: path('categories/', views.CategoryView.as_view()), when i making get request: http://localhost:8000/api/categories/ { "id": 8, "name": "Lifestyle", "slug": "lifestyle", "children": [ { "id": 9, "name": "Fashion", "slug": "fashion", "children": [] }, { "id": 18, "name": "Shopping", "slug": "shopping", "children": [] } ] }, { "id": 9, "name": "Fashion", "slug": "fashion", "children": [] }, { "id": 18, "name": "Shopping", "slug": "shopping", "children": [] }, as you can see fashion and shopping subcategory are showing inside lifestyle category and also showing in category. i just want to show … -
Django MySQL Filter records on dates after adding duration to date
My Model (with attribute values): MyModel: start_date = time.now() active_duration = 6 active_unit = 'm' # month Let suppose, I want to filter all the records which are still active in the current month. -
'InMemoryUploadedFile' object has no attribute 'startswith'
I am creating an image url api and getting the error is ```'InMemoryUploadedFile' object has no attribute 'startswith'``` Here is my models.py ``` class ShowImage(models.Model): image_name = models.CharField(max_length=255) image_url = models.ImageField(upload_to="settings.MEDIA") ``` Serializers.py ```class ShowImageSerializer (serializers.ModelSerializer): class Meta: model = ShowImage fields = ('id', 'image_name', 'image_url')``` Views.py ``` class ShowImageList(generics.ListCreateAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer # parser_classes = (FormParser, MultiPartParser) class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer ``` urls.py ```url(r'^show_image/', ShowImageList.as_view(), name= 'ShowImage'), ``` If i am trying to redirect url to ShowImageDetail then i am getting this error ```Expected view ShowImageDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. ``` -
Django REST Framework PUT doesn't create new object?
When sending PUT request to generics.RetrieveUpdateDestroyAPIView with a URL like site.com/demos/:id where id doesn't match any existing object in the database, a 404 response will be returned. But according to RFC 7231: The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. Doesn't this violate the RFC? -
Combine multiple models(mysql) to template in Django
enter image description hereI have bootstrap design to bind my django crud like operation. which has Modal to insert data and table to show that data on same page. in insert Modal there is 2, 3 dropdown which i want to populate with my mysql db records . thats why i want to combine two modals in single def. views.py def deptlist(request): department = Department.objects.all() return render(request, 'manageemp.html', {'department': department}) def managemp(request): employees = Employee.objects.all() return render(request, "manageemp.html", {'employees': employees}) forms.py class EmpForm(ModelForm): class Meta: model = Employee fields = ["employee_id", "Name", "designation", "department_id", "manager_id", "date_of_joining","date_of_birth", "location_id", "email","contact_number", "password", created_by", "modified_by", "status", "user_type"] class dept(ModelForm): class Meta: model = Department fields = ["department_id", "department_name", "created_by", "modified_by", "status"] -
How could I display the value from two different tables in mySQL?
How could I display the value from two different tables in mySQL in which in (employee) table it contains several information like job_title_id. And on the second table (job_titles) table in contains job_title_id in which it is now a primary key and corresponding job titles like (CE0, Employee,etc). On my form I am pulling all the the information shown from the employee table,but then the job_title_id form employee table is a digit. How could I show its corresponding job_title from table 2? <div class="col-md-4 mb-3"> <div class="form-group bmd-form-group is-focused"> <label class="bmd-label-floating" for="jb_title">Job title</label> <input class="form-control" list="jb_title" name="jb_title" value="{{employee.job_title_id}}"> <datalist id="jb_title"> <option value= "1"> <option value="2" > <option value="3"> <option value="4"> <option value="5"> <option value="6"> <option value="7"> </datalist> </div> </div> </div> </div> Dropdown choices for now. views.py def save_employee_update(request): print(request.POST) emp_id = request.POST['employee_id'] fname = request.POST['first_name'] midname = request.POST['middle_name'] lname = request.POST['last_name'] pr_address = request.POST['present_address'] pm_address = request.POST['permanent_address'] zcode = request.POST['zipcode'] bday = request.POST['birthday'] email = request.POST['email_address'] pagibig = request.POST['pagibig_id'] sss = request.POST['sss_id'] tin = request.POST['tin_id'] sg_pr_id = request.POST['solo_parental_id'] # rg_sched = request.POST['reg_schedule'] usid = request.POST['userid'] defpass = request.POST['default_pass'] ustype = request.POST['user_type'] # j_title = request.POST['JobTitle'] employee = Employee.objects.get(employee_id=emp_id) employee.first_name = fname employee.middle_name = midname employee.last_name = lname employee.present_address = pr_address … -
how to use Q to search fields in list in django DRF without using querysets
def list(self, request): """" """ query = [Q(role_id=USER_ROLE['employer'])] first_name = [Q(request.GET.get('first_name')), Q.AND] last_name = [Q(request.GET.get('last_name')), Q.AND] if first_name: query = query.filter(first_name=first_name) if last_name: query = query.filter(last_name=last_name) user_obj = User.objects.filter(query) serializer_data = self.serializer_class(user_obj, many=True).data return custom_response(status=status.HTTP_200_OK, detail=SUCCESS_CODE['3007'], data=serializer_data) In this i am getting the error AttributeError: 'list' object has no attribute 'filter' -
What is the problem with my ajax Post or with code in my views.py file that the audio is not being retrieved
I am currently working on a project in Django which records audio on the browser and send it to the server for communication. i have already recorded the audio but when i try to POST it using an ajax request, an empty dictionary is received in views.py. here is my script where i have recorded the audio and tried to post an ajax request(record.html) <form method="POST" enctype='multipart/form-data'> {%csrf_token%} <audio scr="" name="audio" id="audio1"></audio><br> <input type="button" value="click me to record" id="recordbtn"> <input type="button" value="click me to stop record" id="stopbtn"> </form> var blob; navigator.mediaDevices.getUserMedia({audio:true}) .then(function success(stream){ var options; try{ options={memiType:'audio/webm;codecs=opus'}; } catch{ console.log('media type not supported') } mediaRecorder=new MediaRecorder(stream,options); mediaRecorder.ondataavailable=DataAvailable; recordbtn.onclick = function() { mediaRecorder.start(); console.log('recoding started'); } var chunks=[]; function DataAvailable(event) { chunks.push(event.data); console.log('dataprocessed'); var audio = document.getElementById('audio1'); audio.controls = true; blob = new Blob(chunks , { 'type' : 'audio/webm; codecs=opus' }); console.log(blob); chunks = []; var audioURL = URL.createObjectURL(blob); audio.src = audioURL; console.log('src assigned'); var token = '{{csrf_token}}'; console.log(token); var fd=new FormData(); fd.append('Blob1',blob); console.log(fd); console.log(fd.getAll('Blob1')); $.ajaxSetup({headers:{ "X-CSRFToken": token}}) $.ajax( { url:"{%url 'record:voice2pg'%}", type:'POST', contentType:'audio/webm; codecs=opus', data:fd, processData:false, success:function(){ alert('post successful') } } ) } stopbtn.onclick = function() { mediaRecorder.stop(); console.log('recording stopeed'); } }) .catch(function failure() { console.log('failure occured'); } ); views.py … -
Django; Problem with Displaying Items Appropriately
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. I have added two activities for Kuala Lumpur through Django admin. They are "Going to Botanical Garden" and "Going to Aquaria." When I go to http://127.0.0.1:8000/triplist/, I see this page: When I click on Kuala Lumpur, I see this page at http://127.0.0.1:8000/triplist/kuala-lumpur/: The two activities, called "Going to Botanical Garden" and "Going to Aquaria," cannot be separated. They are supposed to be displayed in this way: Activity name: Going to Botanical Garden Date: Dec. 4, 2019 Time: 12:34 p.m. Location: KL Sentral Item Type: Ticket Item Number: E12342 Activity name: Going to Aquaria Date: Dec. 4, 2019 Time: 1:58 p.m. Location: Bukit Bintang Item Type: Ticket Item Number: C45776 That means, there must be a … -
create_user() missing 1 required positional argument: 'password'
I am authenticating using email instead of username and i trying to add google authentication everything working fine but this is the error i'm getting: TypeError at /api/complete/google-oauth2/ create_user() missing 1 required positional argument: 'password' user model: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('user must have email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length = 100, unique = True) First_Name = models.CharField(max_length = 100, null = True, blank = True) Last_Name = models.CharField(max_length = 100, null = True, blank = True) is_staff = models.BooleanField(default = False) is_superuser = models.BooleanField(default = False) is_active = models.BooleanField(default = True) last_login = models.DateTimeField(null = True, blank = True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" EMAIL_FIELD = "email" REQUIRED_FIELD = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) .................................................................................... -
How to add reverse in django user login system
I Want to add this if statement! if request.user.is_authenticated: return redirect(reverse('index')) for example: if user is login when i check user can easily go to django login page by typing url i need that if he go to that url django need to redirect to index page because when user is login he don't want to go on login page is there any solution to redirect user to homepage if he is already login i'm using django login system Here is my urls.py from django.urls import path from django.contrib.auth.models import User from todo import views from django.contrib.auth.views import LoginView, LogoutView urlpatterns = [ path('',views.index,name='index'), path('accounts/logout/', LogoutView.as_view(), name='logout'), path('',views.index,name='index'), path('accounts/register',views.signup,name='register'), path('accounts/login/', LoginView.as_view(), {'template_name': 'registration/login.html'}, name='login'), ] Here is my login.html: {% extends 'base.html' %} {% block content_block %} <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <center> <div class="col-sm-4 "> <form class="text-center border border-light p-5 mt-auto mb-auto" method="POST"> <p class="h4 mb-4">Sign In</p> <!-- Email --> {% csrf_token %} {{form}} <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha mt-4" data-sitekey="6LehyMUUAAAAALWRtQz8-T2othAvdtQLsFIjhhYS"></div> <!-- Sign in button --> <input class="btn btn-dark btn-block my-4" type="submit" value="SignIn"></input> </form> </div> </center> {% endblock %} Thanks! Any Help Appreciated! -
How to dynamically filter with field name, condition and values in Django
I have a requirement, that is from the client side I will get an array of objects which will have field names, filtering conditions and the filtering values like this. Sample array of objects: [ {field_name: "book_name", filter_condition: "contains", filter_value: "some book name"}, {field_name: "book_category", filter_condition: "not_equal", filter_value: "category value"}, {field_name: "book_author", filter_condition: "starts_with", filter_value: "authoer name"}, {field_name: "book_price", filter_condition: "equal_to", filter_value: 100} ] and I've to filter based on all of the above conditions. Consider I have a model with name Book and the fields which are there in the array of objects (i.e. book_name, book_category, book_author, book_price). I'm really not understanding how to write the logic for this. can anyone please help with the logic. Thank you in advance. -
ModuleNotFound error in Django. Not able to resolve error
I don't understand the error. I made a same project earlier but was facing some problems with virtualenv so I made another directory with virtualenv and just copy pasted all the codes in the all the files including manage.py settings.py and urls.py. I started app with command line in virtualenv and copy pasted all codes from previous app. manage.py file #!/usr/bin/env python Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quicktt.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Output(error) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 8, in main os.environ.setdefault('DJANGO_SETTINGS_MODULE') TypeError: setdefault() missing 1 required positional argument: 'value' (quicktt) udaykhalsa@warmachine:~/Projects/quick_timetable_main$ python manage.py runserver Traceback (most recent call last): File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/conf/__init__.py", line … -
django.db.utils.IntegrityError: duplicate key value violates unique constraint error while uploading a backup of psql from previous server
I recently changed my server hence I created a backup of psql database. In the new server is I used the psql dbname < dbname.bak to backup my database. Even though the django files (including migrations)(it was identical) were exactly the same, the backup process showed some errors, but somehow the backup succeeded. Every thing is working fine but the problem is when I am creating a new Model (example): class StudentRoutineInformation(models.Model): student = models.OneToOneField(Student,on_delete=models.DO_NOTHING) wakeTime = models.TimeField(blank=True,null=True) sleepTime = models.TimeField(blank=True,null=True) hoursaStudy = models.FloatField(blank=True,null=True) favoriteSubject = models.CharField(blank=True,null=True,max_length = 255) examDate = models.CharField(blank=True,null=True,max_length = 255) examType = models.CharField(blank=True,null=True,max_length = 255) location = models.CharField(blank=True,null=True,max_length = 255) def __str__(self): return self.student.name When I do makemigrations it succeeds but during migration it shows this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey" DETAIL: Key (id)=(121) already exists. Using other answers from stackoverflow I tried this: python manage.py sqlsequencereset MyApp | python manage.py dbshell but this also shows an error: ERROR: relation "basicinformation_studentroutineinformation" does not exist LINE 1: ...alesce(max("id"), 1), max("id") IS NOT null) FROM "basicinfo... The problem is now I can't make any models in any app. Same error in all the apps. What might be the solution? And what could have gone … -
How do we dynamically add id's in onclick function taken in django?
I am new to django and I am having 8 cards. Every card having id,content,and image path which i had dynamically rendered from the database. Now when user clicks on one card the cards information should store in javascript object and should print on console.The code I had done upto now is <div class="row"> {% for i in room %} <div class="col-4"> <div class="card6 mt-3" id="main_{{i.id}}" style ="width: 12rem;" onclick="getdata({{i.id}})"> <img src="{{i.image.url}}" id = "img_{{i.id}}" alt="..." width="185" height="100"> <div class="card-body"> <p class="card-text" id="cont_{{i.id}}"><b>{{i.content}}</b></p> </div> </div> </div> {% endfor %} </div> IN JAVASCRIPT I had written the onclick get data function var object= []; function getData(id,image,content) { var id = id; var image= $("#img_"+id).attr('src'); var content = $("#cont_"+id).text(); console.log('id', id) console.log('image', image) console.log('content', content) } }); Still I am getting error like project1:77 Uncaught ReferenceError: getdata is not defined at HTMLDivElement.onclick ( Please see if any errors in the code and help me out -
How to fix NoReverseMatch at / in django
I Want To Fix This Error: NoReverseMatch at / Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Exception Location: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 660 Python Executable: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 Python Path: ['D:\\Learning\\Work\\Djngo\\todo_app', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] Server time: Wed, 4 Dec 2019 05:07:28 +0000 In This Line I'm Getting Error: <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Signup</a> </li> When i see if user is login and if he type this url http://127.0.0.1:8000/accounts/register he can also go to register page so i don't need that so that's why i add if statement to my urls.py: from django.urls import path from django.contrib.auth.models import User from todo import views from django.contrib.auth.views import LoginView, LogoutView if User.is_authenticated: urlpatterns = [ path('',views.index,name='index'), path('accounts/logout/', LogoutView.as_view(), name='logout'), ] else: urlpatterns = [ path('',views.index,name='index'), path('accounts/register',views.signup,name='register'), path('accounts/login/', LoginView.as_view(), {'template_name': 'registration/login.html'}, name='login'), ] But When i add this i'm getting that error please help me! Error Screenshot: Here is my views.py def login_user(request, template_name='registration/login.html', extra_context=None): cap = None reg2 = None … -
Getting error while i run command docker-compose up in django python
When i run the command, docker-compose up in my django python project i am getting this error, can anyone please help me to resolve this issue, any help will be really appreciated, thanks in advance Starting trialriskincident-backend_app_1 ... Starting trialriskincident-backend_db_1 ... error ERROR: for trialriskincident-backend_db_1 Cannot start service db: driver failed programming external connectivity on endpoint trialriskincident-backStarting trialriskincident-backend_app_1 ... error eady in use ERROR: for trialriskincident-backend_app_1 Cannot start service app: error while creating mount source path '/var/www/trialriskincident-backend': mkdir /var/www: read-only file system ERROR: for db Cannot start service db: driver failed programming external connectivity on endpoint trialriskincident-backend_db_1 (8966683c6b381483c0513fef57b5d3c3e3f0e8331cb4153d37ac5302d5c9f837): Error starting userland proxy: listen tcp 0.0.0.0:3306: bind: address already in use ERROR: for app Cannot start service app: error while creating mount source path '/var/www/trialriskincident-backend': mkdir /var/www: read-only file system -
Places you can reference self in Python classes (Django model)?
I have a model that looks like something like the following: class Location: related_q: Q def whatever(self): return SomeModel.objects.filter(related_q) class Place(models.Model, Location): attr1 = models.CharField… … related_q = Q(some_field__something_else=self) Is there some way to make code like this that actually works? This exact code won't run because self is not actually defined when related_q is declared. The options I'm thinking of are just making whatever abstract in Location and defining it in the subclasses or making related_q a string and altering the code to be along the lines of the following: class Location: related_q: Q def whatever(self): return SomeModel.objects.filter(related_q=self) class Place(models.Model, Location): attr1 = models.CharField… … related_q = "some_field__something_else" However, this doesn't work because related_q here is treated as the literal name of the kwarg and not as the name of the string containing the kwarg. -
Ho to export Django Template to pdf
I'm trying to convert django template to pdf using pdfkit, wkhtmltopdf was installed but I'm getting error like OSError: wkhtmltopdf exited with non-zero code 1. error:QXcbConnection: Could not connect to display How to solve this issue or suggest me any other better way to export django template to pdf....even in this scenario styles are not in proper from django.http import HttpResponse from django.template.loader import get_template import pdfkit def generatepdf(request): data={} template = get_template('template_name.html') html = template.render(data) pdf = pdfkit.from_string(html, False) filename = "sample_pdf.pdf" response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="' + filename +'"' return response Thanks in advance -
Django template Sorting search results on dropdown select
I have a search result django template called search_result.html In the template, I have a list of products based on my filter criteria. I also have a dropdown to sort the result. I would like to sort my result, everytime an option is selected. I did a bit of research and it seems like I need to use ajax and dictsort, but currently unable to figure out the implementation. My code returning the search result page. def select(request): q1 = request.GET.get('brand') q2 = request.GET.get('model') q3 = request.GET.get('bodyStyle') q4 = request.GET.get('budget') q5 = request.GET.get('transmission') print(q1) cars = product_details.objects.all() variables = {'brand_name__icontains':q1,'model_name__icontains':q2,'bodystyle__icontains':q3, 'budget__icontains':q4 , 'transmission__icontains': q5} for key, value in variables.items(): if value is not None: cars = cars.filter(Q(**{key: value})) _brands = products.objects.all() _models= product_models.objects.all() _bodystyles = product_bodystyle.objects.all() carsdetails={ "cars" : cars, "brandFilter" : q1, "modelFilter" : q2, "bodyFilter" : q3, "budgetFilter" : q4, "transmissionFilter" : q5, "brands" : _brands, "models" : _models, "bodystyles" : _bodystyles } return render(request, 'search/search_results.html', carsdetails) Any help in this regard would be awesome. -
Send array of objects attach files in POST request to Django
I'm a newbie Front-End developer. I should build a API to send an array of object, and each object contains many files, structure like below: { files: [ file: (binary), name: "file name", description: "description", attachments: [ attachment(binary), ... ] ... ], infor: { name: "Name", address: "address" } } And our back-end server is wrote by Django. My JS Code: generateFormData() { const originData = store.getState().quotation; let formData = new FormData(); let user = originData.user; Object.keys(originData.files).forEach((key, index) => { const file = originData.files[key]; const surfare_option = (file.surface_otpion && file.surface_otpion.id) ? file.surface_otpion.id : null; const color_option = (file.color_option && file.color_option.id) ? file.color_option.id : null; formData.append(`files[${index}]`, file.file); formData.append(`files[${index}][quantity]`, file.quantity); formData.append(`files[${index}][material]`, (file.material.id) ? (file.material.id) : null); formData.append(`files[${index}][material_type]`, (file.materialType.id) ? (file.materialType.id) : null); formData.append(`files[${index}][surface_option]`, surfare_option); formData.append(`files[${index}][color_option]`, color_option); formData.append(`files[${index}][tolerance]`, file.tolerances); formData.append(`files[${index}][contain_thread]`, file.containThreads); formData.append(`files[${index}][description]`, file.description) if (file.attachments.length > 0) { file.attachments.forEach((attactment, att_index) => { formData.append(`files[${index}][attachments][${att_index}]`, attactment); }); } else { formData.append(`files[${index}][attachments]`, []); } }); formData.append(`g_captcha`, originData.captcha); formData.append('user[first_name]', user.first_name); formData.append('user[last_name]', user.last_name); formData.append('user[phone]', user.phone); formData.append('user[address]', user.address); formData.append('user[email]', user.email); return formData; } sendData() { return new Promise((resolve, reject) => { const formData = this.generateData(); let xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = () => { if (xhttp.readyState === 4 && xhttp.status === 200) { resolve(JSON.parse(xhttp.responseText)); } if (xhttp.readyState === … -
setting DJANGO_SETTINGS_MODULE environment variable
I have a Django project which I got from the previous developer and I am in the process of setting up my local test environment. I can successfully get manage.py run server working without any errors, but unable to access 127.0.0.1:8000 or localhost:8000. I am getting error 'This 127.0.0.1 page can’t be found'. In my research about the issue I doubt the issue is with my manage.py or settings. How to fix this. Please help. The below is my manage.py file. import os import sys import django if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)