Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to exclude some specific django permissions in django html template
I am trying to display the user permissions which are relevant to my project excluding some default django user permissions. I am implementing the following code. I want to exclude permissions like sessions, content_type, groups from my html template. How can i do it?? views.py permissions = Permission.objects.all() template I want to remove user can add group,user can change group in template {% for permission in permissions %} {{permission.name}} {% endfor %} -
Django taking very long time to serve generated static files
In my view I generate 5 images (they are generated by pyplot.) Everything seems to work fine. The files are generated correctly in the right directory. But the browser only shows one of the five images, and the requests for the other 4 usually timeout. Looking at the django server output, the GET requests will often take five minutes to finish. These images are ~100kb, and are present and correct on the drive immediately after being generated. Am I missing a call for Django to update the new static files? Something else? Please help! -
Sometime on Django after ajax get compleate they show page like Jsonrespone
I using django==1.11 djangorestframework==3.8.2 and my view have a two class of api view like this Class NormalReaderHTML(APIView): def get(self,request): .. do_something .. return render('my_html.html',{}) Class AjaxView(APIView): def get(self,request): #we using cache for database like this my_cache = cache.get(cache_engagement_key) if my_cache is not None: return JsonResponse(cache_context, status=200) .. do_something .. .. do_something .. cache.set(my_cache*60*60*6) return JsonResponse({my_data},status=200) and on html page I execute file javascript to call Ajax on documeny ready like this $.ajax({ type:"GET", url:"my_endpoint", success:function(data){ $(".Dothisclass").text(_.get(data,'my_target',"")) }) }) after that we I call to my endpoint of NormalReaderHTML will show html page like normal. and after that my html and javascript will working to call Ajax and do a lot thing like insert value adjust value but sometime we found we got Jsonresponse from ajax to render page like {my_data:my_data,my_data:my_data} I already have no idea what happen and where they from. we only found it's happen in Chromes and Safari (safari it's found more than chrome) -
How can I sync MySQL Data to Google Spreadsheets?
Till now, I'm able to fetch data from Google Spreadsheets to MySQL DB. Now what I want is if I submit my form then it should get stored in MySQL DB also and Google Spreadsheets also. I'm using Django framework for my work. You can refer: https://github.com/vanthoff10/django-sqlsearch-engine Please, it's urgent for my work. Thanks in advance. -
Prepare a string representation of a command and then execute id
Django==2.2.2 Now I have this code: Model class YandexResponse(models.Model): time = models.DateTimeField(auto_now=True) campaigns = models.TextField() ad_groups = models.TextField() ads = models.TextField() keywords = models.TextField() sitelinks = models.TextField() View yandex_response_record, created = YandexResponse.objects.get_or_create(id=1) if what_to_update == "campaigns": yandex_response_record.campaigns=json.dumps(data) yandex_response_record.save() elif what_to_update == "ad_groups": yandex_response_record.ad_groups=json.dumps(data) yandex_response_record.save() ... I'd like to have something like: tmp = "yandex_response_record.{}=json.dumps(data)".format(what_to_update) execute(tmp); yandex_response_record.save() Could you tell me whether is is somehow possible? If it is not possible, could you suggest me some elegant solution here? -
django: Threads does not close after performing the function
[Simple approach to launching background task in Django refering to this I am using threading to do background processing. It perfectly renders a html page but the thread used for background processing does not stop even after performing its function how can i stop this thread after it has done its job(it only stops when i press Ctrl+C)? Note: The output of the function called by thread is fine its just that thread does not stop.I think its because this function does not return to its calling function. i have tried using threadname._stop but it gives assert error also i don't want to use thread.join() as it will wait until processing is done before rendering the html page . Here is the code(args in thread has no functionality) calling function in views.py def callmepls(request): if request.method=="POST": global x x=threading.Thread(target=theds,name="abcd", args=(1,),daemon=False) x.start() return HttpResponse("background process started working") else: return render(request,"callthis.html",{}) Performing function in view.py def theds(name): for i in range(5): print(i) time.sleep(10) x._stop() Template(callthis.html) {%extends "base.html"%} {%block content %} <form method="POST" action=""> {%csrf_token%} <p> Run the it: <input type="submit" value="Start" > </p> </form> {%endblock%} -
Why doesn't this group by work how I want or expect it to
I am new to Django.I am trying to make this this query return count by group. But it doesn't doesn't group data. notification = AppointmentNotificationGroupAppointment.objects.filter(receiver__notification_group__group=group).values('receiver__notification_group__group', 'sender__status__name').annotate(pcount=Count('sender__status__name', distinct=True)) It returns: {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Pending', 'pcount': 1}, {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Pending', 'pcount': 1}, {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Confirmed', 'pcount': 1}, {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Confirmed', 'pcount': 1} What am I doing wrong? I want it to return distinct records with them counted by group -
how to automatically open url(not click open) http://127.0.0.1:8000 python manage.py runserver in pycharm terminal
I would like url (http://127.0.0.1:8000) to automatically open the browser (by no-click) if I enter the command 'python manage.py runserver'. I tried to run http://127.0.0.1:8000/ with a browser without a mouse. so I tried all the shortcuts I could find, but I could not find them. python manage.py runserver (venv) seongyoonhuh@seongyoonhuh:/media/seongyoonhuh/usb16g/20190619/basic$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). June 19, 2019 - 17:39:37 Django version 2.2.2, using settings 'config.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. -
Django user permission not working properly
Here i am trying to give staff users some specific permissions .I tried like this .This code saving all the checked permissions in the database table auth_user_user_permissions and also displaying the added permissions for the particular user in template but the users is not being able to use that permissions.For example i added only permission of user can view product and this permission gets added in the table but when i perform add product action with this user then i am being able to use that permission even i haven't given this action role to this user. views.py def update_user_roles(request,id): user = get_object_or_404(User, id=id) user_permissions = Permission.objects.all() if request.method == 'POST': permissions = request.POST.getlist('user_permissions') print('hey',permissions) form = EditUserRole(request.POST or None,instance=user) if form.is_valid(): role = form.save(commit=True) role.save() user.user_permissions.set(permissions) messages.success(request,'Roles updated for user '.format(user.username)) return redirect('user_profile',user.id) else: form = EditUserRole() return render(request,'update_user_role.html',{'form':form,'user':user,'user_permissions':user_permissions}) template <form action="{% url 'update_user_role' user.id %}" method="post" > {% csrf_token %} <div class="form-group"> <h5>User Roles</h5> <div class="controls"> {% for permission in user_permissions %} <input name ="user_permissions" type="checkbox" id="permission-{{permission.id}}" value="{{permission.id}}" {% if permission in user.user_permissions.all %} checked="checked" {% endif %}> <label for="permission-{{permission.id}}">{{permission.name}}</label> {% endfor %} </div> </div> <div> <button type="submit" class="btn btn-info">Save</button> </div> </form> -
How do I make "if the loop is executing for the last time" condition in python
So, I am making a login system through file handling in python. The code works fine when I enter the correct username/password but it doesn't work when I use 'else' statement for the condition which should execute when the user enters incorrect password. for line in open('accounts.txt','r+').readlines(): loginfo = line.split() if a==loginfo[0] and b==loginfo[1]: return render(request, 'login.html') else: return render(request, 'index.html') Here, the loop is executed and each line is checked to see if the username, password entered by the user is in the file or not. I am using getlines() function to get usernames and passwords of a user through lines, which means each line should consist of a username and password separated with a space. I am using line.split to split usernames and passwords in the file. If I remove "else" then enter the correct password, then the code works fine but it does not work fine when I enter incorrect password. If I put 'else' condition inside the loop then it messes up the algorithm, and the web-page is rendered when the loop is executing for the first time. What I want is that the "else" condition should execute only and the web-page 'index.html' should only be … -
How can i use same serializer in Create and List Views
I have a PostSerializer and this serializer have an user field. Also i have a UserSerializer. So i want to use UserSerializer in the PostSerializer like this class PostSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) class Meta: fields = ('user', 'title') But i got the error when i try to use in the CreateView because i dont send UserSerializer data, i send user_id. I have to use same Serializer in Create and List view. Because i use to ListCreateAPIView. -
Request error in django view when setting up user
I have an app which lets the currently logged in user to create a Person object. That person object has the current logged in user as it's owner. But as I save the form it give me the following error global name 'request' is not defined I am trying to achieve this using Django CreateView the error trackback Traceback: File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\edit.py" in post 217. return super(BaseCreateView, self).post(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\edit.py" in post 183. return self.form_valid(form) File "C:\Users\Bitswits 3\Desktop\Maala\MaalaWeddings\userfiles\views.py" in form_valid 120. obj.user_relation = request.user Exception Type: NameError at /Personadd/ Exception Value: global name 'request' is not defined Views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import * from django.contrib.admin.views.decorators import staff_member_required from .forms import * from django.shortcuts import * from .models import * from django.contrib.auth.forms import * from django.http import * from datetime import * from django.contrib.auth import * from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.views.generic import … -
Django test assertTemplateUsed with included templates
I have a base.html which includes a lot of .html templates. While testing for the correct template, the test fails because the response lists all of the templates used as includes in base.html. But the one which is used is also in the list. Here my code and the error from the test: response = self.client.get(reverse('ListAccounts')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response=response, template_name='/backstage/account/list_accounts.html') The test message: AssertionError: False is not true : Template '/backstage/account/list_accounts.html' was not a template used to render the response. Actual template(s) used: backstage/account/list_accounts.html, backstage/base.html, backstage/partials/header_mobile.html, backstage/partials/header_topbar.html, backstage/partials/header_topbar_menu.html, backstage/partials/header_topbar_search.html, backstage/partials/header_topbar_notifications.html, backstage/partials/header_topbar_quickactions.html, backstage/partials/header_topbar_cart.html, backstage/partials/header_topbar_language.html, backstage/partials/header_topbar_userbar.html, backstage/partials/aside_menu.html, backstage/partials/sub_header.html, backstage/partials/generalModal.html, backstage/partials/footer.html, backstage/partials/quick_panel.html, backstage/partials/filter_panel.html, toastrMessageAjax.html How can I test this ? -
How to save text input from user without modifying property for admin?
I want to store the user's inputs in my database, and I don't wanna the admin can change those user's input. in my models.py, I have: class UserInput(): firs_name = models.CharField(max_length=10) as you can see, the CharField form field is gonna make a character field, so the admin can change the user input. I don't want that. -
Django Cassandra engine does not record datettime correctly
I am using django Cassandra engine for my project and I have defined this model: class StatusLog(DjangoCassandraModel): created_at = columns.DateTime(default=datetime.datetime.now()) but when I add record to database created_at is not recording correct time (for example for all the records of today it records 2019-06-19 11:30:34.154). I dont know where is the problem -
NoReverseMatch at / Reverse for 'single_product' with no arguments not found. 1 pattern(s) tried: ['products/(?P<slug>)/$']
I got this error using django 2.2 here are my codes urls.py app_name = 'products' urlpatterns = [ url(r'^$', product_list, name='product-list'), url(r'^(?P<slug>.*)/$',single, name="single_product"), url(r'^category/(?P<slug>.*)/$',category_single,name="category") ] views.py in product model def get_absolute_url(self,): return HttpResponseRedirect(reverse('single_product',args=[self.slug])) tempplate <h3>{{ product }}</h3> <p>{{ product.description }}</p> <p>{{ product.get_price }}</p> <p> <a href ="{% url 'products:single_product' %}" class = "btn btn-primary" role = "button"> View Product </a> -
How to transform only the values of a queryset into a new array of dictionaries in django
I want to pass data from my view to my template in an efficient way. Specifically I need an array with a dict inside of it like so: arraydict = [{key:value}, {key:value} ...] Right now this is what I do: class VisualizationView(ListView): template_name = 'visualize.html' model = UrlTime def get_context_data(self, **kwargs): context = super(VisualizationView, self).get_context_data(**kwargs) #Extracts the months and counts them context['months'] = (UrlTime.objects.annotate(month=ExtractMonth('timestamp')).values('month').annotate(c=Count('id'))) this counts my months. Printing our my {{ month }} in my django template gives me back this queryset: <QuerySet [{'month': 5, 'c': 313}, {'month': 6, 'c': 1961}]> So far so good. My idea is to visualize my data with d3.js for which I need well-strucutred data. So I would like to transform this queryset into something like: data = [{5:313}, {6:1961}]. Basically creating a dict of the values of the queryset and then put it into an array. (Even better would be data = [{May:313}, {June:1961}]) I tried the .values() method which breaks my count method. Also I tried to put it into a list like so: list(UrlTime.objects.annotate(month=ExtractMonth('timestamp')).values('month').annotate(c=Count('id'))) (this works but gives me back a list with dict of keys and arrays like so: [{'month': 5, 'c': 313}, {'month': 6, 'c': 1962}] I also did … -
FOREIGN KEY constraint failed because of models.DO_NOTHING
I have this snippet of code for models.py class Provider(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) provider = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) when ever I tried to delete an object I faced an error says : django.db.utils.IntegrityError: FOREIGN KEY constraint failed I faced this issue on django 2.x , since every thing was perfect on 1.11. I made a little search I found may this issue happen by this part on_delete=models.DO_NOTHING, So how could I fix it with kepping every thing as it is ? -
Django TypeError in version 2.2.1 : render() got an unexpected keyword argument 'renderer'
I was actually solving this error by editing the django file "boundfield.py" by removing the renderer value.I also tried using django 2.0.x instead of the newest version as the older version is not having this issue. I know this is not the right way to solve this issue. Can anyone tell me what's the problem and is there any way that could help me solve this error if I am using django 2.2.1 ? -
Distinguish which field has changed in signal.instance , Django/signals
Lets say I have a model called BookModel with 4 fields : (title, author, price, publish_year). And I have a handler in signals: @receiver([post_save, post_delete], sender=BookModel) def signal_handler(sender, instance, **kwargs): ….. Question is how to distinguish a situation when specific model field has changed during save(). For example if price has changed I want to do stuff. Better explain in pseudo code... @receiver([post_save, post_delete], sender=BookModel) def signal_handler(sender, instance, **kwargs): # pseudo code bellow if field “price” has changed: do stuff else: do nothing According the docs if I use “update_fields” in save() - it is possible, but what if I dont use it??? Also is it possible to distinguish a situation when I received signal from post_save or from post_delete still using 1 handler? @receiver([post_save, post_delete], sender=BookModel) def signal_handler(sender, instance, **kwargs): # pseudo code bellow if signal is post_save: if field “price” has changed: do stuff else: do nothing else: do other stuff Thanks -
Re-indexing in elasticsearch
In my project, the index command is taking around 5 hours to complete the indexing of entire records in the database. If I want to re-index the data it would take the same amount of time and with the increasing storage, indexing would consume so many hours which is not feasible. Is there any better way to re-index only the updated or deleted data in lesser time? I know we can use elasticsearch-reindex for this but I'm not totally aware of it's usage. Can someone suggest any better alternative ways and provide a sample code if possible? Thanks a lot in advance!! -
ListCreateAPIView post method has stopped working
For some reason my very simple view is blowing up when I attempt to make post() request to it. Here is some of there error message I get: IntegrityError at /api/v1/spi/locations/ null value in column "site_id" violates not-null constraint DETAIL: Failing row contains (29, 2019-06-19, location_a, 2019-06-19, null). Here is my view: class LocationList(generics.ListCreateAPIView): # using get_queryset().order_by('id') prevents UnorderedObjectListWarning queryset = Location.objects.get_queryset().order_by('id') serializer_class = LocationSerializer permission_classes = (SPIPermission,) Nothing to it. Here is the my LocationSerializer class: class LocationSerializer(serializers.ModelSerializer): site = SiteSerializer(many=False, read_only=True) class Meta: model = Location fields = '__all__' I added the line ... site = SiteSerializer(many=False, read_only=True) ... so my client would get the full site data instead of just an id. Is that causing my problem? Here are the Site and Location models: class Site(models.Model): create_date = models.DateField(auto_now_add=True) name = models.TextField(max_length=150, null=False, unique=True, verbose_name="Site name") update_date = models.DateField(auto_now=True) def __str__(self): return self.name class Location(models.Model): create_date = models.DateField(auto_now_add=True) name = models.TextField(max_length=150, null=False, unique=False) site = models.ForeignKey(Site, null=False, on_delete=models.PROTECT) update_date = models.DateField(auto_now=True) @property def site_name(self): try: return self.site.name except Exception as ex: logging.getLogger("capman").error(ex) return 'Unknown' def __str__(self): return self.name -
How To Remove Row in django-extra-views?
In ModelFormSetView how to delete row here is my code how can I manage delete row in Django-extra-views I am trying with normal if formset.deleted_forms: for obj in formset.deleted_forms: obj.delete() Html {{ formset.management_form }} {% for object in formset %} {% for hidden in formset.hidden_fields %} {{ hidden }} {% endfor %} <tr class="formset" class="even pointer">{{ object.id }} <td class=" ">{{ object.as_p }}</td> <td class=""></td> </tr> {% endfor %} View this is general view how can I manage DELETE filled in this class MeasurementPropsUpdateViews(ModelFormSetView): model = MeasurementProps form_class= MeasurementPropsForm template_name = "master/measurementprops_form.html" def get_queryset(self): pk = self.kwargs.get('pk') current_user = self.request.user return self.model.objects.filter(ProductName=pk, user=current_user) def get_success_url(self): return reverse("tailoringproducts") def formset_valid(self, formset): for docs_form in formset: docs_form.save(commit=False) if formset.deleted_forms: for obj in formset.deleted_forms: obj.delete() docs_form.instance.ProductName_id = self.kwargs.get('pk') docs_form.instance.user = self.request.user docs_form.save() messages.success(self.request, "Measurement Properties Updated successfully") return HttpResponseRedirect(self.get_success_url()) def formset_invalid(self, formset): messages.error(self.request, "Form getting invalid") return self.render_to_response(self.get_context_data(formset=formset)) -
How to run a Python code using CLI(Command-Line-Interface) in Chrome?(OS Handling)
How can I use CLI on google chrome to minimize CPU usage and run a python code using Django?I even want to generate a Log file to track the run flow. In short I want to add OS handling to my Python code(using Django).(My code is regarding fetching 2.5 million data from database and write them to an excel sheet which has three sub sheets.) Please help me regarding this. -
Can I use MariaDB ColumnStore with Django (Django-ORM)?
I have a Django project which uses MariaDB (engine - django.db.backends.mysql). I would like to user MariaDB ColumnStore instead - is it possible? Will I need a different ORM engine? Also, I develop on Windows 10 Pro PC and plan to set up ColumnStore using docker containers provided by MariaDB. This should not be an issue, right? Thank you