Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DeleteView without slug and via POST
Hello I want to delete an object in a model but I don't want to show the id in the slug, so I realized I can send the data via a hidden tag in a form. Template <form action="{% url "delete_url" %}" method="post"> {% csrf_token %} <input type="hiden" name="pk" value={{ model.pk }}> <button type="submit">Delete</button> </form> Url. Check I don't want slug path("delete_view", views.delete_view.as_view(), name="delete_url") View class delete_view(DeleteView): model=ModelName success_url = reverse_lazy("success_url") -
How to use handle 404 error with react-router on django projects
I am currently build a django-react web apps, i wondering how do i handle my 404 error on react-router and not with django side, this is my code which 404 error will be routed on django server side... urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^api/', include(urls)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) routes = getattr(settings, 'REACT_ROUTES', []) # urlpatterns += [url(r'^', TemplateView.as_view(template_name='index.html'))] urlpatterns += [url(r'^(%s)?$' % '|'.join(routes),TemplateView.as_view(template_name='index.html'))] -
With drf-yasg, how can I support multiple serializers in the Response?
With a response from my drf just containing the data given by a single serializer, we can implement it as: @swagger_auto_schema( operation_id='ID example', operation_description="Description example.", responses={status.HTTP_200_OK: Serializer4ModelA(many=True)}, ) Which works fantastic, but with some requests constructing a dictionary, where two or three of the keys correspond to different serializers, e.g. response = { "a": serializer_data_for_model_a, "b": serializer_data_for_model_b, "c": serializer_data_for_model_c } How can we describe that in the auto schema? I've tried a few different approaches, mostly similar to the following: @swagger_auto_schema( operation_id='ID example', operation_description="Description example.", responses={status.HTTP_200_OK: openapi.Response( description='response description', schema=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'a': Serializer4ModelA(many=True), 'b': Serializer4ModelB(many=True), 'c': Serializer4ModelC(many=True) }) )} ) But always fails when loading the documentation, with flex saying: "/usr/local/lib/python3.6/site-packages/flex/utils.py", line 125, in get_type_for_value raise ValueError("Unable to identify type of {0}".format(repr(value))) ValueError: Unable to identify type of Serializer4ModelA(many=True): I've read the documentation over and over again, and scoured over github for an example, but I couldn't find an example or anyone doing this. So my question is how to successfully manually define a schema for a response that contains different serializers for different keys in the returned response? -
django many to many relationship query reverse
i have a question with django some relationship where i want to use and i am very confused with that task. i have two tables one table is ball and other table is stadium ,in my problem one stadium maybe to have many balls and one ball maybe to have many stadiums. here my model : class ball(models.Model): code_ball=models.CharField(max_length=150,unique=True) description_ball = models.CharField(max_length=254) made_country_ball= models.CharField(max_length=254) f_ball= models.CharField(max_length=254) rel= models.ManyToManyField(stadium) class stadium(models.Model): code_stadium=models.CharField(max_length=150,unique=True) description_stadium = models.CharField(max_length=254) made_country_stadium= models.CharField(max_length=254) andress_stadium= models.CharField(max_length=254) team_stadium= models.CharField(max_length=254) my question is how to create query views to show that in html templates? for example in some html page need to show all details from table stadium and all or fist code_ball with description_bal from table balls. i don't know hot to do that because i don't have foreign key for table ball to table stadium,with some way i need to reverse relationship to create a new query,any idea how ? -
Django user interacition with other users?
In a Django web app, let's say there is a prediction cast by the user Daniel. In the prediction, there is an accept button, any User can accept this prediction. What I want to know is that if User Andrew accepts the offer, how can I store that in Daniel's prediction class? (If there is an accepted_by field in Daniel's prediction class, how can I change that field to Andrew, the actual User object not just a string, when User Andrew accepts that prediction)? Thanks -
Django: check for exact url in request using regex
I need to check if the url is exactly: http://127.0.0.1:8000/shop/ and based on this render a header. If it is, for example: http://127.0.0.1:8000/shop/stickers/stickers-por-hoja/medida-y-cantidad Header shouldn't render. I've read you can do something like this: {% if "/shop/$" in request.path %} {% include 'header.html' %} {% endif %} But this doesn't work. On the other hand this works, but is not what I need: {% if "/shop/" in request.path %} {% include 'header.html' %} {% endif %} So, Can I use regex in the if condition? -
Iterative access for nested objects
Description of the problem The problem is a classical Bill of Materials (BoM) problem; Suppose we have the class BomEntry(object) defined as: class BomEntry: def __init__(self, part, quantity=0, unit="", children=[]): self.part = part self.quantity = quantity self.unit = unit self.children = children part is a django model, and quantity and unit are two of its members. The model has a method get_bom(self) which returns an instance of BomEntry. Asm is the django model keeping track of BoM data in the database def make_bom(self, depth=1): if not self.is_asm: return BomEntry(self, 1, "", []) else: children = list(Asm.objects.filter(parent=self)) children_bom = [BomEntry(obj.child, obj.quantity, obj.unit, []) for obj in children] bom = BomEntry(self, 1, "", children=children_bom) return bom I'm currently including a parameter to decide the depth of the BoM, but I can't wrap my head around how I would use it. I want to be able to traverse the nested objects, ending up with an output similar to this: { 'part': <PartAsm: 100-1822-R1-A>, 'quantity': 1, 'unit': '', 'children': [ { 'part': <PartAsm: 100-1823-R1-A>, 'quantity': 1, 'unit': '', 'children': [] }, { 'part': <PartAsm: 100-1824-R1-A>, 'quantity': 1, 'unit': '', 'children': [ { 'part': <PartAsm: 100-1825-R1-A>, 'quantity': Decimal('1.00'), 'unit': 'g', 'children': [] }, { 'part': … -
Count a Count with Django Aggregation through multiple Many to Many fields
Given a Django model with two M2M fields: class Book(models.Model): name = models.CharField(max_length=300) authors = models.ManyToManyField(Author) publishers = models.ManyToManyField(Publisher) And starting from a queryset of Authors: authors = Author.objects.filter(...) How can I annotate a count of the number of publishers (non-exclusive) the author has.... interacted with? I can get the number of books the author has: authors.objects.annotate(num_books=Count('book')) But what I want is a count of the number of publishers for all books. For example, if the data was like this: Book | Authors | Publishers B1 A1 P1, P2 B2 A2, A1 P1 B2 A2 P1, P2, P3 ... The resulting annotated counts would be: Author | Publishers A1 3 (B1-P1, B1-P2, B2-P1) A2 4 (B2-P1, B3-P1, B3-P2, B3-P3) ... -
How can I use a custom list method and a custom action in a viewset in DRF?
From the code below you can see that I use a modelviewset, a custom list method and a custom action called get_recent_movies. class MoviesViewSet(LoginRequiredMixin, ModelViewSet): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = Movie.objects.all() serializer_class = MovieSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend, rest_framework.filters.SearchFilter, rest_framework.filters.OrderingFilter) filter_class = MovieFilter search_fields = {"title", "genre", "country", "language"} ordering_fields = ("title", "genre", "country", "language", "release_year", "timestamp") def get_queryset(self): queryset = Movie.objects.filter(user=self.request.user).select_related() return queryset def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) # Check for Datatables and server side processing parameters draw = self.request.query_params.get("draw", None) start = self.request.query_params.get("start", None) length = self.request.query_params.get("length", None) if draw and start and length: draw = int(draw) start = int(start) length = int(length) queryset = queryset[start:start+length] serializer = MovieListSerializer(queryset, many=True) result = {"draw": draw, "recordsTotal": total_count, "recordsFiltered": total_count, "data": serializer.data} return Response(result) else: serializer = MovieListSerializer(queryset, many=True) return Response(serializer.data) @action(methods=["get"], detail=False, url_path="recent", url_name="recent") def get_recent_movies(self, request): queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(status=1).order_by("-timestamp")[:12] serializer = MovieListSerializer(queryset, many=True) return Response(serializer.data) The reason for the custom list method is that I use Datatables and server side proecessing so the data have to be formated the correct way. I use the get_recent_movies to get the last 12 movies a user has seen. The issue is that the … -
How to save updater and creator when using inline models in Django admin
I'm trying to use save_formset() function to save updator and creator in Django admin. The way I implemented save_formset() doesn't work properly. It just keeps updating updated_by. Like I used change argument in save_model(), I thought it's gonna be working properly if I do the same way in save_formset(). Did I miss something? class ImageInline(admin.TabularInline): model = Image extra = 0 readonly_fields = ('updated_by', 'created_by', 'updated_at', 'created_at', ) @admin.register(Store) class StoreAdmin(ImportExportModelAdmin, admin.ModelAdmin): form = StoreForm inlines = [ ImageInline, ] ... # For inline models def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) # For deleting for obj in formset.deleted_objects: obj.delete() # For adding for f in formset.forms: obj = f.instance if obj.image or obj.url: if not change: obj.created_by = request.user else: obj.updated_by = request.user obj.save() formset.save() def save_model(self, request, obj, form, change): # adding the entry for the first time if not change: obj.created_by = request.user # updating already existing record else: obj.updated_by = request.user obj.save() -
Fabric rsync: read error: Connection reset by peer (104)
I'm trying to deploy a Python/Django/Mezzanine website to DO using FABRIC. My dev environment is Windows 10 with Ubuntu WSL I've checked the server and /mezzanine/my_cms exists Here is the error is get dup() in/out/err failed rsync: read error: Connection reset by peer (104) rsync error: error in rsync protocol data stream (code 12) at /usr/src/rsync/rsync-3.0.8/io.c(760) [sender=3.0.8] Fatal error: local() encountered an error (return code 12) while executing 'rsync --exclude "*.pyc" --exclude "*.pyo" --exclude "*.db" --exclude ".DS_Store" --exclude ".coverage" --exclude "local_settings.py" --exclude "/static" --exclude "/.git" --exclude "/.hg" -pthrvz --rsh='ssh -p 22 ' /c/WebDev/site_env/my_cms/ saleh_cms@123.456.789.012:/home/saleh_cms/mezzanine/my_cms' Aborting. Disconnecting from 123.456.789.012... done. If I try running rsync manually rsync --exclude "*.pyc" --exclude "*.pyo" --exclude "*.db" --exclude ".DS_Store" --exclude ".coverage" --exclude "local_settings.py" --exclude "/static" --exclude "/.git" --exclude "/.hg" -pthrvz --rsh='ssh -p 22 ' /c/WebDev/site_env/my_cms/ saleh_cms@123.456.789.012:/home/saleh_cms/mezzanine/my_cms' I get the following error The source and destination cannot both be remote. rsync error: syntax or usage error (code 1) at /usr/src/rsync/rsync- 3.0.8/main.c(1148) [Receiver=3.0.8] I hardcoded the path /c/WebDev/site_env/my_cms/ to avoid using the colon which rsync interprets as a remote host If anyone can point me in the right direction it would be greatly appreciated. -
I have an issue with CSS in django heroku app
So I uploaded my django app to heroku. Some of the CSS styles do not display. But it does in development server. What might be the cause? Other styling shows in well. Thanks -
Django - Static files not found when DEBUG = True; all settings are correct according to docs
I have a project-level directory named static which contains various .css, images, and javascript files. My settings file contains: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... DEBUG = True ... INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATICFILE_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] I've printed out BASE_DIR and it points to the correct directory. Yet, when I load my webpage, I receive this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/css/style.css This file exists, and it exists in exactly the location that Django is trying to access. Still, these files aren't found. I'm a bit at my wits end—the documentation has no information outside of what I've already done, and I've searched around for hours. All of the already-answered questions here regard STATICFILE_DIRS. This question, for example, points out that—when DEBUG = True—one doesn't have to run collectstatic and using STATICFILE_DIRS should suffice. -
How do I can extract data from database in a django framework?
I am learning django and I did finished database setup,also the admin section is now capable to take data as input. But my ambition is to show those data or articles in home.html from that sqlite database. Feel free to share your suggestion. Database data: class Article: title description category -
Django and JavaScript: filtering not working paused on exception
I am trying to filter a table by the room name of the records which are in each row. My table rows look like this: <tr data-room="{{ record.room.room_name|lower|field_name_format}}"> So, when the user checks kitchen, rows related to kitchen shows up in the table and not rows related to other rooms. And this is the code in the header of my HTML: {% for room in user_related_rooms %} document.querySelector('#{{room.room_name|lower|field_name_format}}').addEventListener('change',function (evt) { updateTableView("{{room.room_name|lower|field_name_format}}", evt.target.checked); }); {% endfor %} function updateTableView(room_name, bVisible) { var dataSelectorVal = ""; switch (room_name) { {% for room in user_related_rooms %} case "{{room.room_name|lower|field_name_format}}": dataSelectorVal = ".site-table tbody tr[data-room='{{room.room_name|lower|field_name_format}}']"; break; {% endfor %} } $(".site-table tbody tr").has(dataSelectorVal).css('display', bVisible ? "" : "none"); } Here is the code for the filter: <!-- Filters --> <div class="col-md-1"> <h1>Filters</h1> <form> <span> by room:</span> <div class="side-filter-list"> <ul> {% for room in user_related_rooms %} <li class="flex-field"> <input type="checkbox" id="cb_{{room.room_name|lower|field_name_format}}" /> <label for="{{room.room_name}}">{{room.room_name}}</label> </li> {% endfor %} </ul> </div> </form> </div> The browser pauses on the exception. I get error on this line, living_room being the first room in the loop (i.e. the first iteration of the loop): document.querySelector( '#cb_living_room' ).addEventListener('change', function (evt) { It seems the above line returns null whereas when I comment … -
Postgresql View is not found when going through Django
My database setup makes search_path to be my_path only, so SHOW search_path will only show my_path I have a view that exists in public schema in the same db. Let's call is my_view so what I'm doing in the query is SELECT * FROM my_path.some_table a JOIN public.my_view b ON ...... and django always complains about relation "public.my_view" does not exist When I do it manually (directly on postgres, setting search path to only see my_path, and then run the same command), this query works, but going through Django (also tested in django shell, same result) somehow makes it's a different result. My question is why. Does it have to do with the setup? Why would the same (or so I believe) setup work on manual but not django? Also, if I run query to get data from a table instead of a view, it works. Seems like it's a view-specific issue? -
Merging two query sets data in get_context
I have this get_context method: def get_context(self, request): context = super(IndexPage, self).get_context(request) context['my_data'] = MyPage.objects.live() context['my_date'] = MyDate.objects.all().order_by('date') return context I want to use this to list all dates to certain events on the page. I tried a nested for loop in my template to access both my_data and my_date but that wasn't a successful solution. I'm guessing I need to merge these to contexts but I couldn't find any solutions for this... Does any of you know a solution for this? Thanks for your help! -
URL path for objects that may include 'null' objects
I have a URL path defined like this: # Page for a single label. path('labels/<str:label_name>/', views.label, name='label'), However, the 'label' field is optional (blank=True, null=True), so there are inevitably cases where there is no label name. I'm wondering how I can work around this - is there a way to change the definition of 'label' in the models.py file that would do the trick? Some sort of 'if' statement in the def __str__(self): part? This is the 'label' definition: class Label(models.Model): """The label a song was released on.""" name = models.CharField(max_length=100) def __str__(self): """String for representing the model object.""" return self.name -
Django Rest Framework modelviewset - updating fields before create
I have a modelviewset: class ExpenseViewSet(ModelViewSet): permission_classes = [permissions.IsAuthenticated, HasMetis] serializer_class = ExpenseSerializer def get_queryset(self): return Expense.objects.filter(recorded_by=self.request.user) And a serializer: class ExpenseSerializer(serializers.ModelSerializer): class Meta: model = Expense fields = ["flat_id", "flat_group_id", "description", "notes", "amount"] These are the fields that are POSTed to the viewset, but they are not sufficient to populate the object completely, so I need to add some more fields. I've tried overriding the serializer, like so: class ExpenseSerializer(serializers.ModelSerializer): class Meta: model = Expense fields = ["flat_id", "flat_group_id", "description", "notes", "amount"] def create(self, validated_data): expense = Expense.objects.create( flat_id=validated_data["operations_flat"], flat_group_id=validated_data["operations_building"], description=validated_data["description"], notes=validated_data["notes"], amount=validated_data["amount"], recorded_by=self.request.user, ) return expense This, however, is never called (tested by sticking a print statement in the create function - it never runs). Apparently this is because of this question: Django Rest Framework serializer create() doesn't get triggered This explains the issue, but not how to solve my problem. I'm not sure whether I need to override the is_valid function of the serializer, the create function of the serializer, or the create function of the viewset, or something else. -
Django models - is it a good practice to create models that only link two tables?
Let's say that I want to develop a simple todo-list app. This is what the models.py mght look like. PRIORITIES = ["LOW", "MEDIUM", "HIGH", "URGENT"] class User(models.Model): username = models.CharField(max_length = 20) password = models.CharField(max_length = 100) email = models.EmailField() class Task(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) text = models.TextField() dueDate = models.DateField() priority = models.CharField(choices = PRIORITIES, default = "LOW") class UserTask(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) task = models.ForeignKey(Task, on_delete = models.CASCADE) Here, the UserTask model was created only with a view to reducing redundancies in the database. Is it a good practice? I don't think that this is what models should be used for. -
Access AWS Cognito forms Django/Python
I'm trying to display the Cognito login/signup forms in my Django app. After googling for a while, i have not found any answer. I'm using django-warrant python lib. -
Django Convert Normal Queryset to Iterator
I have a Django view: def object_search_list(request): if request.user.get_username() in ['username']: objects = MyModel.objects.filter(some_field='filter value').select_related('another_field').prefetch_related('a_third_field') else: objects = MyModel.objects.filter(some_field='a different filter value').select_related('another_field').prefetch_related('a_third_field') return render(request, 'objects/object_list.html', {'objects':objects}) My backend, SQL Server, has a limitation of 2100 paramaters in a query. Therefore, the prefetch_related is causing an error because it is putting more than 2100 parameters into the IN statement of the SQL Server query. How would I use iterator() (if possible) to replace prefetch_related? I understand that it will look something like this: objects = MyModel.objects.filter(some_field='filter value').select_related('another_field').iterator() for o in objects: #do something But I'm not sure how to directly convert rendering a queryset to a template into rendering an iterated queryset to a template. How would I make that conversion? -
Django and changing server times
Is there any library in Django framework that acts like the Moments.js to change the server time with addition or subtraction! -
how can i using hits(views) conter in django
Django-Hitcount allows you to track the number of hits (views) for a particular object Anyone has a way for knowing the number of visitors to the page I find it difficult to do so Any Help I want a useful lesson -
Upgrading to Wagtail 2.3 and Django 2.1 causes migrations and login to freeze
I upgraded our existing site to Wagtail 2.3 from Wagtail 2.1, everything went smoothly and it works fine. I saw support for Django 2.1 was included, so I upgraded Django - it successfully applied the migrations but froze before script completion. I had to close the terminal window to stop it (cntl-c didn't work). I also could not login to the site - runserver would freeze up the same way. I tried this with Django 2.1, 2.1.1, 2.1.2, 2.1.3, 2.1.4 - all with the same results. I've downgraded to Django 2.0.9 and everything is working fine. I'm not sure if this is a Django bug, a Wagtail bug, or a project bug. There is no output when running migrate or runserver. I did look at my Postgres processes - it looked like it was freezing up while trying to read permissions for a user or something related to the content types. I'm looking for ideas on what else I can check to debug this.