Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't detect language for the text "Notebook 9 Pro" given from pre_save signal. Django 2.1, Python 3.7
I want to create slug in admin with helping by pre_save signal, but I have next error: Can't detect language for the text "Notebook 9 Pro" given. I know, that can make with prepopulated_fields, but i need method with pre_save signal. Thx. models.py class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail', kwargs={'product_slug': self.slug}) def pre_save_product_slug(sender, instance, *args, **kwargs): if not instance.slug: slug = slugify(translit(str(instance.title), reversed=True)) instance.slug = slug pre_save.connect(pre_save_product_slug, sender=Product) Traceback /media/m0nte-cr1st0/43338d5a-aa90-411c-a6d7-96964c46e415/m0nte-cr1st0/programming/django_projects/djangoshop/ecomapp/models.py in pre_save_product_slug slug = slugify(translit(str(instance.title), reversed=True)) ... ▶ Local vars /media/m0nte-cr1st0/43338d5a-aa90-411c-a6d7-96964c46e415/m0nte-cr1st0/programming/django_projects/myvenv/lib/python3.5/site-packages/transliterate/utils.py in translit language_code = detect_language(value, fail_silently=False) ... ▶ Local vars /media/m0nte-cr1st0/43338d5a-aa90-411c-a6d7-96964c46e415/m0nte-cr1st0/programming/django_projects/myvenv/lib/python3.5/site-packages/transliterate/utils.py in detect_language _("""Can't detect language for the text "%s" given.""") % text ... ▶ Local vars -
Why am I getting TypeError: 'vc' is an invalid keyword argument for this function error?
I don't understand what I am doing wrong here. Here is my Django model: class VMMigrationEvent(models.Model): created = models.DateTimeField(auto_now_add=True) # DateTime because there may be multiple events in a day. dc = models.TextField(max_length=150), # data center destination_host = models.TextField(max_length=150), # host migrated to. message = models.TextField(), # The message from virtual center. updated = models.DateTimeField(auto_now=True) # DateTime because there may be multifple events in a day. user = models.TextField(max_length=150), # The user logged into the virtual center that execute the migration. vc = models.TextField(max_length=150), # virtual center vm = models.ForeignKey(VirtualMachine) # The VirtualMachine record associated with this event. And from the python console I do this: >>> from cm.models import * >>> dc='DCM01N-01' >>> destination_host='auroravm2-1.example.com' >>> message='my hovercraft is full of eels.' >>> user='mister_gumby' >>> vc='vca-001-s.example.com' >>> vm='ads-108' >>> vm_db_obj = VirtualMachine.objects.filter(name=vm).latest('create_date') >>> vmme = VMMigrationEvent.objects.create(dc=dc, destination_host=destination_host, message=message, user=user, vc=vc, vm=vm_db_obj) Traceback (most recent call last): File "<input>", line 1, in <module> File "/apps/man/man/env/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/apps/man/man/env/lib/python2.7/site-packages/django/db/models/query.py", line 392, in create obj = self.model(**kwargs) File "/apps/man/man/env/lib/python2.7/site-packages/django/db/models/base.py", line 573, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'vc' is an invalid keyword argument for this function Why … -
How to insert a form (in a cell) within a d3.js table
I have created a table in d3.js and I want to integrate a form within a cell which allows an user to add a value to the table. To be honest, I have no clue whether or not it is possible to do that using D3.js and if so, how to do this. Many thanks in advance for your help d3.json("{% url "b_up_fd:data_returns" fund %}", function(error, data) { if (error) throw error; var columns = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'YTD']; var table = d3.select('#returns').append('table'); var thead = table.append('thead'); var tbody = table.append('tbody'); // append the header row thead.append('tr') .selectAll('th') .data(columns).enter() .append('th') .text(function (column) { return column; }); // create a row for each object in the data var rows = tbody.selectAll('tr') .data(data) .enter() .append('tr'); // create a cell in each row for each column var cells = rows.selectAll('td') .data(function (row) { return columns.map(function (column) { return {column: column, value: row[column]}; }); }) .enter() .append('td') .style("color", function(d){ return d.value <= 0 ? "red" : "green"}) .on("mouseover", function(){d3.select(this).style("background- color", "#c1c1c1")}) .on("mouseout", function(){d3.select(this).style("background- color", "#f2f2f2")}) .html(function(d){ return typeof(d.value)==="number"? (100*d.value).toFixed(2)+"%":d.value;}) .each(function (d, i) { if (i == 0){ d3.select(this).style("font-weight", "bold") } else if (i== 13) … -
Django: AttributeError: type object 'Data_Point ' has no attribute 'objects'
I am trying to make a migration, but however I am running into an issue. I am getting the error: queryset = Data_Point.objects.all() AttributeError: type object 'Data_Point' has no attribute 'objects' and I am not sure why. I have googled the error, and still can not find a soultion. Could the error lie in the models.py class? Specifically could the issue be with the association with each table and the foreign keys? Here are the follow classes: models.py class System(models.Model): System = models.CharField(max_length=255) def __str__(self): return self.System class Sub_System(models.Model): Sub_System = models.CharField(max_length=255) System = models.ForeignKey(System, on_delete=models.CASCADE) def __str__(self): return self.Sub_System class Data_Name(models.Model): Data_Name = models.CharField(max_length=255) Sub_System = models.ForeignKey(Sub_System, on_delete=models.CASCADE) def __str__(self): return self.Data_Name class Data_Point(models.Model): Captured_Timestamp = models.DateTimeField(auto_now_add=False, blank=True) Inserted_Timestamp = models.DateTimeField(default=datetime.now, blank=True) Data_Value = models.CharField(max_length=4) Data_Name = models.ForeignKey(Data_Name, on_delete=models.CASCADE) def __str__(self): return self.Data_Value views.py class SystemView(viewsets.ModelViewSet): queryset = System.objects.all() serializer_class = SystemSerializer class Sub_SystemView(viewsets.ModelViewSet): queryset = Sub_System.objects.all() serializer_class = Sub_SystemSerializer class Data_NameView(viewsets.ModelViewSet): queryset = Data_Name.objects.all() serializer_class = Data_NameSerializer class Data_PointView(viewsets.ModelViewSet): queryset = Data_Point.objects.all() serializer_class = Data_PointSerializer serializers.py class SystemSerializer(serializers.ModelSerializer): class Meta: model = System fields = ('id', 'System') class Sub_SystemSerializer(serializers.ModelSerializer): class Meta: model = Sub_System fields = ('id', 'Sub_System', 'System') class Data_NameSerializer(serializers.ModelSerializer): class Meta: model = Data_Name fields = … -
How to make try_files with multiple fallbacks work in nginx?
I have nginx running as a proxy for two application servers: daphne and gunicorn And my webApp is an AngularJs Single-Page-Application. So I need to use prerender.io to help bots crawl the website. My nginx file: upstream ex_server{ server unix:/home/webapps/ex/run/gunicorn.sock fail_timeout=0; } upstream channels-backend { server 0.0.0.0:8001; } server { server_name example.com; listen 80; rewrite ^ https://$http_host$request_uri permanent; } server { server_name example.com; listen 443 ssl; ssl_certificate /etc/ssl/_cert_chain.crt; ssl_certificate_key /etc/ssl/_in.key; root /usr/share/nginx/html; server_name _; location / { try_files /$uri @prerender; #try_files /$uri @prerender @proxy_to_main_app; <= I wanted this } location @proxy_to_main_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; # <- proxy_set_header Host $http_host; proxy_redirect off; #proxy_buffering off; try_files $uri @proxy_to_daphne_app; if (!-f $request_filename) { proxy_pass http://ex_server; break; } } location @proxy_to_daphne_app { proxy_pass http://channels-backend; proxy_set_header X-Forwarded-Proto https; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location @prerender { proxy_set_header X-Prerender-Token RMVQxJkVVugDjcPgHakN; set $prerender 0; if ($http_user_agent ~* "googlebot|bingbot|yandex|baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator") { set $prerender 1; } if ($args ~ "_escaped_fragment_") { set $prerender 1; } if ($http_user_agent ~ "Prerender") { set $prerender 0; } if ($uri ~* "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)") { set $prerender 0; } resolver 8.8.8.8; if … -
Creating functional classes in Django that provide deployment pipeline functionality
I am learning Django, so please correct any issues with my way of thinking here. To start, I am using the Django Rest framework and I'm not interested in just creating a list of items, which is all that I can find examples of on the entire Internet... I will have some pretty large functional classes that will POST and GET data to and from a pipeline server (TFS to be specific) and obviously, I'll need to insert this logic into a file within my app, I am not just displaying things from my database here. So, my question is, where does this go within my app? my understanding is that the "Django way" is to keep models thick.. does that mean that all code logic to make requests and interact with the pipeline server should end up in my models.py? It's kinda frustrating that everyone else seems to just be listing furniture or some other sales item from their database. -
How to get some results before submitting the form using Django extra_views?
I want to add some rendering on the place (in the form) preferably without even have to click a button, but a button is also fine. I am trying to get the latex version of the text entered in a textbox. I am using modelForms with Django-extra-views. What I want shouldn't be a hard task but I cannot resolve it. My question is is there any way to do it? Or what is the work around this problem if I am using class-based modelforms (as I will present in my code)? I tried redefining form_valid() method as: def form_valid(self, form): if 'render' in self.request.POST: # Do something elif 'addQ' in self.request.POST: # Do something But it doesn't work for some reason I don't understand. Views.py class QuestionCreateView(LoginRequiredMixin, CreateWithInlinesView): model = Question form_class = questionForm inlines = [QLevelInline, QSubjectInline, QMethodInline] def forms_valid(self, form, inlines): if 'render' in self.request.POST: print("RENDER") elif 'addQ' in self.request.POST: print("ADD QUESTION") form.instance.author = self.request.user self.object = form.save() for inline in inlines: inline.save() return super().form_valid(form) Question_form.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form }} <button class="btn btn-outline-info" type="submit" name="render">Render</button> {% for formset in inlines %} {{ formset }} {% endfor %} </fieldset> <button class="btn btn-outline-info" type="submit" … -
How to use the virtualenv module in godaddy windows server
I need to configure this windows IIS server in godaddy to deploy a django app. Godaddy´s documentation explains that I must access the virtualenv through my local command line. When I try to do so, it seems to be a permissions matter. Does any one of you people have experience on configuring all of the permissions and stuff to get to this point where you can use the virtualenv module from the local command line to deploy a django app in a cloud server? -
How to make two joins using django's ORM
I'm using the django ORM to make a query like this: MyModel.objects.filter(<condition>) This comes out to a query like this: SELECT my_model.* FROM my_model WHERE <condition> If I wanted to join another table, I could do this: MyModel.objects.select_related('other_table').filter(<condition>) which comes out to: SELECT my_model.*, other_table.* FROM my_model JOIN other_table ON my_model.other_table_id = other_table.id What do I do if I need to make two joins? If I do something like MyModel.objects.select_related('other_table', 'one_mode').filter(<condition>) I get an error saying that one_more is not related to my_model. HOWEVER, is one_more IS related to other_table, the ORM does not detect that. Basically I 'm trying to do this: SELECT my_model.*, other_table.* FROM my_model JOIN other_table ON my_model.other_table_id = other_table.id JOIN one_more ON one_mode.id = other_table.one_mode_id How do I do this? -
Ordering of queryset results using regex
I have the following code: class StartNumeric(Func): function = 'REGEXP_MATCHES' template = "(%(function)s(%(expressions)s, '^(\d+)|(\d+$)'))[1]::int" class EndNumeric(Func): function = 'REGEXP_MATCHES' template = ( "%(function)s(%(expressions)s, '^(\w+)([0-9]+)|([0-9]+)|([a-z]+)$')") class MyHistoryTable(tables.Table): ...some fields... def order(self, queryset, is_descending): queryset = queryset.annotate( short_label_numeric=StartNumeric('field__short_label'), short_label_char=EndNumeric('field__short_label') ).order_by(('-' if is_descending else '') + 'field_label_numeric', 'field_label_char', 'field__short_label') return (queryset, True) When I sort by ASC: it's ok and result is 2c 3c 5 7 9 10 11 12 13 14 15 16 17 19 20 21 22 23 24 25 26 27 28 29 30 32c 33c 35c 106 107 147 200c 260 261 262 263 264 265fs 266fs 267c 268c 269c 273c 274c 275c 276c 276c 501 502 503 504 506 507 511 512 520 521 603 604 610 611 623 … S1 S2 S3 S4 S5 S6 S7 S9 S10 S11 S14 S19 But when I sort by DESC: the last part of result is ... S1 S2 S3 S4 S5 S6 S7 S9 S10 S11 S14 S19 How I need to change my EndNumeric regex for getting result like S19 S14 S11 S10 S9 S7 S6 S5 S4 S3 S2 S1 ... 623 611 ... 276c 275c 274c ... 147 107 106 ... 12 11 9 7 5 … -
django threw command line error, now I can't type in the command line
I'm really new to django. I'm creating my first app on Windows 7. I typed python manage.py runserver I got an error telling me after a long stack trace: File "C:\Inetpub\wwwroot\poll_example\poll_example\urls.py", line 26, in <modu le> path('polls/', include('polls.urls')), NameError: name 'path' is not defined Now I can't type in the command window! How do I retrieve my ability to type? -
Django not finding the static files
I am creating django project so root directory doesn't have any static folder i have two static folder in two app admin_panel and project respectively but when i run python manage.py collectstatic its shows file or folder not found: FileNotFoundError: [Errno 2] No such file or directory: '/home/tbosss/Desktop/environment/virtualenv/myproject/static' STATICFILES_DIRS = ( ('admin_panel', os.path.join(BASE_DIR, 'admin_panel', 'static')), ('project', os.path.join(BASE_DIR, 'project', 'static')), ) -
Getting all permissions specific to a model, and listing it in a table
I'm having trouble listing all model-specific permissions in a table. I'm able to pull out permissions through {{ perms.account }} in the html, but it won't filter for permissions specific to the account model. Futhermore i want to list each permission in a html table, with the permissions description, and a checkmark if its granted: Permission1 Desc1 V <!-- Granted --> Permission2 Desc2 X <!-- Not granted --> I have tried for-looping all permissions, and filtering out the ones related to the model account, and then for looping to get the different rows in the table. This, however, just returned a long string of all permissions names. I have also tried: class echo_users_user_permissions(generic.DetailView): model = Account template_name = 'echo/users/echo-users-user-permissions.html' content_type = ContentType.objects.get_for_model(Account) permissions = Permission.objects.filter(content_type=content_type) views.py class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk')), blank=True) role = models.CharField(max_length=50, choices=(('Administrator', 'Administrator'), ('Moderator', 'Moderator'), ('Editor', 'Editor'))) phone_number = models.CharField(max_length=8) birth_date = models.DateField() street_adress = models.CharField(max_length=255) note = models.TextField(blank=True); zip_code = models.CharField(max_length=4) city = models.CharField(max_length=255) def get_absolute_url(self): return reverse('account-detail', kwargs={'pk': self.pk}) class Meta: verbose_name = 'Account meta' verbose_name_plural = 'Accounts meta' permissions = ( ("has_user_hijack_permission", "Allows the user to … -
Django Model form for imagefield() not throwing validation error for non-image files
I know this question has been asked and answered before but can't find a definite answer. I model form works fine for image files but is not throwing a form level validation error for uploading non-image files... probably because is_valid() is returning false. My code is below: eLearning/views.py: from django.contrib.auth import authenticate, login, get_user_model from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import LoginForm, RegisterForm from students.forms import ImageUploadForm from students.models import StudentProfile from students.views import upload_pic User = get_user_model() def register_page(request): register_form = RegisterForm(request.POST or None) photo_upload_form = ImageUploadForm(request.POST, request.FILES) context = { "register_form": register_form, "photo_upload_form": photo_upload_form } if register_form.is_valid(): # print(register_form.cleaned_data) username = register_form.cleaned_data.get("username") first_name = register_form.cleaned_data.get("first_name") last_name = register_form.cleaned_data.get("last_name") email = register_form.cleaned_data.get("email") password = register_form.cleaned_data.get("password") new_user = User.objects.create_user( username, email, password, first_name=first_name, last_name=last_name, ) upload_pic(request, photo_upload_form, username=username) return render(request, "auth/register.html", context) students/views.py: from django import forms from django.contrib.auth import get_user_model from django.http import HttpResponseRedirect from django.shortcuts import render, redirect, HttpResponse from .models import StudentProfile from .forms import ImageUploadForm def upload_pic(request, form, username): print("upload_pic") if request.method == 'POST': print("request method is POST") if form.is_valid(): print("upload_pic form valid") entry = form.save(commit=False) User = get_user_model() user = User.objects.get(username=username) entry.user = user entry.save() students/forms.py: from django import forms … -
Include in "static" also the domain and protocol for loading static file using external sources
I need to load an image from the server in an email. <img src="{% static 'img/brand.png' %}"> doesn't work because the domain is ignored. I get: http:///static/img/brand.png" I can add a direct link, but I prefer to use static, in case I modify the default url/folder. -
How to fix django channels consumers stopping to handle messages send to groups
Sending messages to groups using group_send() suddenly stops working after some time. The handler method of the consumer is not called anymore. Restarting daphne is fixing the issue for some time. Details There is no error showing up anywhere in the logs, just the messages are not getting handled by the consumers anymore. I'm, using the following libraries: aioredis==1.2.0 asgiref==2.3.2 channels-redis==2.3.2 channels==2.1.6 daphne==2.2.4 django==2.1.5 redis==3.0.1 Code # settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": {"hosts": [("localhost", "6379")]}, } } # views.py class ReceiveEventView(APIView): def post(self, request, *args, **kwargs): # payload: {"type": "event_triggered", "group": "warning", "message": "Button pressed"} # or # payload: {"type": "event_triggered", "group": "danger", "message": "Red Button pressed"} payload = json.loads(request.POST.get("payload", "{}")) if (payload.get("type") == "event_triggered"): async_to_sync(channel_layer.group_send)(payload.get("group"), payload) return HttpResponse(status=204) # consumers.py class EventConsumer(WebsocketConsumer): def connect(self): if not self.scope["user"].is_authenticated: return self.accept() for group in get_subscriptions(self.scope["user"]): async_to_sync(self.channel_layer.group_add)(group, self.channel_name) def disconnect(self, close_code): if not self.scope["user"].is_authenticated: return for group in get_subscriptions(self.scope["user"]): async_to_sync(self.channel_layer.group_discard)(group, self.channel_name) def event_triggered(self, event): logger.debug("Consumer::event_triggered()") self.send(text_data=json.dumps(event)) expected and actual results For some time Consumer::event_triggered() appears in the logging, but suddenly stops. Receiving messages from the browser via WebSocket still works. Just the transport from group_send() to the consumers is broken. -
Implement custom components from javascript in Django
My company has provided various custom developed components for web development (buttons, icons etc). The instructions they give for using them is via JavaScript loading CSS files for each element. I have my local Django project setup with STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"),] I tried putting their "loader.js" script as a tag in my Django template, but still can't seem to use their custom elements. I got so desperate to use them that I navigated to each individual components' CSS file and adapted it to regular HTML components (submit button, etc). I'm sure part of the problem is my novice level understanding of all this, but I'd like to think I could figure it out. Apologies if I haven't provided enough details for this to make sense. If any other details are needed I will add them. -
Django template if statement doesn't return what I expected
I want to allow users to edit their own comments. I tried to compare request.user.username to comment.nick, and request.user.get_username. Both of them return expected value(for example comment.nick return 'author' and request.user.username will return 'author', but Edit won't be visible), but 'if' doesn't return True. Everything is working well, the only problem is that if statement in template. {% if request.user.username == comment.nick %} <a href="{% url 'edit_comment' comment.id %}">Edit</a> {% endif %} # models.py class Commentary(models.Model): nick = models.ForeignKey('Profile', on_delete=models.CASCADE, max_length=20) comment = models.TextField(max_length=300) article = models.ForeignKey(Article, on_delete=models.CASCADE) added = models.DateTimeField(auto_now_add=True, blank=True) -
How to Count values of ManyToMany Field?
I am trying to count all the likes in Posts models class Posts(models.Model): user_profile = models.ForeignKey(Profile, on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True, related_name='likes') What I am trying is all_posts = Posts.objects.all() j = all_posts.filter(user_profile=2).values('likes').count() But this approach counts incorrectly when none of the Posts is liked(i.e. none of ManyToMany Field is selected by users) as it also counts {'likes': None} in QuerySet. for e.g When none of post is liked the queryset is <QuerySet [{'likes': None}, {'likes': None}, {'likes': None}, {'likes': None}, {'likes': None}]> and hence I get count as 5, which is not correct. So, is there any way to count only selected values in ManyToMany Field or to exclude {'likes': None} while counting values of queryset. Note : Once each post have atlest one likes then I get Correct count. -
in below code what does ordered_by("?") do?
I'm new in django , javascripts , jquery , css and etc . In a project on the Internet I have seen the following code and i try to found whats going on with this project , but i cant understood what does ordered_by("?")in views.py do.any help? for more imformation : this project is about marketing site that in home page will show stuff from database. tnx urls.py: path('', product.views.home), models.py: class Product(models.Model): name = models.CharField(max_length=70, verbose_name='نام ') subtitle = models.CharField(max_length=70, null=True, blank=True, verbose_name='عنوان فرعی ') code = models.CharField(max_length=30, null=True, blank=True, verbose_name='کد محصول') father = models.ForeignKey("self", related_name="children", null=True, blank=True, on_delete=models.CASCADE, verbose_name="پدر") have_children = models.BooleanField(default=False, verbose_name="فروش به صورت فصلی") og_description = models.CharField(max_length=250, null=True, blank=True) company = models.ForeignKey(Company, verbose_name='شرکت ', null=True, blank=True, related_name='products', on_delete=models.CASCADE) price = models.IntegerField(default=0, null=True, blank=True, verbose_name='قیمت به ریال') # grade = models.ForeignKey(Grade, related_name='products', null=True, blank=True, verbose_name='پایه تحصیلی') brochure = models.ImageField(upload_to='brochure', null=True, blank=True, verbose_name='بروشور') photo_id = models.CharField(max_length=100, null=True, blank=True, verbose_name='آی دی تلگرام عکس') video_id = models.CharField(max_length=100, null=True, blank=True, verbose_name='آی دی تلگرام ویدئو') video = models.FileField(upload_to='videos', null=True, blank=True, verbose_name='دموی ویدیویی') introduction = models.TextField(null=True, blank=True, verbose_name='معرفی اولیه') thumbnail = models.ImageField(upload_to='thumbnail', null=True, blank=True, verbose_name='تامب نیل') link = models.URLField(max_length=300, null=True, blank=True, validators=[URLValidator()], verbose_name='آدرس فروش در وب سایت') label_1 = models.CharField(max_length=30, null=True, blank=True) label_2 … -
Date filtering with Django -- how to send start and end dates to my view?
I'm trying to add date filtering to an event listing I have on my Django site. In other words, I want the user to be able to select start and end dates and then show all events on or between those dates. I've tried the below code, which I feel like should be working. relevant HTML <div id="datefilter-container"> <p class="js-command">Filter shows by date &#8595;</p> <div id="datefilter"> <form name="date-range-form" id="date-range-form" action="{% url 'concerts:date_filter' %}" method="GET"> <label for="start">Start date:</label> <input type="date" id="start" name="start"> <label for="end">End date:</label> <input type="date" id="end" name="end"> <button type="button" name="date_filter">Submit</button> </form> </div> </div> urls.py (relevant line) url(r'^date_filter/$', views.filter_by_date, name="date_filter"), views.py (relevant function) def filter_by_date(request): if request.method == "GET": start_date = request.GET.get('start') end_date = request.GET.get('end') try: results = Concert.objects.filter( Q(date__gte=start_date) & Q(date__lte=end_date) ) except Concert.DoesNotExist: results = None template = "concerts/calendar.html" context = { "results" : results, "start_date" : start_date, "end_date" : end_date } return render(request, template, context) else: return render(request, "concerts/calendar.html", {}) Nothing is happening when I press the submit button in my HTML. I'm not sure if this is a problem with my HTML or my view. A little guidance would be greatly appreciated. -
store Django models in a dataframe and get column names from it even though dataframe is empty
I have Django models, which is based on SQL tables, which I need to read and store in a dataframe and later retrieve just one column to work on. For first run, table would be blank because of which dataframe is coming out blank [] I would need models to return blank dataframe with column names, even though data is not there. Current line of code that I've been using to retrieve model into dataframe is as follows:- dt = pd.DataFrame.from_records(my_table.objects.all().values()) my_val = dt.col1.iat[-1] currently, code is failing with following error AttributeError: 'DataFrame' object has no attribute 'col1' -
Can't get GCBV with context to show books by author unless i set the pk value as fixed
Using a Generic Class Based View and a Book model with a FK (author), I can only return all books or books of fixed value id. Using the python shell, I can retrieve the value I need, e.g. b.all().filter(author=6) >>> <QuerySet [<Book: bookA>, <Book: bookB]> However, I can't seem to translate this via a GCBV using context. Below, on the query below, how do I tell it to filter (for whatever the author id value of this page is? I.e. substitute the fixed value for the dynamic one. Views.py class AuthorDetailView(LoginRequiredMixin, generic.DetailView): context_object_name = 'author' queryset = Author.objects.all() def get_context_data(self, **kwargs): # call the base implementation first to get a context context = super().get_context_data(**kwargs) # add Queryset of All books context['book_list'] = Book.objects.filter(author=4) return context Each author page should show all related books. All examples i've seen don't use the id, name instead. Or it's a function based view. I'm fine using FBV if that's the only way, but i'd like to know how to use it in both, so I started with the GCBV. Thanks! -
Listing model-specific permissions in table
I'm having trouble listing all model-specific permissions in a table. I'm able to pull out permissions through {{ perms.account }} in the html, but it won't filter for permissions specific to the account model. Futhermore i want to list each permission in a html table, with the permissions description, and a checkmark if its granted: Permission1 Desc1 V <!-- Granted --> Permission2 Desc2 X <!-- Not granted --> I have tried for-looping all permissions, and filtering out the ones related to the model account, and then for looping to get the different rows in the table. This, however, just returned a long string of all permissions names. views.py class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk')), blank=True) role = models.CharField(max_length=50, choices=(('Administrator', 'Administrator'), ('Moderator', 'Moderator'), ('Editor', 'Editor'))) phone_number = models.CharField(max_length=8) birth_date = models.DateField() street_adress = models.CharField(max_length=255) note = models.TextField(blank=True); zip_code = models.CharField(max_length=4) city = models.CharField(max_length=255) def get_absolute_url(self): return reverse('account-detail', kwargs={'pk': self.pk}) class Meta: verbose_name = 'Account meta' verbose_name_plural = 'Accounts meta' permissions = ( ("has_user_hijack_permission", "Allows the user to log in as others"), ("has_user_management", "Allows a user to deactivate/delete other users"), ("has_user_site_edit", "Allows a user to edit … -
Django - How to Filter after Window expression/Annotation?
I'm trying to use Django's Window expressions to find the Rank of a bunch of Leaderboard objects. I need to save that ranking for later use, and it's that part that's causing me trouble. I have a method that works, but is much too slow for me. (Yes, I've already got @transaction.atomic set) window = { 'partition_by': [F('category_1'), F('category_2')], 'order_by': F('score').desc() } my_filter={"condition_1":True, "condition_2": False} ranking = Leaderboard.objects.filter(**my_filter).annotate( r=Window(expression=Rank(), **window) ) for lb in ranking: lb.ranking = r lb.save() I know I need to get rid of the save loop and replace it with an update() call. So I tried to do this instead: Leaderboard.objects.filter(**my_filter).update( ranking=Subquery( Leaderboard.objects.filter(**my_filter).annotate( rank=Window(expression=Rank(), **window) ).filter( pk=OuterRef('pk') ).values('rank')[:1] ) ) But when I try this every Leaderboard gets a ranking of 1... which isn't what I want (but it is 10x faster than the previous method). What I think is going on is that my filter on primary key is happening before my Window expression, which results in the Window expression running on 1 object instead of many. To run the update() I need to be able to get my Subquery results down to just the rank of an individual. I feel like I'm being tripped …