Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In my selenium file, I want to add printed data i.e. odr_id of terminal to database using model.py or any alternative option?
odr_id = pay.find_element_by_id('deep-dtyp-order-details-section') sleep(3) print(odr_id.text) #views.py def odr(request): name = odr_id.GET(request) return [Amazon.order_detail, name] pass -
reportlab in django, return a string instead of a pdf
I am working in an application in which I need to create pdf file from response which I am getting from server. I am using reportlab with django 1.8 and the response looks like this: %PDF-1.3 %���� ReportLab Generated PDF document http://www.reportlab.com 1 0 obj << /F1 2 0 R >> endobj 2 0 obj << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj 3 0 obj << /BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /DCTDecode ] /Height 1250 /Length 1206832 /Subtype /Image /Type /XObject /Width 1667 >> stream [...] here is my code : def generate_pdf(request,course_id): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # # change the page size p.setPageSize((500,500)) # # Draw the image at x, y. I positioned the x,y to be where i like here p.drawImage('fond.jpg', 0, 0, width=500,height=500) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() … -
Is there a way to start/stop a celery task from django views?
I just finished my celery task for my django app, but I'm looking a way now for how to start/stop it through a toggle button on my frontend UI. I know it can do on django-admin(built in). but I want to make it for the app. like from a typical django view and restapi, you create a function like this: def start_task and def stop_task and call it through api(URL) to execute it. How can I do it? Thanks! -
unable to save files to django model through rest api serializers
I am trying to use djangrest api to upload multiple files to a single model, while trying to do so, though I can pass my files through serializer but couldnt save those on my model. Here is my models.py from django.db import models # Create your models here. class UploadedImage(models.Model): img = models.ImageField('Uploaded Image', upload_to='images') # stores uploaded image # dt_created = models.DateTimeField(auto_now_add=True, blank= True, null= True, verbose_name='Created') my admin.py from django.contrib import admin from .models import UploadedImage # Register your models here. admin.site.register(UploadedImage) My viewsets.py from django.shortcuts import render from rest_framework import viewsets from imageUpload.serializers import UploadedImageSerializer from imageUpload.models import UploadedImage from rest_framework.response import Response from rest_framework import parsers from rest_framework import status # Create your views here. class UploadImageViewset(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = UploadedImageSerializer def create(self, request): serializer_class = UploadedImageSerializer(data=request.data) if 'img' not in request.FILES or not serializer_class.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) else: # Single File # handle_uploaded_file(request.FILES['file']) # Multiple Files files = request.FILES.getlist('img') for f in files: handle_uploaded_file(f) serializer_class.save() return Response(status=status.HTTP_201_CREATED) def handle_uploaded_file(f): with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) Here is my serializers.py from rest_framework import serializers from .models import UploadedImage class UploadedImageSerializer(serializers.ModelSerializer): img = serializers.FileField(max_length=None, allow_empty_file=False) class Meta: model = UploadedImage fields = … -
Django - how to cache template for all url prefix
I have a Django app which renders html template and loads data into html via ajax from front end(based on url's dynamic id). For eg., this is my site's dynamic url pattern "www.mysite.com/order/< some dynamic id>", I want django to cache & return all the requests to this url prefix r"^**www.mysite.com/order/**" to render the html without hitting my views function. Currently, each dynamic id in the url pattern ("/order/100","/order/101","/order/102..etc")is coming to my views and rendering the same template for each. I'm expecting, anyone visits with prefix "/order/" the html template needs to be rendered automatically without hitting my views. I'm currently using redislite for caching, Please help me with a solution. -
Django : Media Files not displayed in templates
I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error). Media Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) Project urls.py: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin' , admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")), ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) App urls.py: from django.urls import path, re_path from django.conf.urls import include, url from app import views from . import views urlpatterns = [ path('', views.index, name='home'), url(r'^blog$', views.blog_view, name ='blog'), url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'), re_path(r'^.*\.*', views.pages, name='pages'), ] Views.py … -
How to show suggestions of existing child record in TabularInline in django admin?
I want to show suggestion of existing child record while adding child record to parent. class IndustryInline(admin.TabularInline): model = Industry class ParentIndustriesAdmin(admin.ModelAdmin): list_display = ('id', 'name') search_fields = ['id', 'name', ] ordering = ['-date_modified'] inlines = [ IndustryInline, ] def save_model(self, request, obj, form, change): obj.modified_by = request.user obj.save() admin.site.register(ParentIndustry, ParentIndustriesAdmin) How to get suggestion for existing records like we get in case of ManytoMany relationship. -
Django view doesn't properly redirect
When view function - index is called with post request it doesn't redirect. Print inside the function executes. Can't find reason. I changed return redirect('/result') to return HttpResponse("some text") and it does not work either. My code: data = {"number" : 0} @csrf_exempt def result(request): global data response = "solution: " + str(data['number']) return HttpResponse(response) @csrf_exempt def index(request): global data if request.method == 'POST': uploadFile1 = request.FILES['file1'] uploadFile2 = request.FILES['file2'] text1 = '' text2 = '' with open('file1', 'wb+') as file1: text1 = uploadFile1.read() with open('file1', 'wb+') as file2: text2 = uploadFile2.read() data = calcpy.views.getNumber(str(text1), str(text2)) print('test') #this executes return redirect("/result") template = loader.get_template('main.html') context = {'solution' : 0} return HttpResponse(template.render(context)) My urls.py code: from django.conf.urls import patterns, include, url from . import views import version.models web_srv_prefix = version.models.getWebSrvPrefix() urlpatterns = patterns('', url(r'^' + web_srv_prefix + '/ajax/(?P<module>\w+)/(?P<function>\w+)/', views.ajax, name='ajax'), url(r'^$', views.index, name='index'), url(r'^result/$', views.result, name='result') ) -
Django - TypeError - Field 'id' expected a number but got <WSGIRequest: GET '/marketplace/add_to_cart/5/'>
I'm pretty new to Django and face a problem trying to implement a cart for my e-shopping website. As I call my "add_to_cart" function, I want to be sure if either a cart exists for this session, and if there is already a reference for the selected item in this cart. Here is my models.py : CART_ID = 'CART-ID' class Cart(models.Model): creation_datetime = models.DateTimeField(auto_now_add=True) update_datetime = models.DateTimeField(auto_now=True) checked_out = models.BooleanField(default=False) user = models.ForeignKey(User,on_delete=models.DO_NOTHING, null=True, blank=True) @classmethod def create(cls): cart_id = request.session.get(CART_ID) if cart_id: cart = models.Cart.objects.filter(id=cart_id, checked_out=False).first() if cart is None: cart = cls() request.session[CART_ID] = cart.id else: cart = cls() request.session[CART_ID] = cart.id return cart def add(self, article, prix_unitaire, quantite=1): item = Item.objects.filter(cart_id=self.id, article=article).first() if item: item.prix_unitaire = prix_unitaire item.quantite += int(quantite) item.save() else: Item.objects.create(cart_id=self.id, article=article, prix_unitaire=prix_unitaire, quantite=quantite) class Item(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) quantite = models.PositiveIntegerField() prix_unitaire = models.PositiveIntegerField() def prix_total(self): return self.quantite * self.prix_unitaire prix_total = property(prix_total) in my views.py, I defined my "add_to_cart" function : def add_to_cart(request, pk, quantite=1): article = Article.objects.get(pk=pk) cart = Cart(request) cart.add(article, article.prix_unitaire, quantite) and my urls.py urlpatterns = [ ... path('add_to_cart/<int:pk>/', add_to_cart, name='add_to_cart'), As I call the function, I get this error : TypeError at /marketplace/add_to_cart/5/ Field … -
Is there any way to save data into third(join) table? django
I have 2 main tables which I join them with many to many. I have some checks and I need to save the data into this join table. I made a research but can't really find how to save data in this kind of table. for patient in patients: patientDatabase, created = Patient.objects.get_or_create( coreapi_id=patient["ID"], defaults=dict( first_name=patient["first_name"], last_name=patient["last_name"], email=patient["email"], ), ) # Get the last saved record from DB lastPatient = (Patient.objects.latest('coreapi_id')) roles_DB = list(Role.objects.values()) for role in patient['Roles']: if role['name'] == roles_DB[0]['role_name']: Save the result(data) into role_role_id this is what my model looks like: class Patient(models.Model): coreapi_id = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) language = models.CharField(max_length=20) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Role(models.Model): role_id = models.ManyToManyField(Patient) role_name = models.CharField(max_length=100) -
notification to say "please make your screen landscape" in phone screen with django
how can i make notification to say "please make your screen lanscape" when phone screen is horizontal? -
Django How to display error if the query results are empty
I am building a simple app which enables the users to search quotes from db by entering keywords using a form. I would like to return an error if "no matching quotes are found for the entered keywords" . Kindly guide me. Heres the search form: <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search By Keywords" id="q" required /> <button onClick="{% url 'search_results' %}" class="btn btn-success">Search Quotes</button> </form> -- Heres the views.py {% for quotes in object_list %} <div class="shadow card"> <div class="card-body"> <h6 class="card-title">{{ quotes.by }}</h6> <p>{{ quotes.quotation }}</p> </div> </div> {% endfor %} -
getting 'str' object has no attribute 'get' when using django template tags
template {{ show_details.message|get_value:"data_errors"}} template_tags.py @register.filter def get_value(dictionary, key): print("DICTIONARY",dictionary,"KEYYY",key) #output for this is ('DICTIONARY','','KEYYY',u'data_errors') return dictionary.get('key') AttributeError: 'str' object has no attribute 'get' -
django rest api framework "list" obj has no attribute values
I trying to pass some files through djangorest framework and while trying to do so, I am facing error 'list' object has no attribute 'name' my views.py from django.shortcuts import render from rest_framework import serializers from rest_framework import viewsets from rest_framework import status from rest_framework.response import Response from restfilesupload.serializers import FileSerializer class FileUploadViewSet(viewsets.ViewSet): def create(self, request): serializer_class = FileSerializer(data=request.data) if request.method == 'POST': if 'file' not in request.FILES or not serializer_class.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) else: handle_uploaded_file(request.FILES.getlist("file")) return Response(status=status.HTTP_201_CREATED) def handle_uploaded_file(f): with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class Meta: fields = ['pk' , 'file'] my serializers.py from rest_framework import serializers class FileSerializer(serializers.Serializer): file = serializers.FileField(max_length=None, allow_empty_file=False) -
Update item that contains file without file reupload in RetrieveUpdateAPIView
class Item: name = models.CharField(...) document = models.FileField(...) class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' class UpdateItemAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated, ) serializer_class = ItemSerializer parser_classes = (MultiPartParser, FormParser) In GET response I see "photo": "127.0.0.1:8000/media/items/11/01/2021/file_name.pdf" What should I put as a value when I want to update Item but photo file is the same? If I put a path to the file that I grab from GET response, I see a validation error that it is not a file. Vue.js var formData = new FormData(); formData.append("photo", this.photo); for (var key in data) { formData.append(key, data[key]); } this.$http .put(`/api/item/update/${this.itemID}/`, formData, { headers: { "X-CSRFToken": this.getCookie("csrftoken"), "Content-Type": "multipart/form-data" } }) -
I am trying to create drop down menu in django but my code is showing only text box ? Help Appricated
I have defined modles.py, view.py, and forms.py but unable to get the drop-down menu. at initial, I have created moodle.py using os_choice and later on a substitute in the operating_system. further, I have created forms and I am using crispy forms to render in front page. likewise, I have defined this in views.py but when I see it on the font page it shows only a text file, not a drop-down with choices. Here is my model.py code: from django.db import models from django.utils.encoding import smart_text from multiselectfield import MultiSelectField # Create your models here. class ResultQuery(models.Model): os_choice = ( ('Windows 10', 'Windows 10'), ('Windows 8', 'Windows 8'), ('Linux', 'Linux'), ) operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice) level = models.CharField(max_length=30) program = models.CharField(max_length=30) semester = models.CharField(max_length=20) exam_year = models.IntegerField() institute = models.CharField(max_length=4) reg_no = models.CharField(max_length=50) symbol_num = models.IntegerField() student_name = models.CharField(max_length=50) dob = models.DateField() sgpa = models.TextField() result = models.CharField(max_length=40) name = models.CharField(max_length=30) subject1_code=models.CharField(max_length=40) subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.TextField() subject1_grade=models.TextField() subject1_remarks=models.CharField(max_length=20, null=True, blank=True) subject2_code = models.CharField(max_length=40) subject2_title = models.CharField(max_length=40) subject2_credit_hour = models.TextField() subject2_grade_point = models.TextField() subject2_grade = models.TextField() subject2_remarks = models.CharField(max_length=20, null=True, blank=True) subject3_code = models.CharField(max_length=40) subject3_title = models.CharField(max_length=40) subject3_credit_hour = models.TextField() subject3_grade_point = models.TextField() subject3_grade = models.TextField() subject3_remarks = models.CharField(max_length=20, null=True, … -
How to use filter_horizontal with TabularInline and .through?
My models are class Test(models.Model): name = models.CharField(max_length=255) class Testrelated(models.Model): name = models.CharField(max_length=255) tests = models.ManyToManyField(Test, related_name='tests') And admin: class TestrelatedInline(admin.TabularInline): extra = 0 model = models.Test.tests.through filter_horizontal = ('name') class TestAdmin(admin.ModelAdmin): list_display = ('id', 'name') search_fields = ('name',) inlines = [ TestrelatedInline, ] The problem is that .through has no the model fields. So I can not refer to any field using filter_horizontal. <class 'app.admin.TestrelatedInline'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'name', which is not an attribute of 'app.Testrelated_tests'. I have created a test stand https://gitlab.com/marataziat/testdjangoproject. -
Creating a waiting room Django
I would like to create something like FaceTime on a website based of the tastes of the users. I thought about creating a waiting room where all users will be. Then a matching algorithm will try to pair two of the users and take them to a private room where they will be able to chat. I have made a simple music controller with the following tutorials: https://youtube.com/playlist?list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j The problem is that I don’t know how to create a room by default. A room which is always active and where I can put my users in it :/ PS: I use Django with python and rest framework for the backend. Thanks -
Not working Import tool and template override at the same time for same model
Trying to use both import tool and Django admin template override on the same model. However, it not working same time . Is there a particular solution for this? -
djongo aggregate in python django
i`m using mongodb(3.6) in python(3.8.5) django(3.1.5). and i have used djonjo(1.3.3) for mongodb connection. when i have run aggregate query with model.objects.aggregate({'$graphLookup': { 'from': 'categories_categories', 'startWith': 'id', 'connectFromField': 'sub_category', 'as': 'SubCategory' } }) so i am getting error QuerySet.aggregate() received non-expression(s): {'$graphLookup': {'from': 'categories_categories', 'startWith': 'id', 'connectFromField': 'sub_category', 'as': 'SubCategory'}}. -
How to create multiple instances in DRF?
I have a list of data coming in a request, and after filtering taken out data that needs creation, I'm passing it to the serializer create method, but I'm getting this error: AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `apps.some_app.serializers.SomeSerializer`, or set `read_only=True` on nested serializer fields. My view looks like this: class MyViewSet(ModelViewSet): # Other functions in ModelViewset @action(methods=['post'], url_path='publish', url_name='publish', detail=False) def publish_data(self, request, *args, **kwargs): new_data = util_to_filter_data(request.data) serializer = self.serializer_class(data=new_data, many=True) if serializer.is_valid(raise_exception=True): serializer.create(serializer.validated_data) return Response() I understood the error, that I am passing nested fileds in the create method. But, when I am directly calling my Viewset with single POST request, it is created successfully, even though it too contains nested fields. What am I doing wrong here? -
Angular 8 , angular chosen not working after build
Currently I am developing website using django and angular 8. for dropdown I have used angular-chosen and I have configured it in angular side using angular-chosen package. On Angular side dropdown working properly with angular-chosen and I am able to get expected results as shown in SS below. But after build into my django application, angular chosen not able to load.I have attached screenshot as below. I have done same configuration as have been suggested in below plunker. https://embed.plnkr.co/plunk/N5KF1d I have tried a lot to find solution but not able to. So guys please let me know if anyone have solution for it. Thanks. -
How to add or remove fields from a serializer based on a condition?
I'm creating a simple Todo app and I want to provide an api for it. A todo task maybe completed or not. if it's not completed yet, then the field Todo.date_completed will be null. I want to let the same serializer send the field date_completed if it's not null. One solution would be to let date_created be a SerializerMethodField and send some string like "Not completed yet" in case it's not completed. But that's not really helpful since the client will be asking for the tasks that're not completed anyways... Another solution would be like here, I've rewritten the same class (Meta) twice just to remove the value from rest_framework import serializers from todo.models import Todo class TodosSerializer(serializers.ModelSerializer): date_created = serializers.ReadOnlyField() date_completed = serializers.ReadOnlyField() class Meta: model = Todo fields = ['title', 'memo', 'date_created', 'date_completed', 'is_important'] class PendingTodosSerializer(TodosSerializer): class Meta: model = Todo fields = ['title', 'memo', 'date_created', 'is_important'] How to let the field date_completed be sent only in case it's not null? And one extra question, in case there is no way, can I somehow remove the field date_completed from PendingTodosSSerializer.Meta without rewriting the entire class again so that I don't have to copy and paste the code? -
How do I set the duration of the output of a job in Elastic Transcoder using Django?
I want to automate using Amazon's Elastic Transcoder to trim a video file in Django. My code so far is: def trim_video(key, new_key, duration): pipeline_id = 'XXXXXXXXXXXX-XXXXXX' region = 'XXXXXXXX' transcoder_client = boto.elastictranscoder.connect_to_region(region) create_job_result=transcoder_client.create_job(**{ 'pipeline_id': pipeline_id, 'input_name': {'Key': key}, 'output': { 'Key': new_key, "PresetId": 'XXXXXXXXXXXXX-XXXXXX' } }) print('Job has been created. The output key will be ' + new_key) This code will cause the file to be transcoded but will not trim it. What do I add in order to trim the video? -
how to add two different tables data in one table through button in django without form
urls.py path('books/<int:book_id>/',addfavourite,name='addfavourite') This is the model table. models.py class Library(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) book = models.ForeignKey(Book,on_delete=models.CASCADE,related_name='library') def __int__(self): return self.library_id views.py def addfavourite(request, pk): userid = auth.get_user(request) bookdetail = get_object_or_404(Book, pk=pk) if request.user.is_authenticated: favourite = Library() favourite = Library.objects.create(user=userid,book=bookdetail) favourite.save() else: return reverse('books.html') The button to add data as no user value is needed. <button type="submit" href="{% url 'addfavourite' bookdetail.pk %}" class="button"> I am not getting error but the data is not created in table.