Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Counter of CheckBox - Django - Django-tables2
First, i am not well skilled in web-languages like JS... I would make a JS like counter of checkbox in my django-tables2 table. I look few tips but in my case i have a select all available on header column and i dont succefull deal with it :/ tables.py class GeneralTable(SOMES_TABLES): """ GeneralTable Class """ s = tables.CheckBoxColumn(accessor="id", attrs={"th__input": {"onclick": "toggle(this)"}}, orderable=False) column_default_show = ['s', ..............] class Meta: """ Meta Class """ attrs = {'class': 'table table-sm table-hover table-bordered table-striped table-condensed'} sequence = ('s', ..............) view.html {% block table%} <div class="row" style=" white-space: nowrap;"> {% load django_tables2 %} {% render_table table %} <br/> </div> {% endblock %} <script language="JavaScript"> function toggle(source) { checkboxes = document.getElementsByName('s'); for(var i in checkboxes) checkboxes[i].checked = source.checked; } </script> table in html format <table class="table table-sm table-hover table-bordered table-striped table-condensed"> <thead > <tr> <th class="s"> <input type="checkbox" onclick="toggle(this)"/> </th> <th class="asc orderable test_a"> Test_A </th> ....... </tr> </thead> <tbody > <tr class="even"> <td class="s"><input type="checkbox" name="s" value="1"/></td> <td class="test_a"> AAAAAAAAAAAAA </td> ....... ....... </tr> ....... ....... </tbody > </table> I don't put here some trash-tests that i made for resolve this problem... -
How to filter list of dictionaries with another list of dictionaries
I want to filter through list of dictionaries with another list of dictionaries in Python and Django. I have a list of filters as follows: filters = [{'type': 'make', 'value': 'SEAT'}, {'type': 'model', 'value': 'Acura'}] And I have a list of vehicles as follows: vehicles = [ {'make': 'Audi', 'model': 'A3', 'transmission': 'Manual'}, {'make': 'Audi', 'model': 'A1', 'transmission': 'Automatic'}, {'make': 'Seat', 'model': 'Acura', 'transmission': 'Manual'}, {'make': 'Seat', 'model': 'LEON', 'transmission': 'Manual'}, {'make': 'Skoda', 'model': 'Octavia', 'transmission': 'Manual'}, ] I want to get all vehicles with make Seat and model Acura. Thus the result that I want is: [ {'make': 'Seat', 'model': 'Acura', 'transmission': 'Manual'} ] I tried something as follows: def filter_item(vehicle, filters): for fil in filters: key = fil['type'] value = fil['value'] if key == 'make': if vehicle.make == value: continue elif key == 'model': if vehicle.model == value: continue else: return False return True vehicles = list(filter(lambda vehicle: filter_item(vehicle, filters), vehicles)) But that gives me all vehicles. Any idea? -
Graphene Returning NoneType Error on Subscription
I'm trying to setup subscription on graphene-django and channels using channels_graphql_ws. I'm getting the following error when trying to run my subscription query: An error occurred while resolving field Subscription.onNewComment Traceback (most recent call last): File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/graphql/execution/executor.py", line 450, in resolve_or_error return executor.execute(resolve_fn, source, info, **args) File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/graphql/execution/executors/sync.py", line 16, in execute return fn(*args, **kwargs) File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/channels_graphql_ws/subscription.py", line 371, in _subscribe register_subscription = root.register_subscription AttributeError: 'NoneType' object has no attribute 'register_subscription' Here is what I have in my setup: # /subscription.py/ class OnNewComment(channels_graphql_ws.Subscription): comment = Field(types.UserCommentNode) class Arguments: content_type = String(required=False) def subscribe(root, info, content_type): return [content_type] if content_type is not None else None def publish(self, info, content_type=None): new_comment_content_type = self["content_type"] new_comment = self["comment"] return OnNewComment( content_type=content_type, comment=new_comment ) @classmethod def new_comment(cls, content_type, comment): cls.broadcast( # group=content_type, payload={"comment": comment}, ) I'm not sure if this is a bug or if I'm missing something. -
Update and Delete method in same serializer Django Rest Framework
I was working on a project where I have a requirement like this. consider the below is the array of objects, which will be passed from the client-side. [ { id: 1, title: "some title", body: "some body", status: "In progress" }, { id: 2, title: "some title", body: "some body", status: "In progress" }, { id: 3, title: "some title", body: "some body", status: "Completed" }, { id: 4, title: "some title", body: "some body", status: "In progress" }, { id: 5, title: "some title", body: "some body", status: "Completed" }, ] So after successfully validating the data, this array of objects and the instance will be passed to the serializer update method. So in the update serializer method what I want to do is. Delete the objects which have the status completed from the current model and move it to another model for example Completed model which has all the data of completed data. And update the values to the current instance of the model which have the status in progress. So while returning instance back from the update method how I want to return it like below. [ { deleted_obj:[ { id: 3, title: "some title", body: … -
How to map custom DRF view to multiple urls?
I have an API view like this: class FollowersView(ListAPIView, RetrieveAPIView): serializer_class = FollowerSerializer queryset = Follower.objects.all() How can I make it work with different URLs with each action - list and retrieve? urlpatterns = [ path('followers/', FollowersView.as_view(), name='followers'), #all requests are captured here path('followers/<int:id>/', FollowersView.as_view(), name='followers-detail'), ] By now each request is catched by list action. -
How to call a “modal” from class within views.py in Django?
I have a page with a form that is used to track entry/leave times. Currently, entries with errors (missing enter or exit) get flagged from views.py. I created a modal based on some templates I was given, but I have no idea how to call it from views.py. Basically, after a submission gets flagged with an 'N', the modal would need to appear, asking the user to give a value. Right now the modal just says "Hi" because I'm trying to get it to appear first, before diving into the functionality of it. Below is my views.py, with a comment of where the modal call would need to happen. I’m not sure how to render it within the logic in this part. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) # If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N' if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).count() > 1: first = EmployeeWorkAreaLog.objects.filter(employee_number=emp_num, time_out__isnull=True).order_by('-time_in').first() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(time_out__isnull=True))).exclude(pk=first.pk).update(time_exceptions='N') # Here's … -
Difference between generic views and model mixins
im new to django rest framework. Can someone guide me when to use 'mixins.CreateModelMixin' instead of 'generics.CreateAPIView'. -
how can I connect the string as html in python?
what I try to do is to connect the string like : <img class="img-polaroid" src= "{% static 'pictures/picture{{forloop.counter0}}.jpg'%}" alt="店铺名称" /> the following is the codes : {% for shop in shops %} <div class="col-xs-6 col-lg-3 shop"> <p > pictures/picture{{forloop.counter0}}.jpeg</p> <div class="thumbnails shop_icon"> <img class="img-polaroid" src= "{% static 'pictures/picture{{forloop.counter0}}.jpg'%}" alt="店铺名称" /> </div> <div class="shop_desc"> <h4><a href='/shop/{{shop.id}}'>{{shop.name}}</a></h4> <p>{{shop.shoptype}}</p> <p>miniprice: {{shop.miniprice}} 元</p> <p>amount: {{0}}</p> </div> </div><!-- one shop --> -
Django + JQuery - Interactive Gantt Chart
Im working on an interactive gantt chart with django and jquery. I build the table like this: <div class="gantt"> <div class="gantt-labels"> {% for item in items2 %} <tr> <div class="gantt-labels" id="labels"> </div> </tr> {% endfor %} </div> <div class="gantt_timeline"> <div class="table gantt_table" id="myTable"> <thead> <div class="gantt-tr time-bar"> {% for item in items2 %} <div class="gantt-td chart-values">{{ item.y|date:"D" }}</div> {% endfor %} </div> </thead> <tbody> {% include "datamodel3.html" %} {% for item in items2 %} <div class="tr gantt-tr rows" id="row{{ forloop.counter }}" > {% for item in items2 %} <div class="td gantt-td"> </div> {% endfor %} </div> {% endfor %} </tbody> </div> </div> </div> The queryset "items2" holds the data for the table (amount of rows and cells in dates) Example: row1 01/01/2012 row2 02/01/2012 ... row31 31/01/2012 datamodel3.html Here are the bars: {% for item in items3 %} <div class='bar resizable bars' style="pointer-events:visible;" id="bar{{ forloop.counter }}" data-duration="{{ item.start|date:'D' }}-{{ item.end|date:'D' }}"> <div class='resizers'> <div class='resizer top-left'></div> <div class='resizer top-right'></div> <div class='resizer bottom-left'></div> <div class='resizer bottom-right'></div> </div> </div> {% endfor %} The queryset "items3" holds the data for the bars (name, start- and finish-date) Example: bar1 01/01/2012 10/01/2012 bar2 08/01/2012 14/01/2012 I use this to make the bars draggable: (function() { … -
Django form failed with 'id': This field is required.'
Django supposed to auto increment the field id (and auto create it). I created a model: class SubscribtionData(models.Model): client = models.ForeignKey(Client, on_delete=models.DO_NOTHING, null=True) more_to_sheep = models.PositiveIntegerField(blank=True) shipping_comments = models.TextField(blank=True) history = HistoricalRecords() This is it's form: class AddSubscriptionData(forms.ModelForm): class Meta: model = SubscribtionData fields = ('more_to_sheep', 'shipping_comments',) widgets = { 'more_to_sheep': forms.NumberInput(attrs={'class':'form-control', 'placeholder': 'How Manny Need To Be Sheeped'}), 'shipping_comments': forms.Textarea(attrs={'class':'form-control', 'placeholder': 'Commant For Sheepment'}), } And I have some very wired problems with it... I have multiple forms and formsets in the same page, so I have to use prefix on every form. When I use AddSubscriptionData directly, I can't submit anything (it's recognize AddSubscriptionData as Client (even so the prefix is different) and because they have different fields the .save() return None... Only if I use this form as a formset like this: FormsetAddSubscriptionData = inlineformset_factory(Client, SubscribtionData,form=AddSubscriptionData, extra=1, max_num=1, fields=('more_to_sheep', 'shipping_comments',), can_delete=True) It's wort (partially)... In the creation of a new Client it's recognize the form as AddSubscriptionData object and save it, but for some unknown reason it left the field id (auto generated and supposed to be auto incremented) as None. This problem arise when I try to edit this form and Django yell at me: [{'id': … -
Django admin change list scrollbar at top and bottom
In my Django changelist there are lots of columns that means there is a scrollbar at the bottom of the list. Is it possible to get a scrollbar to appear at the top so I don't need to scroll down Thanks Grant -
Create or Update field in Django many-to-many-through model
I want to create_or_update in m-m through model field This is my models.py from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) is_featured = models.BooleanField(default=False) is_active = models.BooleanField(default=False) In my view.py Below code is work perfectly fine person_obj = Person.objects.get(id=1) group_obj = Group.objects.get(id=1) group_obj.add(person_obj, through_defaults={'is_featured': False, 'is_active': True}) Now for same group_obj and person_obj I want to update is_featured = True in membership model How can i do that? I can do it by filtering Membership table and update fields but i guess it is not a good practice. I wanted to do it by better solution. I have tried with same line group_obj.member.add(person_obj, through_defaults={'is_featured': True, 'is_active': True}) but it is not updating that field. -
how to avoid pandas in converting string to date format
i have below code where it checks if the date is in between start and end dates and returns its filename. import pandas as pd def loaddata(): global dict1 dict1 = {} with open('load.csv', mode='r') as f: for z in csv.DictReader(f, skipinitialspace=True): Start_date = pd.to_datetime(z['Start_date']) End_date = pd.to_datetime(z['End_date']) File_type = z['File_type'] File_name = z['File_name'] if File_name not in dict1: dict1[File_name] = {} if File_type not in dict1[File_name]: dict1[File_name][File_type] = (Start_date, End_date) # dict1 gives >> {'file_name': {'type1': (Timestamp('2019-05-06 00:00:00'), Timestamp('2019-12-31 00:00:00'))}, # 'file_name1': {'type2': (Timestamp('2018-05-06 00:00:00'), Timestamp('2018-12-31 00:00:00'))}} def fn(date, filetype): for filename, range in dict1.items(): if filetype in range: start, end = range[filetype] if start <= date <= end: return filename new_date = pd.to_datetime('2019-12-21') print(fn(new_date, 'type1')) # >> returns filename I used pandas for converting the string dates to date format. Is there any way to convert it without pandas ? -
Why does Django return http 200 if form data is invalid?
AFAIK Django uses this way to handle forms: GET: client receives HTML with input elements user fills out the form user submits form: http POST server/Django validates the form. In this case it is invalid server sends HTML containg the same form and an error message to the user. With http status 200. Wouldn't it make more sense to use a different http status code if the data is invalid? -
How to implement callbacks asynchronously in Django?
I am building a web app, using Django, which has two parts: deploy docker containers and store the expiry time in the database, according to the expiry time kill them, however, a user of the app can choose to extend the life of the container. How do I implement the second part without polling on the database? I tried using asyncio and implemented a custom middleware in Django but it blocks the execution. Is there any other way which does the job asynchronously. import asyncio from threading import Thread def callback_func(eventloop): """ check DB if now: kill else: register a new callback with new updated time """ # Logic to kill a container goes here print ("Inside callback") class KillerMiddleware: def __init__(self, get_response): self.get_response = get_response self._eventloop = asyncio.new_event_loop() asyncio.set_event_loop(self._eventloop) self._t = Thread(target=lambda : self._eventloop.run_forever()) self._t.daemon = True self._t.start() def __call__(self, request): response = self.get_response(request) self._eventloop.call_later(86400, callback_func, self._eventloop) return response -
How to create a dataframe from a model (Django)
I am developing an app in Django. I have this model class my_model(models.Model): Field_A = models.CharField(max_length=256, blank=True, null=True) Field_B = models.CharField(max_length=25, blank=True, null=True) Field_C = models.TextField(blank=True, null=True) I want to create a dataframe with columns names equal to model fields names, containing in every row the model objects, and in every column the object fields values. How can I do it? Is there a single command to do it? Or do I have to iterate? -
Unable to import 'django.urls'pylint(import-error)
How to Solve this Problem , My First step to Django Web app development. This is my first error... Iam using VSCode Editor in Windows 10 / 64 bits. -
How to modify the url from which PasswordResetConfirmView tries to GET the ".*/set_password/" page?
I use Nginx which redirects requests with urls starting from 'api/' to my Django app that listens to port 8000. part of my nginx.conf: location ^~ /api/ { include uwsgi_params; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://192.168.99.100:8000/; proxy_read_timeout 900; } Now, I use django.contrib.auth.views for password reset. part of my urls.py file of my "users" app urlpatterns = [ . . . url(r'^reset-password/$', PasswordResetView.as_view(success_url=back_base_url+'users/reset-password/done/', html_email_template_name= 'registration/password_reset_email.html',extra_context={'mode': 'reset'},extra_email_context= {'back_base_url':back_base_url}), name='reset_password'), url(r'^reset-password/done/$', PasswordResetDoneView.as_view(extra_context= {'mode': 'reset'}), name='password_reset_done'), url(r'reset-password/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', PasswordResetConfirmView.as_view(success_url=reverse_lazy('users:password_reset_complete')), name='password_reset_confirm'), url(r'reset-password/complete/$', PasswordResetCompleteView.as_view(), name='password_reset_complete'), . . . ] As you can see, I pass the variable "back_base_url"="http://192.168.99.100/api/" into "success_url" argument of several views because otherwise, "api/" wouldn't be part of the respective url. This process works as expected: PasswordResetView & PasswordResetDoneView user makes a GET request to "http://192.168.99.100/api/users/reset-password/" they get "templates/registration/password_reset_form.html" where: they fill their email address and when submitting it, they get an email of the form of "templates/registration/password_reset_email.html" (after email submission) they get redirected and make a GET request "http://192.168.99.100/api/users/reset-password/done/" where they see "templates/registration/password_reset_done.html" However, this process doesn't work as expected: PasswordResetConfirmView (within the email) user makes a GET request to "http://192.168.99.100/api/users/reset-password/confirm///" by clicking the email activation link Now, I don't know exactly what is happening, … -
NoReverseMatch at / Reverse for 'index' not found. 'index' is not a valid view function or pattern name. in django
Tis is urls.py This is home urls.py this is index.html can't fix this error. Please help me. -
How to insert date and time to DateTimeField in Django after a function in python script gets executed?
I have a Django Template that contains a text which says "None". Besides the text, I want to display the time after a user clicks on a button. Once clicked, a function will be called in the views.py module and calculates the current time. I want to store this time in the DateTimeField in my model and access the value in my Template. How can this be done? This is what I had done so far: models.py: from django.db import models from django.contrib.auth.models import User class Time(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) time = models.DateTimeField(null=True, blank=True) #I didn't use a auto_now = True parameter since I intend to add my own datetime only after a user clicks on the button. code.py (external script): from datetime import datetime def time(): current_time = datetime.now() date_time = current_time.strftime("%d/%m/%Y %H:%M:%S") return date_time Output of the above code: '15/11/2019 16:10:39' views.py: from code import time #accessing the code.py file since it is in root directory def current_time(request): c_time = time() #if the time is not available in DateTimeField(), then create it in the model. if not Path.objects.filter(current_time= c_time).exists(): Path.objects.create(current_time= c_time) else: #If time already exists in model, then grab the user_id and replace the … -
how to use check_password fun to compare plain pass and hash pass while login
I have hash password(using set_password) in my mysql table , i want to compare that hash-password with my plain password using check_password to login successfully. how can i do that.. views.py/login view def logauth(request): if request.method == "POST": email = request.POST['username'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: messages.error(request, 'if part : user is not None') login(request, user) return redirect('emp') else: messages.error(request, 'else part : user is None') return redirect('login_url') else: messages.error(request, 'Please provide valid credentials') return render(request, 'registration/login.html') backends.py class MyBackEnd(object): def authenticate(self, request, email=None, password=None): existing_user = RegAuth.objects.get(email=email,password=password) if not existing_user: # Checking the user Regauth Custom DB. user_data = RegAuth.objects.get(email=email,password=password) if email == user_data.email: user = RegAuth.objects.create_user(email=email, password=password) user.save() return user else: return None else: return existing_user def get_user(self, email): try: return RegAuth.objects.get(email=email) except Exception as e: return False -
Error: Unable to load celery application. The module tasks was not found
I'm trying to get celery up and running on Heroku as per instructions here When I try to run "heroku local" however it fives me the following error: 10:05:42 PM worker.1 | Error: 10:05:42 PM worker.1 | Unable to load celery application. 10:05:42 PM worker.1 | The module tasks was not found. Any help is much appreciated. -
How can i get data from an object using the primary key within another object? (django-friendship)
I am currently implementing django-friendship into my project and have created the ability to view friend requests, current friends, blocked users etc. When a user views current friends, they get a list of users containing each friends full name, profile picture and username from data obtained from the User.objects. Here is an individual friend of a user for example: Using this code: def view_people_friends(request): users = Friend.objects.friends(request.user) args = {'users': users} return render(request, 'accounts/people.html', args) However, when the user goes to view friend requests, they are given a list of users containing only their primary keys and nothing else. Here is an individual friend request for example: Using this code: def view_people_requests(request): users = Friend.objects.requests(request.user) args = {'users': users} return render(request, 'accounts/people.html', args) After comparing the objects after printing both the Friends.objects.friends and Friends.objects.requests into a console i understand that the Friends.objects.requests only stores primary keys For example: [<FriendshipRequest: 35>, <FriendshipRequest: 34>] I would like to make it so that receivers of friend requests can also see the full name, profile picture and username of each user like the first picture by using the primary keys from the Friend.objects.requests to obtain information from User.objects or if there are other alternatives. … -
How to deploy a Celery worker on Google app engine
I have a Celery worker need to deploy to Google app engine, is it possible? I intend to use one app for my main Django app, one app for Celery worker and one Rabbitmq service (it supported by Google cloud) -
Filter MultiSelectField in views.py in django
Product class in models.py class Product(models.Model): category = models.ForeignKey( Category, related_name='products', on_delete=models.CASCADE) gender_choice = ( ('Male', 'Male'), ('Female', 'Female'), ) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) stock = models.IntegerField(default=0, null=False) price = models.DecimalField(max_digits=10, decimal_places=2) gender = MultiSelectField(choices=gender_choice) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) I need to filter the gender. Suppose I go on the landing page, it shows all the products as it is an ecommerce website. There appears a link to 'Male' and 'Female'. If I click Male, it needs to show only the products that belong to male. The gender field is a MultiSelectField. Same goes for female filter. The categories only contain brand names and not male and female. I tried something like this: views.py def product_list2(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True, gender='Male') if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) Notice the line products = Product.objects.filter(available=True, gender='Male') It surely doesn't work. How should I make it to filter the objects …