Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Dynamic storage folder for models.ImageField
I have an ImageField in my model which I want to store the image url dynamically depending on a user session var. Imaginary like this: logo = models.ImageField(null=True, upload_to = 'empresas/'+codEmp+'/logo/') And the var codEmp is a session variable: request.session['codEmp'] Therefore if the codEmp of a user is for example 'McDonalds' it should save the following path: 'empresas/McDonalds/logo/imaginary_picture.jpg'. I tried by init but I can't finish it and I'm not sure if it'll work. class Empresa(models.Model): def __init__(self, filter_on, *args, **kwargs): super(Empresa, self).__init__(*args, **kwargs) codEmp = filter_on logo = models.ImageField(null=True, upload_to = 'empresas/'+codEmp+'/logo/') I tried to do this in the ModelForm but it seems that forms.ImageField doesn't have an upload_to attribute. -
Django REST and React implementation model
I am currently creating a website hosted by Django. I plan to use React as my frontend framework. I have done some research on putting them together but most say that I should go for the SPA model and have separate web servers for frontend and backend. The problem is that I wish to use apache as a prod server with django and avoid having 2 separate servers. I have read about the hybrid model and having django serve static files with react. My Biggest concern is security as I have already setup apache for security and I aware that node.js is somewhat insecure. What would the best approach be. The separate SPA model or the hybrid model. -
Why cannot run open source django projects by intellij IDEA?
I have one django projects in github, I try to run django server, but it says add django module, even I add but just different django server run, why? -
Django model save() method not called when using Model.objects.create()
I have a primary key ID CharField in my model Image, I want to create unique IDs for newly created objects. I try to achieve this by overriding the model's save method: def save(self, *args, **kwargs): if not self.pk: # is created self.id = uuid.uuid4().hex while Image.objects.filter(id=self.id).exists(): self.id = uuid.uuid4().hex The problem is, save() doesn't seem to be called when I create objects with Image.objects.create(), it is only called when I create the object with image=Image(...) and then call image.save(). As a result, the newly created object has no id assigned unless specified, which causes PostgreSQL to throw a non_unique primary key error. How can I make sure that unique IDs are created upon calling Image.objects.create()? Django version: 1.11.3 -
Django REST framework, content negotiation
I am trying to get my endpoint to return a uri-list when asked for that and a json string as default. I am testing this in a unit test looking a bit like: [...] headers = {'Accept': 'text/uri-list'} response = self.client.get('/api/v1/licenses/', headers=headers) [...] I have written a URIListRenderer like this: from rest_framework import renderers class URIListRenderer(renderers.BaseRenderer): media_type = 'text/uri-list' def render(self, data, media_type='None', renderer_context=None): return "\n".join(data).encode() Next I am trying to get my Response in my View to be rendered using my renderer: class RestLicenses(APIView): """ List all licenses, or create a new license """ permission_classes = (IsAuthenticated,) parser_classes = (MultiPartParser,) renderer_classes = (JSONRenderer, URIListRenderer,) def get(self, request, format=None,): models = LicenseModel.objects.all() if len(models) == 0 : return Response('[]',status=204) if request.META.get('headers') is not None : if request.META.get('headers').get('Accept') == 'text/uri-list' : result = []; for m in models : result.append(reverse('downloadLicense', args=[m.pk], request=request)) return Response(result, status=200) serializer = LicenseJSONSerializer(request, models, many=True) serializer.is_valid() return HttpResponse(JSONRenderer().render(serializer.data), content_type='application/json', status=200) But it seems impossible to get it to choose any other renderer than the first one in the list. How do I make it choose my URIListRenderer and not the json one? -
After log out in a django page I get to a page where I can´t log in
When I log out from any page of my application, it redirect me to: "/accounts/login/?next=/" From this page, I can´t log in again. If I try to log i get redirected to: "/accounts/login/" From there I can log right, if I tried to log on in other link, as for example "/accounts/login/example" It also login good and redirect me to the right place. Can someone shed some light about my issue? -
How to get a function to run when an image file is requested from a Django server?
Let's say I'm hosting an image file on my server, at myserver.com/imagefile.jpg How can I get Django to run a function/module when the image file is loaded from outside sources that I have no control on? How could I set the Django so every time imagafile.jpg is requested, an action can be programmed, like sending an e-mail. It is ok if the file extension is different in the URL but it has to serve the image as an image so that outside sources can use it like: <img src="http://myserver.com/imagefile.jpg1"> or <img src="http://myserver.com/images/image1"> -
How do we store session values in a table
i have stored username using session request.session['un'] = username i want to store this username in a table Is there a method to store this value in table? -
How to access Django crispy tag array within JavaScript?
I am working on a Django project. Within one of my apps I want to pass an array of numerical data from my views file to a template. I then want to have access to said data so that I am able to manipulate it within JavaScript. I can successfully send the array to the template as a crispy tag via the render function. Unfortunately, I can only access said tag within the HTML itself but not within JavaScript. views.py: from django.shortcuts import render sample_data = [1,2,3] def home(request): data = { 'message': sample_data } return render(request, 'blog/home.html', data) home.html: {% extends "blog/base.html" %} {% block content %} <body> {{ message|safe }} <!-- can access crispy tag within HTML--> <script> var x = {{ message|safe }} // can not access crispytag within javascript </script> </body> {% endblock content %} I want to be able access the crispy tag array within the templates' JavaScript. What do I need to change to be able to do this ? -
Download some files as one zipped archive
i have some pictures in project root folder and i want to make them available to download dynamically as zip archive. All the pictures have same name but the difference is in sequence number at the end, So i tried to do this def zip_files(name, iterat): temp = tempfile.TemporaryFile() archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) for index in range(iterat): filename = name+"_"+str(index)+".jpg" archive.write(filename) archive.close() wrapper = FileWrapper(temp) response = HttpResponse(wrapper, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=test.zip' response['Content-Length'] = temp.tell() temp.seek(0) return response so i got errors in lines response['Content-Length'] = temp.tell() and temp.seek(0) Operation in closed file. and when i comment those lines, the returned data to the ajax is empty (because this is triggered as an ajax request) -
How to create a Static HTML files server using Django?
Good Day to you , (1) I manage a team where every team member sends out a report in the form of a html page . At the end of the day i'll have to aggregate them and perform some statistics. I want to create an application using which a team member can upload their html stuff into it and it creates a link to it and anyone with the link can view that content. This is similar to Image hosting where a user when uploads an image, the image can be accessed using the imageid/slug/name whatever .. but with HTML file here. (2) I'm skeptical about the link files in the html file. say, there are several css & js files are connected to index.html .. how could they be linked together or how can the links be unbroken if at all these files are uploaded . My major goto is DJango and I want to do it using Django. I do not know how to actually go about it and need your help. any links/code repos/ help sites/ how to do would be so helpful. I'd be very grateful to you. Thanks, before posting this, i've looked at … -
How to properly change Django FileField.upload_to attribute?
I'm trying to rename function used in FileField.upload_to attribute. After I change function name, Django fails on Performing system checks.... And in traceback I see AttributeError: module 'the_app.models' has no attribute 'old_function_name'. Is it possible to change function name/replace function used in upload_to. And if so, how do I properly do it? Am I correct that rewriting content of old migration (applied on live server) is bad practice. -
How do i manage to make a log out option in a webpage that will redirect me to the main home page?
I am trying to make a web application and i want a log out option in one of my template which will redirect to my home page. How should i do it? i have a home page name 'home.html' which have a google sign in option by social o-authentication process and once signed in it will redirect it to another template named 'jumbotron.html'. But if i refresh and try logging it again it directly takes me to that template. So i basically want a log out option on a template 'jumbotron.html' which will redirect me to the home page and have to log in again. how should i do it? Thank you in advance! -
Display models in tablular form in django with a custom dynamic action button
I have a model, which has some few entries as seen here, ID From To Type Length Weight 2 C D Trailer High 23 2 1 A B Open 12-Tyre 22 3 and I was able to display them using this function in my views.py : def suppliertablefun(request): data = ShipperBoardModel.objects.all() return render(request, 'supplierboard/board.html', locals()) and my model is this : models.py class ShipperBoardModel(models.Model): From = models.CharField(max_length=100,null=True) To = models.CharField(max_length=100,null=True) Type = models.CharField(max_length=100,null=True) Length = models.CharField(max_length=100,null=True) Weight = models.CharField(max_length=100,null=True) but I want to add a button in each row upon clicking which a popup opens with a form with prefilled entries from the row and a blank(price) cell and a submit button which will store the data. For Exammple: The fields in popup form of 1st row are as follows: ID 2 From C To D Type High Length 23 Weight 2 Price ____ **Submit** -
why python readline() is skipping some lines in the file
i am building a web application which will analyse the apache log file. When i try to read each line from the log file by using the for loop it skips so many log entries and prints only some of them. am using python 3.7.2 django 2+ and pycharm to build the project this is what i done so far with open('Test.log', "r") as f: for line in f: print(line) f.close() am expecting to get all the log entries from the log file line by line so that i can process further -
Django: How to update model instance using pre_save signal?
I want to create a pre_save signal which will update the already created model instance whenever the sender is updated. I want to do it in pre_save signal. The previous instance of the model will be either deleted and new instance will be created or the previous instance will be updated. My models: class Sales(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True) party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledgersales') sales = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='saleledger') date = models.DateField(default=datetime.date.today,blank=False, null=True) sub_total = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True) class Journal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname') date = models.DateField(default=datetime.date.today) by = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Debitledgers') to = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Creditledgers') debit = models.DecimalField(max_digits=10,decimal_places=2,null=True) credit = models.DecimalField(max_digits=10,decimal_places=2,null=True) My pre_save signal for creation: @receiver(pre_save, sender=Sales) def user_created_sales(sender,instance,*args,**kwargs): if instance.sub_total != None: Journal.objects.update_or_create(user=instance.user,company=instance.company,date=instance.date,by=instance.party_ac,to=instance.sales,debit=instance.sub_total,credit=instance.sub_total) I want to create a signal which will update the Journal instance whenever the sender model or Sales model is update or delete the previous instance or create a new one. Any idea how to perform this? Thank you -
Submitting dynamically created input field in django
am working on a project with Django, i dynamically created an input field and am trying to submit it, but i could not do so, i searched online and i saw that it could be done with formset_factory but when i tried it, i got this error CatName = int(float(request.POST.get('CatName'))) TypeError: float() argument must be a string or a number, not 'NoneType' here is my code the form.html <form action="." method="post" id="PostCat__form">{% csrf_token %} <input type="hidden" name="deyHidden" value="category_hidden"> {% comment %} {{ catForm | crispy }} <input type="hidden" name="deyHidden" value="category_hidden"> {% endcomment %} <input type="text" class="form-control" name="CatName[]" > <input type="text" class="form-control" name="CatName[]" > <input type="text" class="form-control" name="CatName[]" > <input type="text" class="form-control" name="CatName[]" > <div class="form-group"> <h6 id="PostCat__show"></h6> <img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostCat__img"> <button class="btn btn-outline-info" type="submit" id="PostCat__submit">Create</button> </div> </form> the model.py class Category(models.Model): CatName = models.CharField(max_length=100) the view.py myFormCat = CatPostForm(request.POST) CatName = int(float(request.POST.get('CatName'))) # print(CatName) formset = formset_factory(FormsetForm, CatName=CatName)(request.POST) if myFormCat.is_valid() and formset.is_valid(): for form_c in formset: if not form_c.cleaned_data['CatName']: Category.objects.get_or_create(CatName=CatName) response_data = { 'SType': 'success', 'message': "Saved Successfully" } return HttpResponse(json.dumps(response_data), content_type="application/json") the forms.py class CatPostForm(forms.ModelForm): class Meta: model=Category fields = ['CatName'] pls how can i do it so that i can successfully submit the … -
Why is this returning a ValueError (unpacking tuple)
I'm trying to randomize a list of tuples, and when I try to unpack the tuple's values, it returns a ValueError: too many values to unpack (expected 2). The only problem is, my tuples only have two values. Please help! The problem code: captcha =captcha_array.pop(random.randrange(len(captcha_array))) for (a,b) in captcha: return a -
Css file not linking with project in django
I want to link css file with my django project. I've tried various methods but its not reflecting any changes in html page. I'm new to this, any help will be appreciated. This my html code : {% extends 'base.html' %} {% load static %} <link rel="stylesheet" href="{% static 'css/custom.css'%}" type="text/css"> {% block content %} <form class="form-signin"> <div class="text-center mb-4"> {% csrf_token %} <ul>{{shipper_data_object.first_name}}</ul> <ul>{{shipper_data_object.last_name}}</ul> <div class="checkbox mb-3"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> {% endblock %} <p class="mt-5 mb-3 text-muted text-center">© 2017-2019</p> </div> </form> This is my views.py: def shipper_login(request): shipper_data_object = shipper_form(request.POST) if request.method == "POST" and shipper_data_object.is_valid(): shipper_data_object.shipper_ID = shipper_data_object.cleaned_data['shipper_ID'] shipper_data_object.last_name = shipper_data_object.cleaned_data['last_name'] shipper_data_object.first_name = shipper_data_object.cleaned_data['first_name'] shipper_data_object.contact = shipper_data_object.cleaned_data['contact'] shipper_data_object.comapany_name = shipper_data_object.cleaned_data['comapany_name'] shipper_data_object.gst_pin_or_pan = shipper_data_object.cleaned_data['gst_pin_or_pan'] shipper_data_object.origin = shipper_data_object.cleaned_data['origin'] shipper_data_object.destinations = shipper_data_object.cleaned_data['destinations'] shipper_data_object.save() shipper_data_object = shipper_form() # supplier_data_object = auction.suppliers.views.suppliers_form # if supplier_data_object.operational_cities == shipper_data_object.origin or supplier_data_object.operatioal_cities == shipper_data_object.destinations: # return HttpResponse("found match!!") # else: # return HttpResponse("match not found!!") return render(request, 'shipper_details.html', {'shipper_data_object': shipper_data_object}) This is my base.html: {% load static %} <link rel="stylesheet" href="{% static 'css/custom.css'%}" type="text/css"> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" <meta charset="UTF-8"> <title>Title</title> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" … -
Django template does not return list of objects from model
guys, I have a problem with my Django projects. I want the template to get objects from the database and list them, but the template does not return objects. I will place my project scripts below. This is my models file: class Dog(models.Model): breed = models.CharField(max_length=100) name = models.CharField(max_length=100) age = models.FloatField(default=0.5) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.breed This is my views file: def dog(request): context = { "dog_list": Dog.objects.all() } return render(request, 'dog.html', context) This is my html file: <!DOCTYPE html> <html> <head> <title> Welcome to Dog sharing platform</title> </head> <body> <h2> Dog types </h2> <div> <ul> {% for x in dog_list %} <li>{{x.dog_list}}</li> {% endfor %} </ul> </div> </body> </html> When I run server, This page returns a page that shows Dog types and a blank list Thanks beforehand -
Iam Using Django-Filter for dynamic search option but i couldn't able to render the filter form
here I'm filtering the 'rawitem' using django filter but in my template I'm not able to render the form what wrong I'm doing models.py class Purchase(models.Model): rawitem=models.ForeignKey(Rawitem, on_delete=models.CASCADE) quantity=models.PositiveIntegerField(blank=True) date=models.DateTimeField(default=timezone.now) supplier=models.ForeignKey(Supplier, on_delete=models.CASCADE) total=models.PositiveIntegerField(editable=False) receives=models.BooleanField(default=False) counts=models.PositiveIntegerField(null=True, blank=True) sgst=models.FloatField(null=True, blank=True, editable=False) grand_total=models.PositiveIntegerField(editable=False) filters.py from material_transaction.models import Purchase import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = Purchase fields = ['rawitem'] views.py from django.shortcuts import render from material_transaction.models import Purchase import datetime from .filters import UserFilter # Create your views here. def report(request): return render(request,'report/report.html') def purchase_report(request): user_list = Purchase.objects.all() purchase_report = UserFilter(request.GET, queryset=user_list) return render(request, 'report/purchase_report.html', {'purchase_report':purchase_report}) urls.py from django.urls import path from .import views urlpatterns = [ path('',views.report, name='report'), path('purchase_report',views.purchase_report, name='purchase_report'), ] and my template <form method="get"> {% csrf_token %} {{ filter.form.as_p }} <button type="submit">Search</button> </form> this are my installed things Django==2.1.5 django-crispy-forms==1.7.2 django-filter==2.1.0 pytz==2018.9 -
Google People API not fetching contacts
Im using Google People API on my website to access contacts of the users. The website is in Django. Im able to get access to contacts of users on localhost. But Im not able to get access to the contacts while on production mode with my domain connected to the site. Ive verified domain, and the login part is working smoothly but the issue is with accessing contacts. Why Im I not able to use PEOPLE API during production? -
Run Django App only from __pycache__ and delete actuall source code
my Django up runs in a quite unsave envirnoment and i want to protect it from source-code manipulation. The only "proper" way i was able to find is to compile the source code as .py to .pyc like this: import compileall compileall.compile_dir(".", force=1) But if i do so and afterwards delete all .py files and restart the docker container and also the python runserver restarts, my app is not able to start anymore because the app expects the views.py, urls.py etc. is there any way to tell django that it should always and only run from pycache then i could simply pre-prosess the compilation and later on delete the uncompiled/unprotected source from within the docker container on build-up. regards -
User login and Django OTP
I want the user to login using three fields, username, password and OTP ONLY. Here is my .html file {% extends "base.html" %} {% load static %} {% load bootstrap4 %} {% block head %} <title>HomePage</title> {% endblock %} {% block content %} <div class="container"> <div style='width:500px;margin:0 auto;' class="panel panel-default"> <div class="panel-body"> <h1>Login</h1> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Login</button> {% endbuttons %} </form> </div> </div> </div> {% endblock %} Here is the browser view of the .html file I want to remove Otp Device and Otp Challenge as they are unnecessary for my case. Here is my models.py file from django.contrib.auth.models import AbstractUser class ProjectUser(AbstractUser): # add additional fields in here def __str__(self): return self.email Here is my urls.py file urlpatterns = [ path('user_login/', LoginView.as_view(template_name="accounts_app/user_login.html", authentication_form=OTPAuthenticationForm), name='user_login'), ] And my admin page from accounts_app.models import ProjectUser # Register your models here. admin.site.register(ProjectUser) Here is the reference I used -
How to return arrayfield in django model?
This is my models.py class Product(models.Model): product = ArrayField(ArrayField(models.CharField(max_length=200), blank=True)) def __str__(self): return self.product But i'm getting error like : TypeError at /admin/ordering/product/add/ str returned non-string (type list)