Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to escape symbols entered in django admin to html representation
I have a model that has a regular text field, that needs to be able to accept user pasted text data into it which may contain scientific symbols, specifically lowercase delta δ. The users will be entering the data through the model admin. I'm using a mysql backend, and the encoding is set to Latin-1. Changing the DB encoding is not an option for me. what i would like to do, for simplicity's sake, is have the admin form scrub the input text, much like sanitation or validation, but to escape the characters such as δ to their HTML representation,so that i can store them in the DB without having to convert to Unicode and then back again. What utilities are available to do this? I've looked at escape() and conditional_escape(), but they do not seem to do what i want them to (not escape the special characters) and the django.utils.encoding.force_text() will encode everything, but my data will render as its Unicode representation if i do that. The site runs on django 1.10 and python 2.7.x any help or thoughts are much appreciated. -
CreateView with ListView in django init form
Im working with sigurdga/django-jquery-file-upload for multiple upload images, so i want to achieve that when the user enter a page, the photos uploaded by him appears in the page so, is there a way no initialize a django CreateView with all the objects displayed like a ListView? I have this createview. class PictureCreateView(CreateView): model = Picture fields = "__all__" template_name = 'fileupload/picture_form.html' # form_class = PictureForm # def get_initial(self): # initial = super(PictureCreateView, self).get_initial() # initial = initial.copy() # files = [serialize(p) for p in self.get_queryset()] # data = {'files': files} # response = JSONResponse(data, mimetype=response_mimetype(self.request)) # response['Content-Disposition'] = 'inline; filename=files.json' # return response def form_valid(self, form): self.object = form.save(commit=False) self.object.usuario_id = self.request.user.id self.object.save() usuario = User.objects.get(id=self.request.user.id) if usuario: photos = Picture.objects.filter(usuario_id=usuario.id) for photo in photos: photo.usuario_id = self.request.user.id photo.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') ListView class PictureListView(ListView): model = Picture template_name = 'fileupload/picture_list.html' Html {% extends "fileupload/upload_base.html" %} {% block content %} <ul> {% for picture in object_list %} <img src="/media/{{ picture.file }}" /> {% endfor %} </ul> {% endblock %} -
Django Filter Not Returning Right Results
I have a view where I am trying to filter a product by category. class ProductListView(ListView): context_object_name = 'products' model = models.Product template_name = "catalogue/catalogue.html" products = Product.objects.all() birdish = Product.objects.filter(category="Biryani Dishes") So I have a category called 'Biryani Dishes'. I get the error ValueError: invalid literal for int() with base 10: 'Biryani Dishes' If I change the query to (name='Chicken Biryani') I get back all the products. (I am expecting just Chicken Biryani). Ideally, I would like to create a generic query that takes in the category as an argument and I can specify the actual name on the HTML template. Any help is really appreciated. -
What are the ways for creating a Django project structure
I have been following Django tutorials. It says I can create projects using the following command: django-admin startproject mysite And then I can create apps using python manage.py startapp polls This gives me a standard project structure. When creating real life websites/portal is this how project structures are? Are there other ways of creating projects? -
What is the most efficient way to count votes on an object?
I want to count votes on model object. I am thinking there are two ways to accomplish this: Approach 1 class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) vote_count = models.IntegerField() And then get the model, update the count, then re-save the model. Or: Approach 2 class Vote(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) votes = models.ManyToManyField(Vote,related_name='questions') In this way I can add to the votes and then count on all votes when I need a summary. Which approach is most efficient from a database cost perspective as well as future scalability? -
rest framework's list_route returns empty
I am using django rest framework. I have a ViewSet similar to as defined below class ModelViewSet(viewsets.ModelViewSet): queryset = Model.objects.all() serializer_class = ModelSerializer @list_route(url_name="custom") def custom(self, request): objects = Model.objects.all() serializer = self.get_serializer(objects) return HttpResponse("{} </br> {}: ".format(objects, serializer)) When I go to the custom url for the list_route I get ,,,,,]> ModelSerializer(,,,,,]>, context = ...) however when I got to the base url, I can see the full list of all my model's objects. I am confused cause it seems to me it should be using the same data. It seems that there are the correct number of objects in the list (based on the number of commas), however the objects are unpopulated. Following the Django rest guide, it suggests to use serializer.data, however since my objects are not there this produces an error. Any ideas? -
Restart celery beat and worker during Django deployment
I am using celery==4.1.0 and django-celery-beat==1.1.0. I am running gunicorn + celery + rabbitmq with Django. This is my config for creating beat and worker celery -A myproject beat -l info -f /var/log/celery/celery.log --detach celery -A myproject worker -l info -f /var/log/celery/celery.log --detach During Django deployment I am doing following: rm -f celerybeat.pid rm -f celeryd.pid celery -A myproject beat -l info -f /var/log/celery/celery.log --detach celery -A myproject worker -l info -f /var/log/celery/celery.log --detach service nginx restart service gunicorn stop sleep 1 service gunicorn start I want to restart both celery beat and worker and it seems that this logic works. But I noticed that celery starts to use more and more memory during deployment and after several deployments I hit 100% memory use. I tried different server setups and it seems that it is not related. -
Render objects using CreateView init, Django
I want to do render all the registers from an object using CreateView, i know how to do it with normal view but not with CreateView. model Picture class Picture(models.Model): usuario = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="pictures_usuario") # session = models.ForeignKey(Session, null=True, blank=True) file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs) view.py from Leankd_app.fileupload.models import Picture def testFormu(request): p = Picture.objects.all() return render(request, 'test/formu.html', {'p': p}) template.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for photos in p %} {{ photos.id }} <br> {{ photos.slug }} <br> {{ photos.file }} {% endfor %} </body> </html> How can achive the same using CreateView? I have this files. CreateView en views.py class PictureCreateView(CreateView): # model = Picture # fields = "all" form_class = PictureForm template_name = 'fileupload/picture_form.html' def get_initial(self): initial = super(PictureCreateView, self).get_initial() initial = initial.copy() p = Picture.objects.all() self.initial = {"p": p} return initial def form_valid(self, form): self.object = form.save(commit=False) self.object.usuario_id = self.request.user.id self.object.save() usuario = User.objects.get(id=self.request.user.id) if usuario: photos = … -
Use external data in Django
How can I list external Json data get from mongodb into Django page? The Json data has table structure. Django is should just read this data not require create, update and delete actions. How can I do this? -
Pass a initial object from CreateView to Django Template
I´m working with 3d party django-jquery-file-upload to upload multiple images, there i have these 2 urls to render de templates url(r'^$', PictureCreateView.as_view(), name='upload-new'), url(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), name='upload-delete'), What i want to do is that when i call PictureCreateView get initialize with the photos from the user, so i need to get all those photos from the createview but when i render it to the template any happen. CreateView class PictureCreateView(CreateView): # model = Picture # fields = "__all__" form_class = PictureForm template_name = 'fileupload/picture_form.html' def get_initial(self): initial = super(PictureCreateView, self).get_initial() initial = initial.copy() p = Picture.objects.filter(usuario_id=3) self.initial = {"p": p} return initial def form_valid(self, form): self.object = form.save(commit=False) self.object.usuario_id = self.request.user.id self.object.save() usuario = User.objects.get(id=self.request.user.id) if usuario: photos = Picture.objects.filter(usuario_id=usuario.id) for photo in photos: photo.usuario_id = self.request.user.id photo.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') class PictureForm(forms.ModelForm): class Meta: model = Picture exclude = ('slug', 'file', 'usuario') def __init__(self, *args, **kwargs): super(PictureForm, self).__init__(*args, **kwargs) picture = Picture.objects.get(usuario_id=3) self.fields['slug'] = picture.slug picture_form.html {% block content %} {{ form }} {%endblock %} i know im not using the self.initial = {"p": p} in … -
Every time I logout & log back in a new cart is created, Django Cart App
I'm new to Django! I'm trying to let unauthenticated user add products to cart. And when the login & refresh the card is associated with user. But the problem is for authenticated users. When authenticated user logs out and logs back in, a new cart is created for him. This is my function, it checks if I need to make a new cart or get the existing one. def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj -
i want to display only selected year data in Django
Here i put my code file so you can get idea about my code In my index.html {% load tag %} <body> <select name="select_year"> <option>2017</option> <option>2018</option> <option>2019</option> <option>2020</option> </select> </br> </br> <table border="1"> <tr> <td>No</td> <td>Name</td> <td>DOB</td> <td>Year</td> </tr> {% for Manvi_User in ordering %} <tr> <td>{{forloop.counter}}</td> <td>{{ Manvi_User.first_name }}</td> <td>{{ Manvi_User.dob}}</td> <td>{{year|calculate_year:forloop.counter0}}</td> </tr> {% endfor %} </table> </body> in vies.py def index(request): all_user = Manvi_User.objects.all() ordering = all_user.order_by('dob') return render(request, 'index.html', {'ordering': ordering}) in tag.py @register.filter def calculate_year(year, loop_counter): try: year = int(2017) except ValueError: return None else: return str(year + (loop_counter // 2)) in year i put static year using tag.py if user select 2019 i want to display only data who have year 2019 -
How to filter based on a nested Django JSONField
I have a json field for a model in my Django app that typically has nested json in it. I read that to filter on a JSONfield, you would use contains on the filter for whatever value you are looking for, but I'm not getting any results back even though I know the value does exist in the JSONField. Is there an extra step I need to use for nested json in a json field ? JSON Field "Field name is Content " "content": { "documents": [ { "id": "378", "name": "Test.pdf", "mediaFile": "http://localhost:8000/media/file.pdf" } ] } Query document_modules = WMDocumentModule.objects.filter(content__documents__contains={'id': "378"}) >>> document_modules: <QuerySet []> -
InMemoryUploadFile processing
I have a question about Django InMemoryUploadedFile processing. I tried to upload a simple csv file whose content is as below username,name user1,user1 I use the snippet below to get the file data and save it locally (Django REST framework) def put(self, request, filename, format=None): file_obj = request.data['file'] path = default_storage.save('demo.csv',ContentFile(file_obj.read())) However, the result file has content: ------WebKitFormBoundaryJaXsjE9oec2QW6jz Content-Disposition: form-data; name="demo.csv"; filename="demo.csv" Content-Type: text/csv username,user user1,user ------WebKitFormBoundaryJaXsjE9oec2QW6jz-- Is there any way that I can retrieve the csv file data only without the header and footer above? My purpose is to read the csv file, is there a way to read data directly without saving first? Thank you. -
Django Python Setting up models for multiple databases with lots of tables
I have been trying to setup a Django webapp that monitors a bunch of information and spits it out onto a webpage. I currently have 2 PostgreSQL databases connected to this Django project. The first one is the default one, that mainly just stores users and other information from the Django website. The second database was around before I started developing the Django website and is currently being run on a separate server, which feeds data into it every minute or so. The second database has quite a bit of tables in it, around 1200. They all have the same data fields for information, and are identical except for the data stored in them and their name. I just got into Django and I was wondering how I would go about setting up my models and views page for this. I was able to find this page : https://docs.djangoproject.com/en/2.0/topics/db/multi-db/ Which provided a lot of useful and helpful information but did not answer my question. I am confused about how I would go about setting up the models.py for an app for all these tables, and then accessing it from the views.py to display the data. I understand that I have … -
django-admin parler style tabs in custom template
I've successfully install and translate via admin interface. Now want to make custom template like below What I've done: forms.py class ClassForm(TranslatableModelForm): class Meta: model = Category fields = ('name',) views.py def tran(request): if request.method == 'POST': form = forms.ClassForm(request.POST) if form.is_valid(): form.save() return redirect('tran') else: form = forms.ClassForm() context = { 'form':form, } return render(request,'tran.html',context) tran.html <form method="post"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success" type="submit">Save</button> </form> -
Django Template Attributes of QuerySet for ManyToMany with "Through" Class
I've got roughly models like these: class Person(models.Model): ... name = models.CharField(max_length=40) eyes = models.CharField(max_length=12) ... relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people', ...) to_person = models.ForeignKey(Person, related_name='to_people', ...) status = models.CharField(max_length=20) I've got reasonable database entries, and can see them in the Python shell: >>> p1 = Person.objects.get(...) >>> r = Relationship.objects.filter(from_person=p1) <QuerySet [<Relationship: p1 p2 status>], [<Relationship: p1 p99 status>]> >>> r[0].status Friend >>> r[0].from_person.name p1 >>> r[0].from_person.eyes Brown # p1's eye color >>> r[0].to_person.name p2 >>> r[0].to_person.eyes Blue # p2's eye color !!! Now I want to access this same information from my templates, but I don't see what I expect: <p>name={{ person.name }} ({{ person.eyes }})</p> <p>len={{ person.relationships.all|length }}</p> {% for rel in person.relationships.all %} <p> rel[{{ forloop.counter }}]={{ rel.status }} {{ rel.from_person.name }} ({{ rel.from_person.eyes }}) {{ rel.to_person.name }} ({{ rel.to_person.eyes }})</p> {% endfor %} This displays: name=p1 (Brown) len=2 rel[0]= rel[1]= I expect: name=p1 (Brown) len=2 rel[0]=Friend p1 (Brown) p2 (Blue) rel[1]=Enemy p1 (Brown) p99 (Red!) I added accessor methods to the 'Relationship' model, but it didn't make a difference. I messed with using the template "slice" filter. I'm missing something basic... Thanks for your help! -
How do I merge a remote repo with my current existing directory?
I have my Django project in a Bitbucket repo that I want to merge with my newly created Digital Ocean server. The server directory contains a few basic files for a Django project for my server like env, static and manage.py. The Bitbucket repo has all my project apps etc. I've already done git remote add origin https://user@bitbucket.org/user/project.git from the server directory. So I then perform git merge master but it says Already up-to-date.. I've tried git pull master but it says: fatal: 'master' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Any idea what I can try? -
How to optimally invalidate a per-view cache in Django?
I am not using @cache_page decorators instead I am using per-view cache in the URLconf as suggested in the Django documentation (1.11.8). Now, I want to invalidate a key that I use to cache my list view if a new post is created or deleted. I found 2 answers online first, which does not suggest a clean way to do this and second, which is a good way to do this but uses a redundant request to the view. Is there a better way to do this? Moreover, where should I define the signal receiver for post_save and post_delete (either in my url.py or model.py)? Which one is a good practice? -
Django-Filer Pre-existing images
I've uploaded a large amount of image files to filer. I made a new webapp about coins that needs to use those image files. The ticker of the coin will be exactly the same as the name of the image file. Example: Ticker=ASD Image=ASD.png How do I use my model to call a preexisting image or upload a new image if the image was not found. from django.db import models from django.conf import settings # Create your models here. class coin(models.Model): name = models.CharField(blank=False, max_length=64, verbose_name='Coin Name', unique=True, help_text='Please enter coin name') ticker = models.CharField(blank=False, max_length=10, verbose_name='Ticker') icon = models.FileImageField -
Prefetch_related in Django views results in surplus database queries
I have blown my mind trying to figure what I am doing wrong in this code: contacts = Contact.objects.user(request.user).prefetch_related( Prefetch('contact_phone', queryset = ContactPhone.objects.order_by('value'))) for contact in contacts: for contact_phone in contact.contact_phone.all(): # do something Django hits database several times. Any ideas ? -
Django formfield_for_manytomany doesn't work
I have these two models in my models.py file: class Caar(models.Model): car_id = models.AutoField(primary_key=True) model_name = models.CharField(max_length=255) parent = models.CharField(max_length=255) and class Data(models.Model): number = models.IntegerField() observation = models.TextField() car = models.ManyToManyField(Caar) I want to show Caar in admin, using TabularInline. Also, I want to filter ManyToMany field. Everything works fine, except for the filtering. I use, in admin.py file: admin.site.register(Caar) class CaarInline(admin.TabularInline): model = Data.car.through readonly_fields = [ 'caar_model_name', ] def caar_model_name(self, instance): return instance.caar.model_name class DataAdmin(admin.ModelAdmin): inlines = [CaarInline,] exclude = ('car',) change_form_template = 'admin/web/data/change_form.html' def formfield_for_manytomany(self, db_field, request, **kwargs): print('first') if db_field.name == "car": print('second') kwargs["queryset"] = Caar.objects.filter(car_id=231) return super().formfield_for_manytomany(db_field, request, **kwargs) def add_view(self, request, form_url='', extra_context=None): extra_context = extra_context or {} # some truncated code. ignore it if request.method == 'GET' and 'value' in request.GET: value = request.GET.get('value'); extra_context['value'] = value else: extra_context['value'] = ''; return super(DataAdmin, self).add_view(request, form_url, extra_context=extra_context,) admin.site.register(Data, DataAdmin) When I load the page in admin I can't see first and neither second printing. What am I doing wrong? Thanks. -
How to link to local file download in HTML?
I'm using this tag: <a href:"{{ arquivo.caminho }}" download>link</a> With the download atribute to make a download link files from my local network (tiff images) but the downloaded file is a .tiff file containing the HTML code of my page. I noticed that the link returned from my page is prefixed by address of my django: http://127.0.0.1:8000/172.23.5.17/Imagens/etc... My HTML code: <tr> <td id="td_result"><p class="resultados_p">{{ resultado.nome }}</p></td> <td> <a href="{{resultado.download}}" download> <div class="download"></div> </a> </td> </tr> Value of resultado.download: \\172.23.5.17\Imagens\landsat\IMAGENS_LANDSAT_8_2017\Processadas\003_068l8_oli_002065_20140803_b654_fuseo_sirgas2000_utm.tiff (I already tried changing the bars) Link returned by page: http://127.0.0.1:8000/172.23.5.17/Imagens/landsat/IMAGENS_LANDSAT_8_2017/Processadas/003_068l8_oli_002065_20140803_b654_fuseo_sirgas2000_utm.tiff -
How to save form without validation
I want that my users can fill a post form partially, save as draft and then edit, finish and publish it. So the draft can have some required (text) fields empty. However I want the fields secure to store in the database (so, no special character, etc). What's the best (or a good way) way to do this? I think these solutions: 1) make two different models, one with required=False fields or 2) fill the empty text field with a temporary string ('draft'), then delete it e redraw as needed while edit, publish, save the draft. Or 3) deactivate the validation (novalidation, I'm not sure this works). or what else? I'm looking to the second way because the first I think will give me problems to manage two models and the third maybe is not secure. PS I'm using ajax to call the views. -
use .liquid template as django template
I am making an e-commerce site with Django oscar. I bought a template but later found that it was a template for Shopify and all the files were in a .liquid format which is a ruby on rails templating library. Is there any way to convert liquid templates into Django templates? If not, is there any alternative? I changed the format to .html and used it as Django template but the Tags didn't load correctly. I tried this answer but it will take a lot of time if I just keep on changing everything. I also saw this library in GitHub but could not figure out how to use it. Any suggestion is highly appreciated. I have already spent money on this this template and don't want to waste more time and money on another template. Thanks in advance.