Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - Unable to serialize an OrderedDict object containing Object Ids
Background I am using djongo to interface with a MongoDB database. My models make use of an auto-generated _id field of type djongo.models.ObjectIdField and my APIViews are presently executing the .get() and .filter() methods on my model querysets to perform database transactions. The Problem When serializing the aforementioned QuerySet results, my serializers successfully do so and in return yield the serialized data that I can then send across in a Response object through my APIViews. However, I have recently transitioned to executing raw NoSQL queries in place of the .get() and .filter() methods mentioned above. The following page on djongo, under section Using Pymongo commands, details how to use pymongo commands to be able to perform these raw queries. I am able to exploit this fact and have successfully refactored part of my codebase to experiment with these commands. Unfortunately, my existing model serializers will serialize all the data these pymongo commands return except for the _id field of each returned model. Most importantly, .filter(...) would return a QuerySet object, which my serializers handle perfectly fine. Now, something along the lines of .mongo_find(...), which is instead executed on an instance of the DjongoManager, would return an OrderedDict object whose _id … -
Serialize a single Related Field in Django
In my Django application I am getting data from seriallizer like the following: { "id": 98, "flows": [ { "id": 99, "asked_quantity": 14, "alloted_quantity": 14, "flow": 1, "kit": 1 #this } ], "transaction_no": 2317, "dispatch_date": "2020-07-27T04:42:46.356000Z", "is_delivered": false, "model": "Rent", "driver_name": "__________", "driver_number": "__________", "lr_number": 0, "vehicle_number": "__________", "freight_charges": 0, "vehicle_type": "Part Load", "expected_delivery": "2020-07-27T04:42:46.356000Z", "remarks": "0", "send_from_warehouse": 1, #this "sales_order": 98, "transport_by": 4, "owner": 2 }, Where Flows is a manytomany connected field, I just want to Expand the kit from flows and send_from_warehouse but when I increase the depth all the related fields gets expanded. Here's how I tried doing this : class KSerializer(serializers.ModelSerializer): class Meta: model = Kit fields = "__all__" class WSerializer(serializers.ModelSerializer): class Meta: model = Warehouse fields = "__all__" class AFSerializer(serializers.ModelSerializer): kit = KSerializer(many=True) class Meta: model = AllotmentFlow fields = "__all__" class AReportSerializer(serializers.ModelSerializer): flows = AFSerializer(many=True) send_from_warehouse = serializers.RelatedField(source='warehouse.pk', read_only=True) class Meta: model = Allotment fields = "__all__" But I got the error that 'kitsis not serializable andsend_from_warehouse` vanishes from the JSON. Please explain why did that happen and what's the right way -
how to access multiple parameter from url in django?
this is my get url. I want to access all parameters like test,AAAAA,BBBBB,CCCCC please help me. http://127.0.0.1:8000/test/?text=sample&AAAAA=on&BBBBB=on&CCCCC=on -
Django redirect user before logout
I want to redirect the user to a page where he can see some statistic datas before logout. So what exactly I want is when he clicks on the logout button then first to show him that page ex: localhost:8000/statistic/ and after if he clicked on another button on that page then logout him. Now I am using Django's LogoutView: class LogoutView(SuccessURLAllowedHostsMixin, TemplateView): """ Log out the user and display the 'You are logged out' message. """ next_page = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/logged_out.html' extra_context = None @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): auth_logout(request) next_page = self.get_next_page() if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): """Logout may be done via POST.""" return self.get(request, *args, **kwargs) def get_next_page(self): if self.next_page is not None: next_page = resolve_url(self.next_page) elif settings.LOGOUT_REDIRECT_URL: next_page = resolve_url(settings.LOGOUT_REDIRECT_URL) else: next_page = self.next_page if (self.redirect_field_name in self.request.POST or self.redirect_field_name in self.request.GET): next_page = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name) ) url_is_safe = is_safe_url( url=next_page, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) # Security check -- Ensure the user-originating redirection URL is # safe. if not url_is_safe: next_page = self.request.path return next_page def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_site … -
Django exclude formfield in views for object level permission
I hope you can help me with this problem. I am working on a website where Users can create Projects with multiple members. Every User is only able to access the Projects they are a part of. Now I added different types of Users (as a ManyToMany attribute) to the Project model. So there is the Admin (who is automatically assigned when the project is created) and editors and members. I want the admin to be able to edit every field of the Form (admin can choose who is editor/member) while the editors should only be able to edit the project_image and the project_description. Here is my model: class Project(models.Model): admin = models.ForeignKey(User, default=None, on_delete=models.CASCADE) project_name = models.CharField(max_length=100,unique=True) project_description = models.TextField(max_length=2000) image = models.ImageField(upload_to='project_image/', blank=True, default='project_image/project_default.jpg') slug = models.SlugField() date = models.DateTimeField(auto_now_add=True) editors = models.ManyToManyField(User, related_name='editors') members = models.ManyToManyField(User, related_name='members',) # resized image to 200x200 thumbnail = ImageSpecField( source='image', processors=[SmartResize(200, 200)]) def __str__(self): return self.project_name def snippet(self): return self.project_description[:80]+'...' def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug=slugify(instance) pre_save.connect(slug_generator, sender = Project) Here is my form: class ProjectForm(forms.ModelForm): class Meta(): model = Project fields = ('project_name','project_description','image', 'editors', 'members',)> Specific problem: Is there a way to exclude formfields in views.py based … -
module 'urllib.request' has no attribute 'splithost'
I am using xhtml2pdf for generating pdf file in django but I keep getting this 'module 'urllib.request' has no attribute 'splithost' when I use render_to_pdf function. Following is my code: utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None View.py import os from django.shortcuts import render from django.http import HttpResponse from django.views.generic import View from .test import render_to_pdf # Create your views here. def Report_View(request): #images=os.listdir('Reports_Mangement_Unit/img/car.jpg') data={ 'name':'Muhammad Usama Hameed', 'Age':23, 'Designation':'Intern', 'Company':'Rapidev' } #return render(request,'Reports_Management_Unit/document_editor.html',data) pdf=render_to_pdf('Reports_Management_Unit/document_editor.html',data) return pdf # return HttpResponse(pdf,content_type='') -
Migrating Primary Key from UUID to Int Django
In Django, I use to have my User model instances use a UUID as the PK and have now migrated to Django's default, Int, for the PK. How can I automatically reassign all of the past PK (UUID) to Int. Thanks! -
how create a @username by taking username from registration form
i have setup the forms in the frontend what i want is that any User if gives his username for example username-> helloworld then it is interpreted as @helloworld and then this form with changed @username should be saved in the database so that i can use it afterwards..... i am a noob in django framework . i have been trying since last 2 days to find a answer here and by using google but unable to find a helpful answer here is my ->forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): class Meta: model = User fields = ['first_name','last_name','username', 'email', 'password1', 'password2'] this is my -> views.py file from django.shortcuts import render, redirect from django.contrib.auth import authenticate from django.contrib import messages from django.contrib.auth.models import User from .forms import SignUpForm from django.contrib.auth import get_user_model from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMessage from django.http import HttpResponse from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode UserModel = get_user_model() #index and signin def have been removed because it is out of context of question def signup(request): if request.user.is_authenticated: return redirect('index') else: form = SignUpForm() if request.method … -
How to set particles.js as a background
I have a small HTML file where I want the particle.js as a background but it just shows up on a certain portion of the screen please recommend some solution to it @import url('https://fonts.googleapis.com/css2?family=Rowdies:wght@700&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Work+Sans:ital@1&display=swap'); * { margin: 0; padding: 0; box-sizing: border-box; } body { background:grey; } body .container-fluid .row .col-12 ,body .container-fluid .row .col-sm-1 { left: 35%; } #wel { margin-left: 6%; font-family: 'Rowdies', cursive; } h3,h6 { font-family: 'Work Sans', sans-serif; } #submit-button { margin-left: 6%; ; } #particles-js { position: absolute; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>strong password generator</title> <br> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" href="./home.css"> </head> <body> <div id="particles-js"></div> <div class="container-fluid"> <div class="row"> <div class="col-12"> <h1 id="wel">WELCOME!!!!</h1> </div> <div class="col-12"> <br> <p> <h3>GENERATE A STRONG PASSWORD</h3> </p> </div> </div> <form action="{% url 'password' %}" method="GET"> <div class="form-group row"> <label class="col-sm-1 col-form-label" for="select-number"> Length: </label> <div class="col-sm-3 col-12"> <input type="number" name="select-number" min="6" max="20" value="12" selected='selected' placeholder="Length"> </div> <div class="col-12"> <span> <label for="UPPER" class="col-form-label"> <h6> UPPER : </h6> </label> <input type="checkbox" name="UPPER"> </span> &nbsp; &nbsp; <span> <label for="specialcharacter" class="col-form-label"> <h6>SPECIAL CHARACTER : </h6> </label> <input TYPE="checkbox" name="specialcharacter"> </span> &nbsp;&nbsp; <span> <label for="number" class="col-form-label"> <h6>NUMBER : </h6> </label> <input type="checkbox" name="number"> </span> … -
How to use a localhost API in angular
I want to use an API running at localhost:8000/data into my angular app which is running at localhost:4200. I am getting the below error in the browser. -
ValueError: Unable to configure handler 'mail_admins'
I have a problem whenever i create a new virtual environment conda create --name enc django It create an virtual env for me but whenever i tried to run my sever it throws my such error. I have also downloaded django in my system from there when i run my command it ran successfully but whenever i create a virtual environment it throws me such error. I didn't figure it out how to resolve such error or is this a bug. File "C:\Users\amurt\anaconda3\envs\env\lib\logging\config.py", line 563, in configure handler = self.configure_handler(handlers[name]) File "C:\Users\amurt\anaconda3\envs\env\lib\logging\config.py", line 744, in configure_handler result = factory(**kwargs) File "C:\Users\amurt\anaconda3\envs\env\lib\site-packages\django\utils\log.py", line 89, in __init__ self.reporter_class = import_string(reporter_class or 'django.views.debug.ExceptionReporter') File "C:\Users\amurt\anaconda3\envs\env\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\amurt\anaconda3\envs\env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File … -
I am getting this, Error: That port is already in use. for Django. It's asking me for a password, but I don't remember it
I am trying to run my server, but I am getting this, Error: That port is already in use. I looked up on stackoeverflow and found that I should use sudo lsof -t -i tcp:8000 | xargs kill -9, but it's asking me for a password which I don't know. What should I do? How do I reset my password? Is there another way to kill the current port. Thanks! -
Django on docker container returns localhost as domain in production server
I have been following this tutorial here Dockerize Django to dockerize my django application with Nginx as production web server. However inside my django code get_current_site(request).domain returns localhost as a result all generated url endpoints have the domain localhost instead of the production server domain name. my nginx.conf: here upstream fullstack_application { server web:8000; } server { listen 80; location / { proxy_pass http://fullstack_application; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /static/ { alias /home/app/web/static/; } location /media/ { alias /home/app/web/media/; } } my production docker-compose.yml: here version: "3.7" services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn fullstack_application.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: Pls help :( -
Pandas not working on uploaded csv file in Django
I making an app where the user will upload a CSV file and it will do some operations with pandas. The file is uploading and saving in the media folder correctly, but I am facing a weird problem with pandas. views.py def uploadFile(request): if request.method == "POST": form = csvForm(request.POST, request.FILES) csv_file = request.FILES['file'] if form.is_valid(): form.save() df = pd.read_csv(csv_file) print(df.head()) return redirect('home') else: form = csvForm() return render(request, 'csv_app/upload.html', {'form': form}) In the above code, it gives the error No columns to parse from file and it highlights the line, df = pd.read_csv(csv_file) but after making slight change in views.py if request.method == "POST": form = csvForm(request.POST, request.FILES) csv_file = request.FILES['file'] df = pd.read_csv(csv_file) print(df.head()) if form.is_valid(): form.save() return redirect('home') else: form = csvForm() Now it prints the DataFrame correctly. Please explain what am I doing wrong? I haven't done that much in Django Thanks in advance. -
How do I update some information at certain times of the day in django?
i have many model in my Django project, I want some of these models that are available to the user with the field to be stored in the database at a certain time after registration. for example: We have a form from a model, the user registers this form and I want this form to be saved in my database at a certain time(10 o'clock at night) How can I program this? Thanks -
How to set the value of a django autocomplete light field dynamically using JQuery
I am using Django Autocomplete Light for some fields in my form. I have the need to automatically set the value of the field when the user performs a specific action. For example, if the user checks a certain box in the form, I want the selected value of the autoselect field to change from the placeholder text to the value I need without the user having to also click the autoseelct and select the value themselves. For a standard dropdown or input, this would be accomplished by $("input-id").val("XYZ"); But this does not seem to work for autocomplete fields. I tried making changes to the generated tags that Django Autocomplete Light manages and can make it appear to select a value: $("#select2-input-id-container").attr("title", "XYZ").text("XYZ") "XYZ" now appears in the field, but when the form is submitted, it thinks nothing has been selected and submits null (or if the field is required, it asks the user to select a value). Is there a way to do this? -
Why is chart.js not showing charts?
I created a simple web application with django. I am receiving data from backend API and converting them to chart using chart.js but I don't know why my chart doesn't show until I zoom in or zoom out. My JS: fetchStock() function fetchStock(){ labels = [] price = [] fetch('http://127.0.0.1:8000/api/stock_list?format=json') .then((resp) => resp.json()) .then((data) => { console.log(data) data.forEach(function(task){ console.log(task) labels.push(task.symbol) price.push(task.price) }) console.log(labels) }) var ctx = document.getElementById("myCanvas").getContext('2d'); var chart = new Chart(ctx,{ type:'bar', data: { labels: labels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: price, }] }, }) } JSON: http://127.0.0.1:8000/api/stock_list?format=json [{"id":1,"symbol":"AKPL","price":117},{"id":2,"symbol":"CBBL","price":120},{"id":3,"symbol":"LGIL","price":293}] -
Docker compose failed while building Django app because of "grep -v" with trailing \r
I'm trying to compose up a docker-compose file and there is one step where I ran grep -v '^#' .env to get all the uncommented lines from .env file to set environment variables. In the .env file, it looks like this DB_ENGINE=django.db.backends.postgresql However, after running grep -v '^#' .env and I check the environment, variable DB_ENGINE has value of "django.db.backends.postgresql\r" (notice the trailing \r there). How can I overcome this? I've been doing this for a long time and it has never happened before. -
How to deploy our Django App online on Ubuntu Server?
I'm a beginner and still learning python and django. I want my Django app online on Ubuntu VPS. I don't know how, please help. -
How to deploy our Django App online on Ubuntu Server?
I'm a beginner and still learning python and django. I want my Django app online on Ubuntu VPS. I don't know how, please help. -
jwt token authorization is not working properly with custom role
I am using django-rest-framework and default auth_user table of Django and I create new table to manage new user_role and I extend it using auth_user.id to manage more roles like (teacher, student, staff, admin, school) but Now In Django there is only 3 decorators permission_classes (IsAuthenticated, AllowAny, IsAdminUser) to authenticate different role users to authenticate user. I am using below JWT Token Module in my Django App. JWT TOKEN: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/ Solution which I think: first make sure user is authenticated or login already, using IsAuthenticated decorator permission_classes and then I filter table and check user have enough permission to access specific route or not on basis of user role from extended user table ISSUE: I need to filter data again and again in every route to check user role. Please let me know best approach to manage this thing THANKS IN ADVANCE -
Django get_or_create model function
In one of my recent project, I created a website for users to submit their information in a multi-stage form, in each form I use get_or_create to see if the user submit information previously or not, for example, consider user education model as follows, class UserEducation(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE) university_name = models.CharField(max_length=100) in the view, I have the following code, def education_view(request): if request.method == "POST": uedu, created = UserEducation.objects.get_or_create(user=request.user) uedu.university_name = request.POST['university_name'] uedu.save() return HttpResponse("success") I didn't set uploading for the submit button and the problem is some users have multiple education object! Does anyone know why this happened and whats is wrong with get_or_create? -
Django Rest Framework y Fetch
necesito ayuda o consejos acerca de un problema de seguridad que surge en mi api. Lo que pasa es que tengo una api rest que recibe peticiones GET en django, todo mediante Fetch, todo bien, pero me gustaria saber si hay alguna forma de especificar en django que las peticiones solamente se generen a traves de Fetch, ya que al copiar mi solicitud en el navegador esta me muestra la data que se origina, y no quiero que eso pase. Ante que nada muchas gracias. -
Prevent django form from subtracting values again upon submission
This is my update function, where I can update my order details. In this form, when I update the status field to shipped values from other model fields get subtracted. But the problem I facing with my code is that every time I change other fields and update the form. The values get subtracted again. def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): box = form.cleaned_data.get('box') product = form.cleaned_data.get('product') if order.status =='Shipped': Supplement.objects.filter(supplement_name=product).update(quantity=F('quantity') - box*30) Material.objects.filter(material_name='Packs').update(quantity=F('quantity')-box) Material.objects.filter(material_name='Dispenser').update(quantity=F('quantity')-box) Material.objects.filter(material_name='Cargo Box').update(quantity=F('quantity')-box) order = form.save(commit=False) order.updated_by = request.user order.date_updated = timezone.now() if order.scheduled_date is not None and order.status == 'In Progress': order.status = 'Scheduled' order.save() form.save() return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) -
How to delete an image from the database in django
I have a database that contains images as posts and want the functionality, for images in the database to get deleted once the post gets deleted. I am using the pillow module to handle images in the database. Is there any way I could do that? In my models.py this is the code I use to save images. Just in case it was needed def save(self): super().save() img = Image.open(self.picture.path) width, height = img.size ratio = width/height if img.height > 500: outputsize = (500, (height/ratio)) img.thumbnail(outputsize) img.save(self.picture.path) Thanks a lot!