Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exclude a type of post from pagination
I use a model for the posts of my blog that you can see here(Is a my old post). As you can see, in that moldel, I've an option to indicate highlighted post. If I use the code below to implement the pagination on my blog, also the highlighted post is sent in a page different from the first. {% block pagination %} {% if is_paginated %} <div class="pagination px-auto"> <nav aria-label="Page navigation"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link text-center shadow" href="{{ request.path }}?page={{ page_obj.previous_page_number }}">Pagina precedente</a> </li> {% endif %} <li class="page-item disabled"> <p class="page-link text-center shadow">Pagina {{ page_obj.number }} di {{ page_obj.paginator.num_pages }}.</p> </li> {% if page_obj.has_next %} <li class="page-item"> <a class="page-link text-center shadow" href="{{ request.path }}?page={{ page_obj.next_page_number }}">Pagina successiva</a> </li> {% endif %} </ul> </nav> </div> {% endif %} {% endblock %} I would like to exclude all highlighted post from the pagination. Is it possible? Below views.py class ListPost(ListView): model = Blog context_object_name = 'posts' template_name = "blog/list_post.html" paginate_by = 3 -
django manytomany model relationship crashing admin on object create
I have an Event object in my postgres db, and created a new Collection object to group events by theme via a ManyToMany field relationship: class Collection(models.Model): event = models.ManyToManyField('Event', related_name='collections') name = models.CharField(blank=True, max_length=280) slug = AutoSlugField(populate_from='name') image = models.ImageField(upload_to='collection_images/', blank=True) description = models.TextField(blank=True, max_length=1000) theme = models.ManyToManyField('common.Tag', related_name='themes') date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=False) def __str__(self): return self.name def get_absolute_url(self): return reverse('collection', args=[self.slug]) def clean(self): # because of the way db saves M2M relations, collection doesn't have a # type at this time yet, so image inheritance is # called from the signal which is triggered when M2M is created # (that means if an image is later deleted, it won't inherit a new # one when collection is saved) if self.image: validate_hero_image(self.image, 'image') def save(self, *args, **kwargs): try: self.full_clean() except ValidationError as e: log.error('Collection validation error (name = %s): %s' % (self.name, e)) return super(Collection, self).save(*args, **kwargs) in my admin, I'm defining and registering CollectionAdmin like this: class CollectionAdmin(admin.ModelAdmin): model = Collection verbose_name = 'Collection' list_display = ( 'name', ) however, if I go into admin and attempt to create a Collection "GET /admin/app/collection/add/" 200, the request frequently times out and the query load … -
Django Admin - Prepopulate field and set readonly
i want to set a field (current user) in a model automatically when an object gets created or is being updated and make it readonly, so the user can not change it: In order to prepopulate the field: @admin.register(Model) class ModelAdmin(admin.ModelAdmin): list_display = ('field_1', 'user') def get_form(self, request, obj=None, **kwargs): form = super(ModelAdmin, self).get_form(request, obj, **kwargs) form.base_fields['user'].initial = request.user return form This works, but when i then want to make the field readonly using: readonly_fields=('user', ) the app crashed with error: KeyError at /admin/api/model/add/ 'user' Can anybody help me out and explain how i can reach my goal using django admin? thanks! -
Django 2 : CSS inheritance failing in development environment
I am unable to serve a local css file during Django development (version 2.1). I have followed the django documentation here in addition to searching the web, stackoverflow: https://docs.djangoproject.com/en/2.1/howto/static-files/#serving-static-files-during-development. After following those directions I've expected to be able to inherit from my local css file, but my result is no css inheritance whatsoever. My project structure from the tree shell command is as follows (within C:/Users/raine/Documents/Dev/django_practice/MyShop): C:. ├───media │ └───images │ └───20183411 │ └───09 │ └───18 ├───MyShop │ ├───static │ │ └───css │ └───__pycache__ ├───shop │ ├───migrations │ │ └───__pycache__ │ ├───static │ ├───templates │ │ └───shop │ └───__pycache__ └───static └───css Explanation on the many static directories: As part of debug, I tried to create a base.css file in locations which I believe django would look for those files, (root, the app itself) with no success. There is a base.css file in each of the static/css folders. Relevant code from settings.py (I haven't touched default Django 2 staticfile resources in INSTALLED_APPS, MIDDLEWARE) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Relevant code from 'shop/views.py' def ProductListView(request, category_slug = None): ... return render(request, 'shop/product_list.html', context=context) Relevant code from shop/urls.py: import shop.urls as blog_urls from django.conf … -
Python RunServer Django script not starting
Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 307, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/dist-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/init.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/root/triad_realty/triad_realty/init.py", line 1, in from .celery import app as celery_app File "/root/triad_realty/triad_realty/celery.py", line 3, in from celery import Celery ImportError: No module named celery i am getting this error after every runserver command -
How to configure Memcache for Django on Google cloud AppEngine?
In my settings i have: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } and i have installed https://pypi.org/project/python-memcached/ Anything else needed? -
Create a model object using the json where all keys are not model's fields
I have a model as below: class Person(models.Model): name = model.CharField(max_length = 255) mobile = model.IntegerField(null = True) city = model.CharField(max_length = 255) Now i need to create a model object using a json as below: data = { "name" : "John", "age" : 31, "city" : "New York", "mobile" : 1234432156, "address" : "xyz" } In the above json, name, mobile, city are the fields in Person model. I have to create a model object using the above json. I have done like this: Person.objects.create(**data) But it is throwing an error saying 'age' is invalid keyword argument for this function. My understanding is that, it is throwing error since there is no age field in the model. How to create the model instance with such a json where all the keys are not the fields in the model. -
Setting video ads for website and awarding users for watching them
I have an idea to make something but I'm not sure how to implement a way for users to watch ads and get points (or something else) for it. I searched online but I couldn't find what I was looking for. Can somebody who has experience with this sorts of stuff leave some link or tell me some tips. I'm using Django so implementation with it would be great. -
Why are my postgreSQL tables different after identical django migrations?
So I have a Django app running on a local environment and a AWS Elastic Beanstalk instance. I had some migrations issues, so I updated both with the same "reset to initial" migrations file generated using these instructions, part 2. This is not the first time that I have updated the production DB using migrations, but it is the first time something went wrong. The above step was part of my attempt to fix this error, which seems to have worked, but now I have unexplained differences in the two databases. Using dbshell, I inspected the different tables defined by the migrations file. I have three models. One table matches perfectly. Another, profile, has a field "usertype" on the server that is not on the local database. This "usertype" field has not been in the model for a long time, and should never have been in the production database because I took it out well before deployment. Server: select * from grams_profile; id | phone_number | audio_notifications | read_receipts | interactive_gram | font_size | user_id | usertype | email_verified | profanity_filter Local: select * from grams_profile; id | phone_number | audio_notifications | read_receipts | interactive_gram | font_size | user_id | … -
Django Rest Framework PUT request returns 500, but updates data
I'm fairly new to Django REST framework and I've tried to write an API for my mobile application. I'm facing an issue where a PUT request works fine (updates data) apart from the fact it returns response 500 (Internal Server Error). Some guidance towards resolving this would be much appreciated. views.py: @csrf_exempt def category_instance(request, pk): """ Returns Category instance """ try: cat = Category.objects.get(pk=pk) except Category.DoesNotExist: return HttpResponse("Error: category does not exist", status=404) if request.method == 'GET': serializer = CategorySerializer(cat, many=False) return JsonResponse(serializer.data, safe=False) elif request.method == 'PUT': serializer = CategorySerializer(cat, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, 200) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': cat.delete() return HttpResponse(status=204) else: return HttpResponse(status=400) models.py: class Category(models.Model): name = models.CharField(max_length=25, blank=False) class Meta: ordering = ('id',) serializers.py: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') urls.py: urlpatterns = [ path('category/<int:pk>/', views.category_instance) ] I've tried to look for similar issues that other people may have had, but I was unable to construct a solution to my problem. -
How to set context variable of all Django generic views at once?
I will have standard class-based views for CRUD operations that inherit from various generic views like ListView, DetailView and so on. I will be setting all of their context_object_name attribute to the same value. I was wondering if there is a way to do it more pythonic, to not repeat the operations many times in the code, but to be able to change that variable in one place if necessary? ps. what comes to my mind is of course further inheritance, but maybe there is some more django-like way? -
How to pass data to a modal in Django with Ajax?
I´m trying to show detail information of products within a Bootstrap modal in a Django app. I´m taking this topic as reference: Stack Overflow question . The HTML is correctly calling the AJAX function The AJAX function is opening the modal But I don´t seem to get the data needed in the modal or it doesn´t show One thing I don´t understand is why there is no call to the view in the AJAX code. Nor url declaration. Any clue on what I´m doing wrong or any suggestion on how to achieve my abjective? Thanks! HTML - AJAX function call <div class="row"> {% for y in productos %} {% if y.categoria_producto|stringformat:"s" == objetivo %} <button data-id="{{y.id}}" type="button" class="btn btn-warning margin-bottom delete-company" >delete</button> {% endif %} {% endfor %} {% csrf_token %} </div> AJAX code $(document).on('click','.delete-company',function(){ var id = $(this).data('id'); $.ajax({ url:'', type:'POST', data:{ 'id':id, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), }, success:function(data){ $('#modalQuickView .modal-dialog').html($('#modalQuickView .modal-dialog',data)); $('#modalQuickView').modal('show'); }, error:function(){ console.log('error') }, }); }); HTML Modal <div class="modal fade" id="modalQuickView" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <div class="row"> <div class="col-lg-5"> <!--Carousel Wrapper--> <div id="carousel-thumb" class="carousel slide carousel-fade carousel-thumbnails" data-ride="carousel"> <!--Slides--> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img class="d-block w-100" src="{% … -
Add additional url to a model in Django home admin
I have created a custom admin model: class SettlementAdmin(admin.ModelAdmin, ExportCsvMixin): list_display_links = ('player',) def get_urls(self): urls = super().get_urls() my_urls = [ path('list/', self.settlements_list), ] return my_urls + urls def settlements_list(self, request): .... admin.site.register(Settlement, SettlementAdmin) I am not sure how can I include a link to that custom model on the Django home page next to the existing link? -
Is there a way to get data count from queryset
I made a query that goes like this: LLDPE = Inventory.objects.filter(rm_type='LLDPE') Basically, I'm trying to get the quantity per rm_type that is named LLDPE. my models look something like this: class Inventory(models.Model): RM_TYPES = ( ('--', '----------------'), ('LDPE', 'Low-density polyethylene'), ('LLDPE', 'Linear low-density polyethylene'), ('HDPE', 'High-density polyethylene'), ('PP', 'Polypropylene'), ('PET', 'Polyethylene terephthalate') ) item_type = models.CharField('item_type', choices=ITEM_TYPES, max_length=200, default='Not specified', null=True, blank=True) rm_type = models.CharField('rm_type', choices=RM_TYPES, max_length=200, default='Not specified', null=True, blank=True) quantity = models.IntegerField() -
Django 2 : How can I use a template path with user.id without crashing if not logged?
I need to create a profile edit link in my Django Home template. Like this : <a href="{% url 'app:profile' user.id %}">{{ user.displayed_name }}</a> But it crashes when no user is logged... django.urls.exceptions.NoReverseMatch: Reverse for 'profile' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile\/(?P[0-9]+)\/$'] It's bad but I've done an useless path for app:profile without parameter Is there an other way ? Thanks -
How to let users that upload a photo be able to crop it in django
Yes, I've tried django-image-cropping, followed the documentation and I can't for the life of me get it working. One issue might be the {{ form.media }} in the head. But I'm not sure. <html> <head> <title> </title> {# Load CSS and JavaScript #} {% bootstrap_css %} {% load static %} <link rel="stylesheet" type="text/css" media="screen" href="{% static "common/css/main.css" %}" /> {% bootstrap_javascript jquery='full' %} <script src="{% static "common/js/main.js" %}"></script> {% block extrahead %} {% endblock %} this is my head and i override extrahead to add {{form.media}} as per django-image-cropping. I've also modified the form and model (ImageCropView). What am I missing? Thanks -
Django trigram_similar
I've been trying to implement trigram_similar functionality in my Django backend code. I get an error I've followed the instructions on this page https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/lookups/ but to no avail. I have properly installed the dependencies and added the extra files. SOS! -
Docker & Django: Pytest doesn't run
I'm running Docker to load my Django project locally. Pytest works perfectly without Docker, but since I am using Docker, running the command in my container bash brings back lot's of errors. My docker-compose version: '3' services: db: image: postgres ports: - "5432:5432" web: build: . env_file: .env volumes: - .:/code ports: - "8000:8000" depends_on: - db container_name: local My initial thought is that docker doesn't let pytest create the test database. Did you ever had issues with that and can tell me how to fix it? [...] The above exception was the direct cause of the following exception: elf = <django.db.backends.utils.CursorWrapper object at 0x7f612a744be0> sql = 'INSERT INTO "orders_order" ("created", "updated", "balance_transaction", "event_id", "order_reference", "status", "em...", "payment_method") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING "orders_order"."id"' params = (datetime.datetime(2018, 11, 10, 18, 30, 5, 300123, tzinfo=<UTC>), datetime.datetime(2018, 11, 10, 18, 30, 5, 300166, tzinfo=<UTC>), None, None, 'KRtypwtkrT', 'paid', ...) ignored_wrapper_args = (False, {'connection': <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f613923fd68>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7f612a744be0>}) [...] tests/organizers/test_utils.py::ClientCountryTest::test_country_not_detected /code/tests/organizers/test_utils.py:35: DeprecationWarning: callable is None self.assertRaises(GeoIP2Error, country) tests/organizers/test_utils.py::ClientCountryTest::test_empty_meta /code/tests/organizers/test_utils.py:67: DeprecationWarning: callable is None self.assertRaises(GeoIP2Error, country) tests/organizers/test_utils.py::ClientCountryTest::test_no_ip_address /code/tests/organizers/test_utils.py:55: DeprecationWarning: callable is None self.assertRaises(GeoIP2Error, country) -- Docs: https://docs.pytest.org/en/latest/warnings.html … -
many to many field django how to join
I have no previous experience with many to many fields in django. This is the first time I´m using it, so I´m getting a little confused here. So, this is what I have: #models.py class RefereciaCita(models.Model): titulo = models.CharField(max_length=500, null=True, blank=True, help_text='título da pesquisa') link = models.URLField(blank=True, null=True, help_text='link da pesquisa') #pesquisador = models.ForeignKey('AutorPesquisa',null=True, blank=True, #help_text='pesquisadores que participam da pesquisa', on_delete=models.SET_NULL) pesq = models.ManyToManyField('AutoresPesq', related_name='autoresDaPesquisa',through='AutorRef', verbose_name='pesquisador') def __str__(self): return self.titulo class Meta: verbose_name = "Referência bibliográfica" verbose_name_plural = "Referências bibliográficas" class AutoresPesq(models.Model): nome = models.CharField(max_length=500, null=True, blank=True, help_text='nome do pesquisador') link = models.URLField(blank=True, null=True, help_text='link do currículo do pesquisador') pesquisa = models.ManyToManyField('RefereciaCita', through='AutorRef', verbose_name='pesquisador', related_name='pesquisaDoAutor', help_text='pesquisa que o autor participa') def __str__(self): return self.nome class Meta: verbose_name = "Autores Pesquisa" verbose_name_plural = "Autores Pesquisa" class AutorRef(models.Model): pesquisa = models.ForeignKey(RefereciaCita, null=True, related_name='pesquisarn', help_text='pesquisa que o autor participa', on_delete=models.CASCADE) pesquisador = models.ForeignKey(AutoresPesq, null=True, related_name='autorDaPesquisa', help_text='pesquisadores que participam da pesquisa', on_delete=models.CASCADE) def __str__(self): return self.pesquisador.nome + ", " + self.pesquisa.titulo[:190] class Meta: verbose_name = "Autor Pesquisa" verbose_name_plural = "Autor Pesquisa" I need to retrive, from each ReferenciaCita it´s respective(s) AutoresPesq So in the template I would have something like the picture So, I need to get for each 'researchPaper' it´s 'author' But I´m … -
Using forloop.counter for index in array
I'm passing an array called services into my template. I have a forloop in my template that is running over another array. Within this forloop, I want to display the title of each service in the array using the following code, but it doesn't work. {{services.forloop.counter0.title }} {{ services.0.title }} outputs a value, so I thought that I could just replace '0' with 'forloop.counter0', but this doesn't seem to work. Thanks for the help! -
Django multi language model / filter post by languages
There is my simple blog model; class Article(models.Model): author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author") title_en = models.CharField(max_length = 120, verbose_name="Title_En") title_de = models.CharField(max_length = 120, verbose_name="Title_De") category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True) content_en = RichTextField(verbose_name="Content_En") content_de = RichTextField(verbose_name="Content_De") created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date") image = models.ImageField(blank=True, null=True, verbose_name="Add Photo (.jpg .png)") slug = models.SlugField(unique=True, max_length = 130) def __str__(self): return self.title I use url's with language like this; domainname.com/en/ domainname.com/de/ For example, how can I show only the contents that belong to title_de and content_de in the domainname.com/de urls? How can I do filtering with language? Is there an easy solution to this? (I usage django 2.1.2. i try django-modeltranslation or others dont work this django version...) Thanks... -
Create method for foreign key relationships with Django Rest Framework serializers
My models are like this: class FirewallPolicy(models.Model): name = models.CharField(max_length=100, unique=True) team = models.ForeignKey(Team) source_ip = models.ForeignKey(IP) destination_ip = models.ForeignKey(IP) Now, in order to create a new Firewall Policy, there should already be an existing team, source_ip and destination_ip. My payload to create a new Firewall Policy is as follows: {"name": "test-create-policy-911", "team": "avengers", "source_ip": "1.1.1.1", "destination_ip": "2.2.2.2", } My serializer to create a new Firewall Policy is as follows: class FirewallPolicyCreateSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=100) team = serializers.CharField(max_length=100) source_ip = serializers.CharField(max_length=100) destination_ip = serializers.CharField(max_length=100) class Meta: model = Policy fields = ['id', 'name', 'team', 'source_ip', 'destination_ip'] def validate(self, data): try: Team.objects.get(name=data['team']) IP.objects.get(name=data['source_ip']) IP.objects.get(name=data['destination_ip']) except ObjectDoesNotExist: raise serializers.ValidationError("Entities must exist before you can associate it with a Firewall Policy") def create(self, validated_data): team = Team.objects.get(name=validated_data['team']) source_ip = IP.objects.get(name=validated_data['source_ip']) destination_ip = IP.objects.get(name=validated_data['destination_ip']) policy = Policy.objects.create(name=validated_data['name'], team_id=team.id, source_ip_id = source_ip.id, destination_ip_id = destination_ip.id ) return policy I am not sure if this is the right way of adding foreign keys to a model as it seems too much work. Is there something I am missing where the serializer can automatically check all this and add the foreign keys ? -
how to add perisan language to xhtml2pdf library in django
my problem was that when we render the pdf file and the file was created but the main problem was that the Persian that came in a square square -
Saleor Tutorial
I am new to Django and I learned Django now. And I want to create an E-Commerce site using Saleor Framework. Is there any tutorial or complete documents to learn Saleor framework? Thanks. -
Is Token authentication in django authenticates only active users?
In Django rest framework we have the default TokenAuthentication. Does it authenticates only active users from the Users table or all the users irrespective of their state