Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate pdf file using database entry in django?
I am trying to generate a pdf using database entries of a django model (basically the data was taken input by html form and submitted in database by some view) and store it in the file field of the same model. But none of the solutions posted related to this topic show how to achieve this task(or perhaps i m not able to find it out). This is my view related to storing the form entry in database def apply_purchase(request): current_user = get_object_or_404(User, username=request.user.username) print(current_user) user_details = ExtraInfo.objects.all().filter(user=current_user).first() print(user_details) user_type = HoldsDesignation.objects.all().filter(user=current_user).first() print(user_type) usertype=str.split(str(user_type)) print(usertype) # Academics Admin Check user=usertype[0] #desig_id = Designation.objects.all().filter(name='Faculty') #print(desig_id) print ("yaha se") print(user) #print(user_type) # user = request.user # user = User.objects.get(id=1).extrainfo #user=request.user if(user == "student"): return HttpResponse('You are not authorised to view this page') # user=ExtraInfo.objects.get(id=user) #print(hello) if request.method == 'POST': item_name=request.POST.get('item_name') quantity=request.POST.get('quantity') expected_cost=int(request.POST.get('expected_cost')) if expected_cost >=25000 and expected_cost <= 250000 : local_comm_mem1_id=request.POST.get('local_comm_mem1_id') local_comm_mem2_id=request.POST.get('local_comm_mem2_id') local_comm_mem3_id=request.POST.get('local_comm_mem3_id') nature_of_item1= 1 if request.POST.get('nature_of_item1') == 'on' else 0 nature_of_item2= 1 if request.POST.get('nature_of_item2') == 'on' else 0 # extra = ExtraInfo.objects.all() # extraInfo = ExtraInfo.objects.get(id=inspecting_authority_id) purpose=request.POST.get('purpose') # budgetary_head_id=request.POST.get('budgetary_head_id') # inspecting_authority_id=request.POST.get('inspecting_authority_id') expected_purchase_date=request.POST.get('expected_purchase_date') # print(expected_purchase_date+"...........................") # xyz=apply_for_purchase(indentor_name=name,) # xyz.save() print("hello1") a = apply_for_purchase.objects.create( item_name=item_name, quantity=int(quantity), expected_cost=expected_cost, nature_of_item1=nature_of_item1, nature_of_item2=nature_of_item2, purpose=purpose, # budgetary_head_id = … -
Django: Why is commit not happening?
In a django project, we have a signal handler which starts a celery task on_commit, like so: @receiver(post_save, sender=AThing) def do_stuff(sender, instance, created, **kwargs): on_commit(lambda: some_task.delay(instance.id)) In the tests it seems commits are not being triggered when saving AThing instances. I've confirmed that do_stuff gets called as expected when an instance of AThing is saved, but that seems to be as far as it ever goes - some_task never seems to get called. I've tried patching some_task.delay in order to prove the theory: with patch('some_module.some_task.delay') as mock_do_stuff: mock_do_stuff.side_effect = raise_a_debug_error Where raise_a_debug_error is a def which simply raises an error to prove that code was run, but no debug error ever gets raised. If I leave that patch in place and alter the do_stuff def to remove on_commit like so: @receiver(post_save, sender=AThing) def do_stuff(sender, instance, created, **kwargs): some_task.delay(instance.id) Then the error gets raised as expected in the test. In the real system, the on_commit is necessary, as per celery's docs: https://celery.readthedocs.io/en/latest/userguide/tasks.html#database-transactions I have tried both TestCase and TransactionTestCase. So what am I doing wrong? Why is on_commit never triggering? Is there a different mocking strategy that needs to be employed when on_commit is involved? -
How to use google cloud storage along with s3 using django-storage
I have a model where I have a ImageField that uploads the image on google cloud storage bucket. But I want to add FileField to upload .pdf and .pub files on Digitalocean spaces. I can't figure out how to do that as DEFAULT_FILE_STORAGE is set to 'storages.backends.gcloud.GoogleCloudStorage' -
Can Django admin user edit the base.html page from backend?
I'd like to edit the background image of in the base.html template. I was thinking of having a model and form, that way the user/admin can just upload new images to the background. The issue I think I'm having is referencing the base.html template directly since it's never called directly. I was thinking of just pushing the style in line, or editing the CSS directly would be cool too. I just have only been able to toggle different CSS prewritten codes I've tried having a base_view(request) but doesn't work (base.html is never called, so I assume that's why and obviously the extended pages don't modify the base.html) def base_view(request): context = { 'post': BackgroundImage.objects.last() } return render(request, 'base.html', context) So this is what I have: models.py: class BackgroundImageModel(models.Model): image = models.ImageField(default="default.jpg", upload_to='background_pics') author = models.ForeignKey(User, on_delete=models.CASCADE) def save(self): super().save() img = Image.open(self.image.path) if img.height > 2000 or img.width > 2000: output_size = (2000, 2000) img.thumbnail(output_size) img.save(self.image.path) views.py: class BackgroundImage(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BackgroundImageModel fields = ['image'] base.html: {% if background %} <body style="background: url({{ background.image.url }}) repeat fixed center; margin: 5rem 0 2rem 0;"> {% else %} <body style=" margin: 5rem 0 2rem 0;"> {% endif %} -
Django: Send a Post Request Through Form to Another Server
I have a form on a template on my domain1 and want to send a POST request to domain2. I am using Django as the framework. I only want domain2 to accept requests from domain1 and domain2 (itself). However, I run into csrf problems. -
how display contexts of two different app and different view in one template in one project in django?
i have a project with different views and different function on it. i want to access and display context of one of view in other html app. this my code washer.views.py def Product_list_view(request): product_list_view = Product.objects.all() best_post = Product.objects.order_by('timefield')[0:2] context = { "product_list_view": product_list_view, 'best_post':best_post } template_name = "product_list_view.html" return render(request,template_name,context) gasket.views.py def home(request): template= "base.html" return render(request,template,context={}) how i can access context of product_list_view and show it in base.html ? can i set one html to two different views in different app ? and access to context both of them ? what i have to do ? tnx for help me . -
Can you insert a static tag into a style tag?
I'm trying to link the proper path for a static file but I can't seem to insert that static tag into a style tag. {% load static %} The errror message I get it: Could not parse the remainder: '/blog/img/home.jpg')'' from ''background-image:url('/blog/img/home.jpg')'' -
Nginx HTTPS: Potential Security Risk Ahead in browser
After configure Nginx for HTTPS connection everything work good. I can connect with my website by https connection, but in browser i have to add excpetion if i want to go on website. All of peoples have to do that. How to remove that? i dont want to have this information on my website: Potential Security Risk Ahead enter image description here -
Django: Retrieving database entry based on user instance
I am have an app that allows patient to reserve doctor's appointments. On the doctor's portal, I want to retrieve all appointments that is connected to the doctor using the portal. The problem is "Cannot query "Person Name": Must be "Doctor" instance. Upon debugging I realized that doctor actually refers to the upin specified in the Doctor model instead of the username. Models.py: class User(AbstractUser): users = ( ('doctor', 'Doctor'), ('patient', 'Patient'), ('assistant', 'Assistant'), ) user_type = models.CharField(choices=users, max_length=9, default='patient') #return the users' name def __str__(self): return self.first_name + " " + self.last_name class Doctor(models.Model): upin = models.AutoField(primary_key=True) #unique physician identification number user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = "doctor" specialty = models.CharField(max_length=20) appointments_per_hour = models.IntegerField(null=True) picture = models.ImageField(upload_to = '', default = '') #return the doctors' name def __str__(self): return str(self.user) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = "patient" pid = models.AutoField(unique=True, primary_key=True) #patient identification #return the patients' name def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == "doctor": Doctor.objects.create(user=instance) elif instance.user_type == "patient": Patient.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.user_type == "doctor": instance.doctor.save() elif instance.user_type == "patient": instance.patient.save() class Appointment(models.Model): TIMESLOT_LIST = ( (1, '10:00 – 11:00'), (2, '11:00 … -
Best way to make a searchable models.ForeignKey in Django
I have hundreds of ForeignKeys in my model. I want to make it "Searchable" so i can search for an item i wan to find.. Something like Q(product_name__icontains=query) but in my inlineformset_factory. So when I am about to pick an item in a form i can first narrow the results by typing a word that is a part of the "product_name" field Was trying to find some third-party libraries but having found anything suitable yet... model: class InvoiceItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,null=True) invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, null=True) quantity = models.DecimalField(max_digits=5,decimal_places=0) items_total = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) def __str__(self): return self.product.product_name inlineformset_factory : InvoiceInvoiceItemFormset = inlineformset_factory(Invoice, InvoiceItem, extra=50, exclude=(),can_delete=True) I want to make picking a foreignkey in a inlineformset_factory "searchable" Any ideas ? -
Hay there! How can I get the Clickable "id" for the "thumbs up" used in messenger. Because when I am using the title id .click(); is not working
I'm not able to use .click() method while using the title id of "thumbs-up" in the messenger. There was a path given inside the tag. I just want to know how I can click over the thumbs up. I also tried it with SVG class. But it was also showing "null" or not clickable. I have used this method to like facebook images. I was able to get the right id of it. But now I am confused in the SVG part of the thumbsUP section. var thumb=document.getElementsById('js_sf'); for(var i=0; i<2; i++){ thumb[i].click(); } I was expecting that using this method "2 thumbs ups" would be sent. But now its showing "can not read property click. -
How can I apply this style in Django? (radio type)
How can I apply this style in Django? just one class i can apply in django but double class i cant do that. Django 2.1, python 3.7 I want use this css style https://bootsnipp.com/snippets/Zk2Pz <div class="funkyradio"> <div class="funkyradio-default"> <input type="radio" name="radio" id="radio1" /> <label for="radio1">First Option default</label> </div> <div class="funkyradio-primary"> <input type="radio" name="radio" id="radio2" checked/> <label for="radio2">Second Option primary</label> </div> <div class="funkyradio-success"> <input type="radio" name="radio" id="radio3" /> <label for="radio3">Third Option success</label> </div> <div class="funkyradio-danger"> <input type="radio" name="radio" id="radio4" /> <label for="radio4">Fourth Option danger</label> </div> <div class="funkyradio-warning"> <input type="radio" name="radio" id="radio5" /> <label for="radio5">Fifth Option warning</label> </div> <div class="funkyradio-info"> <input type="radio" name="radio" id="radio6" /> <label for="radio6">Sixth Option info</label> </div> </div> I want apply this part, and my django form class is class DataUploadForm(forms.ModelForm): class Meta: model = DataUpload fields =('Type', 'Kind', 'description', 'document',) widgets = { 'Type': forms.RadioSelect(attrs = {'class' : 'funkyradio funkyradio-default'}), 'Kind': forms.RadioSelect(), } but it isn't work I want radio form using that css -
How to restrict django by taken letter 'e' in integer field in django admin
This is my code for integer field in models.py qty = models.PositiveIntegerField(default='empty') -
Errors from server I think, why do i get them
I get this error in django, I think it might be a server issue, but not sure whats happenning. What could be wrong with it. Traceback (most recent call last): File "/usr/lib/python3.6/socketserver.py", line 651, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.6/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.6/socketserver.py", line 721, in __init__ self.handle() File "/home/david/.envs/env1/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/home/david/.envs/env1/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 194, in handle_one_request handler.run(self.server.get_app()) File "/usr/lib/python3.6/wsgiref/handlers.py", line 144, in run self.close() File "/home/david/.envs/env1/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 111, in close super().close() File "/usr/lib/python3.6/wsgiref/simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split' Internal Server Error: /Nittan/dashboardbusiness/ Traceback (most recent call last): File "/home/david/.envs/env1/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/david/.envs/env1/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/david/.envs/env1/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/david/miniconda3/hedge2/Nittan/views.py", line 205, in business_dashboard stat=reg1[0] File "/home/david/.envs/env1/lib/python3.6/site-packages/django/db/models/query.py", line 303, in __getitem__ return qs._result_cache[0] IndexError: list index out of range -
Django: How to fill inherited form fields from an instance of the base model class?
I have a model Customer, which inherits from a User model. class Customer(User): customer_since: models.Datefield() I then want to use use a generic view to create customers: class CustomerCreate(CreateView): model = Customer form_class = CustomerForm When I create a new customer, I want to use the data from request.user to autofill the form with the inherited fields. How can I do that? I know that if I was creating the record manually, I would do it like this: Customer.objects.create(user_ptr=request.user, customer_since=datetime.date.today()) but with a generic view how it is done? -
How do i fix this load static file code in django 2.0?
I have loaded bg image in my html page but its not rendring it . please help ! <style> body { background-image: url("{% static 'blog/b2.jpg' %}"); background-repeat: no-repeat; background-size: cover; } -
Unable to upload large file to s3 bucket
I deployed my Django app to AWS Elastic Beanstalk and tried to upload some csv file. It seems that small csv file works fine (1000 lines) but with large csv file it cannot be uploaded (1,000,000+ lines). Any idea how to fix that? Besides, upload large file can be done from my local host but failed when on the Elastic Beanstalk URL. Working in Python and Mysql. -
Calculate a form field, based on the previous forms in the formset
I have an inline formset, attached to a main form, and I'm trying to do some updates to a formset form field: So I inherit from BaseInlineFormSet. I know I can do the validation at the form level using clean_field, but I need to number if the teck field was completed. Basically each form of the formset depends if the field 'teck' was completed on previous forms. class BaseTeckInlineFormSet(BaseInlineFormSet): def clean(self): super().clean() idx = 0 for form in self.forms: if form.cleaned_data['teck']: ...... form.cleaned_data['key'] = ... I receive a key error, because looks like cleaned_data is empty -
Django / Django rest framework view uncaught exception
When I have DEBUG=True in my settings I can see the following error Traceback: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view 116. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 495. response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create 21. self.perform_create(serializer) File "/device_mgmt/selection/views.py" in perform_create 84. serializer.save(realm=utils.get_realm_from_request(self.request)) File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in save 214. self.instance = self.create(validated_data) File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in create 943. instance = ModelClass._default_manager.create(**validated_data) File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in create 422. obj.save(force_insert=True, using=self.db) File "/device_mgmt/selection/models.py" in save 123. self.full_clean() File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in full_clean 1203. raise ValidationError(errors) Exception Type: ValidationError at /company/api/company/ Exception Value: {'id': ['Company with this Id already exists.']} The model is throwing an error but the rest framework view is calling 455. self.raise_uncaught_exception(exc) How can I make it so that rest framework uses the exception from the django model? I thought this would get handled automatically as the exception has the info about what went … -
How to use Multiple Databases in Django Application using Database Router
Am trying to implement multiple Database support for my django Existing appplication.I have already tried the approach provided in dajngo offical documentation. But my requirement is quite diffrent from what the documentation has stated. In a django functions, you could call request.session.['user'] and perform actions based on that. In my case, I would like to be able to switch databases depending on the session varaible assigned at the time of login. Is there anyway to inject a request/session call into the db_for_read() and db_for_write() methods like in the following class DataBaseRouter: def db_for_read(self, model, **hints): if request.session['user'] == "Some value": return "master" return "default" def db_for_write(self, model, **hints): if request.session['user'] == "Some value": return "master" return "default" I am using Django 2.0.1 currently, and I have tried the following code, am not sure it's a correct approach or not, following is what I have implemented and I couldn't access session or request objects. from django.http import HttpRequest class DataBaseRouter: def db_for_read(self, model, **hints): request = HttpRequest() if request.session['user']=="Value": return 'second' return first def db_for_write(self, model, **hints): request = HttpRequest() if request.session['user']=="Value": return 'second' return first I expect to access Session variables or request object just like we can access them … -
Python/Django Strange behavior with object dictionary and __dict__
I have a portion of a Django project that involves submitting apartment applications into a system and I am noticing strange behavior with finding an application using the ORM and then turning the object into a dict calling __dict__ in order to pre-populate a form. I am curious if anybody can explain either what is happening or what I am doing wrong. Basically, I have a Foreign Key in my UnitApplication model so Applications are mapped to Properties, this database column name and the attribute name in my Model is property_id, however when I turn the object to a dictionary it appends and extra _id to the field name. Here is my code: application_id = request.GET.get('application_id') application = UnitApplication.objects.using(db_alias).get(id=application_id) # this is in a view so property_id == Property Object (1) print(application.property_id) # this will print my actual property_id, which is 1 print(application.property_id.id) # this is the odd behavior, here is the dict that prints, and hinders form filling # {..., 'property_id_id': 1, ...} print(application.__dict__) What is going on? I can fix this by editing the dict, but I feel like this is buggy. Note: I am using a regular Form for this because it provided me a bit more … -
How to pass arguments from javascript to django view?
I'm trying to do page with simple calculator. I made calculator in js, and now, when I click button I want to pass arguments from js to django. Count them there and print on redirect page. I have problem with redirect page. My actual code work without redirect page from 'http://127.0.0.1:8000/' to 'http://127.0.0.1:8000/calc'. html code: <form action="calc/" method="post"> {% csrf_token %} <input id='btn' type="submit" value="CALC" onclick="change()"> </form> javascript code: function change(){ var foo = 1; var foo1 = [1, "tralal", true, '']; $.ajax({ url: 'calc/', data : { 'foo': foo, 'foo1': foo1, }, success: function (data) { alert("it worked!"); } } )}; urls in django path('calc/', views.calc, name='calc') view in django def calc(request): foo = request.GET.get('foo') print(foo) foo1 = request.GET.getlist('foo1[]') print(foo1) context = {'data': foo1} return render(request, 'calc.html', context) When I dont put button in , js script call calc view, but dont redirect page. I want redirect page and print a result there. -
Python social auth addon doesnt work properly with VK.com
I have installed "social_django"(Python Social Auth ) app to arrange authorization to my site via VK.com. Project is on Django 2.2. It works, but problem is that it creates new user with a new name each time I trying to authorize myself via Social auth, regardless to the fact that user with the same email is already exists in the database(AbstractUserModel). Settings are bellow. Theoretically, according the documentation at least “social_core.pipeline.social_auth.associate_by_email” pipeline element should check these situation of 2 users with same emails ant authorize it, but it stubbornly creates new one instead. I have been trying to remove 'social_core.pipeline.user.create_user', but it doesn’t work then at all. AUTHENTICATION_BACKENDS = ( "social_core.backends.vk.VKOAuth2", "django.contrib.auth.backends.ModelBackend" ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.associate_by_email', ) SOCIAL_AUTH_VK_OAUTH2_KEY = "xxxxxxxxxxxx" SOCIAL_AUTH_VK_OAUTH2_SECRET = "xxxxxxxxxx" SOCIAL_AUTH_VK_OAUTH2_SCOPE = ["email"] SOCIAL_AUTH_VK_APP_USER_MODE = 2 context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', "social_django.context_processors.backends", "social_django.context_processors.login_redirect", it seems that it possible to make your own pipeline element for VK.com. Does anyone has it ,or maybe any advice would be valuable, or perhaps I should think in an alternative direction. Perhaps you know better app for this task then Social-Django? Anyway, thank you in advance. I have … -
Why does Django return X-Frame-Options SAMEORIGIN from views decorated with xframe_options_exempt?
I have a Django view decorated with @xframe_options_exempt, and I'm hosting it in an iframe. The GET request on the view works fine, but the POST results in a browser error because the response comes back with X-Frame-Options set to SAMEORIGIN. Why isn't @xframe_options_exempt working? -
What is `defer` and `only` stands for in Django?
I am new to Django. What is the meaning of defer amd only stands for in Django QuerySet? For an instance, I have following model class Car(models.Model): name = models.CharField() color = models.CharField() gears = models.IntegerField() What would be the impact of following two queries and what is difference between both? Car.objects.defer('color') Car.objects.only('color')