Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin: limit user to add/list/modify users from own group only
Say I have a group defined with limited permissions. Users in this group should be able to add/remove/modify other users, but only in their own group. Ideally I would like to implement 2 extra levels of user permissions: Superusers (all permissions on all apps) Admins that can add/list/edit admins and normal users, but not superusers (with partial permissions on some apps) Normal users that can add/list/edit normal users, but not admins nor superusers. (with limited permissions on some apps) What would be the best approach to archieve this, Maybe there is some package I overlooked? TIA! -
call a function from django-form without rendering its view
using Django I want to create a website on which if you click a button, a function is called in the server. And I also want a following condition: after the button is clicked, the page will not to be re-rendered. In a simpler word, I want to button-click and the run python script in the server. I've created the button-and-call-function script as follows, but it causes error because returned value is 1 and not rendering function. How can I achieve the goal? app_name/templates/app_name/index.html <body> <form action='some_function' method='GET'> <button type='submit'>Click Here</button> </form> </body> app_name/views.py def some_function(request): print("do something here") return 1 # error is caused here but I don't want re-render app_name/url.py from django.urls import path from . import views urlpatterns = [ path('', views.show_view, name='view'), path('do_something', views.do_something, name='do_something') ] Thanks! -
Django-extensions creates an unreadable graph
I was trying to visualize the database of a project and saw it was recommended to use django-extensions to do that, so I followed the documentation. What I did was: Install pyparsing and pydot using pip and also install graphviz without pip. Also modify my settings as follow: #settings.py INSTALLED_APPS = ['blabla', ... 'django-extensions'] GRAPH_MODELS = { 'all_applications': True, 'group_models': True, } And I ran the command - ./manage.py graph_models --pydot -a -g -o my_project_visualized.png in the container. It does end up producing a .png file, however, the text is just squares. I saw there are other threads, where people have problems with the versions of pyparsing and pydot. I haven't specified any versions, as I had no issues installing both and also when running the above mentioned command. -
Django save a modelformset without checking uniqueness
I have a model like this (I will only paste the relevant data): class Chart(BaseModel): name = models.CharField(max_length=255, null=False, blank=False) order = models.PositiveSmallIntegerField(blank=False, null=False, default=0) data_type = models.CharField(max_length=3, null=False, blank=False) # one data_type will be repeated in many instances of the model class Meta: unique_together = (('order', 'data_type'), ) When I have more than one Chart with a certain data_type, trying to reorder them manually becomes a big waste of time, so I decided to use a modelformset, allowing the user to only modify order. However, when I save the modelformset, an exception raises since the unique_together constraint is being violated. Here is the formset I use: class ChartOrderForm(forms.ModelForm): name = forms.CharField(disabled=True) class Meta: model = Chart fields = ['name', 'order'] ChartOrderFormSet = forms.modelformset_factory( Chart, form=ChartOrderForm, extra=0, ) And here is the method I use to save them: @login_required def charts_reorder(request): if request.method == 'POST': formset = ChartOrderFormSet(request.POST) if formset.is_valid(): formset.save() Is there a way to save them without violating the constraint that isn't modifying the orders several times, or deleting all the instances from the db and creating them again with different order? -
Unable to write Arabic letters to PDF file in Python 3
I have a PDF file with fields which need to be filled. I give the input to the fields in terms of a dictionary. I am able to fill the fields in different languages but when I try Arabic the field is empty but the code runs without any error. I tried to simply write Arabic text into a text file and it writes without any need for encoding or decoding. I use the following code to write an output PDF file from PyPDF2 import PdfFileWriter, PdfFileReader def update_form_values(infile, outfile, newvals=None): #newvals has the dictionary that contains the value for the fields pdf = PdfFileReader(open(infile, 'rb')) writer = PdfFileWriter() for i in range(pdf.getNumPages()): page = pdf.getPage(i) try: if newvals: writer.updatePageFormFieldValues(page, newvals) else: writer.updatePageFormFieldValues(page, {k: f'#{i} {k}={v}' for i, (k, v) in enumerate(newvals.items()) }) writer.addPage(page) except Exception as e: print(repr(e)) writer.addPage(page) with open(outfile, 'wb') as out: writer.write(out) -
(2059,“Authentication Plugin 'caching_sha2_password'”) when running server connected with MYSQL database on Django
I want to configure my django project in order to connect it with database in MYSQL I created with workbench 8.0, and then I want to run the server by running python manage.py runserver from anaconda command prompt, so that I can use the Django interface to visualize and alter data. Please note that I don’t want to downgrade workbench 8.0. These are the steps I have made: From anaconda prompt: pip install mysqlclient In my project folder, in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'schema_meta', 'USER': 'root', 'PASSWORD': '<mypassword>', 'HOST': '127.0.0.1', 'PORT': '3306', }, } Inside the directory of mysql server, I open cnf.ini and insert a the [client] section: [client] database=schema_meta host=127.0.0.1 user=root password=<mypassword> port=3306 default-character-set = utf8 Then from anaconda prompt I run Python manage.py runserver And I obtain error django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: Impossibile trovare il modulo specificato.\r\n") So I try to solve it by following this thread: django.db.utils.operationalError: (2059,"Authentication Plugin 'caching_sha2_password'") I open mysql workbench and I run this query: delete from mysql.user where user='root' and host = '127.0.0.1'; flush privileges; CREATE USER 'root'@'127.0.0.1' IDENTIFIED WITH mysql_native_password BY '<mypassword>'; And then, in the my.ini file I change default-authentication-plugin= … -
Start/Stop celery with Django
i have a django app that uses celery task and beat (periodic_task). i have written a script that start these two processes (Worker and beat) the way it should be. I'm quite new to django and now im trying to figure out how i can start celery when my app also gets started, or in other words: "How can i run the celery_start script at django app start"? Currently i have to trigger the celery_start script and the django app manually. And i would like to reduce this to a single app start. Thanks in advance :D -
Make a post request to a remote service using django_rest api
I want to post the modal data (modal fields for each entry in Json format) from my app (made up of python django) to a remote service using the provided end point url. I want to achieve something like this below of which i tried but failed def modal_data_view(generics.ListAPIView): molis_response= requests.post(remote_url, data=my_modal_data) return HttpResponse(molis_response.text) I am expecting my modal data to be received by the remote endpoint and return a text response. -
AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user'
Traceback (most recent call last): File "C:\Users\surje\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Users\surje\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\staticfiles\handlers.py", line 63, in call return self.application(environ, start_response) File "C:\Users\surje\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\wsgi.py", line 158, in call self.load_middleware() File "C:\Users\surje\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 53, in load_middleware mw_instance = mw_class() TypeError: init() missing 1 required positional argument: 'get_response' -
django annotate with dynamic column name
I have a model in django app, with the following structure: class items(models.Model): name = models.CharField(max_length=50) location = models.CharField(max_length=3) I wanted to create a pivot table for the count of each location per each name/item, which I managed to do as per the following: query_data = items.objects.values('name')\ .annotate(NYC=Sum(Case(When(location='NYC', then=1),default=Value('0'),output_field=IntegerField())))\ .annotate(LND=Sum(Case(When(location='LND', then=1),default=Value('0'),output_field=IntegerField())))\ .annotate(ASM=Sum(Case(When(location='ASM', then=1),default=Value('0'),output_field=IntegerField())))\ .annotate(Total=Count('location'))\ .values('name', 'NYC', 'LSA''Total')\ .order_by('-Total') This gives me how many times each name appears against each location which is all ok. my question is how can I make the location dynamic, and so if new locations where added I don't have come back and change the code again! either from a list or from the model data itself Many Thanks AB -
Graphene/GraphQL query without model binding
I want to pass JSON from client-side, process that JSON on server-side and then response to Client depending on JSON content. I know, that in usual case with Python/Django I need to use Graphene/GraphQL where I need to describe DjangoObjectType descendant with model, binded in descendat's Meta class. Then I should include this class to Query class, as class field. This is the way of models' data communication via Graphene. How can I solve my task as I don't need any model binding for my Query? -
Method Not Allowed (POST) Django 405 error
I've just changed my code from function based views to class based views and now am getting an error I can't seem to resolve. The error appears when a user presses a button to submit their location coordinates. Method Not Allowed: /connect/post [2019/02/11 14:27:17] HTTP POST /connect/post 405 [0.00, 127.0.0.1:57896] Everything was working before and I can't figure out what I am doing wrong. I have both the get and post requests. Could someone point me in the right direction? views.py class ConnectView(View): template_name = 'connect/home.html' def get(self, request, *args, **kwargs): context = { 'users': User.objects.exclude(username=request.user), } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) location.save() return JsonResponse({'message': 'success'}) urls.py urlpatterns = [ path('', connect_views.ConnectView.as_view(), name='connect_home'), ] connect.html <script> function showPosition(position) { pos = position; var { latitude, longitude } = pos.coords; $('#btn_submit').attr("disabled", null); } $(document).ready(function() { $demo = $("#demo"); $('#btn_submit').on('click', function() { var data = pos.coords; data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val(); $.post("post", data, function() { alert("Location Confirmed!"); }); }); }); </script> ---omitted irrelevant code-- <button type="submit" id="btn_submit" class="btn btn-success" disabled>2. Confirm Location </button> -
How can I compare values in a field in 2 distict models that have no relationship with eachother
I have 2 distinct models with no relationship to eachother but inheriting from an abstract model, these 2 model have email fields in common, I want to be check if an email value contained in this model exists in the other model. Here is my models. class BaseRespondent(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE class Meta: abstract = True id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256) email = models.EmailField() pos_applied = models.ForeignKey(PositionApplied, on_delete=_safedelete_policy, null=True) date = models.DateField(auto_now_add=True) test = models.ForeignKey(Test, on_delete=models.SET_NULL, null=True, blank=True) class Respondent(BaseRespondent): least_disc = models.CharField(max_length=256, default='') most_disc = models.CharField(max_length=256, default='') most_personality = models.ForeignKey(Personality, on_delete=models.SET_NULL, null=True, related_name="most_personality") least_personality = models.ForeignKey(Personality, on_delete=models.SET_NULL, null=True, related_name="least_personality") # combine = GenericRelation(Combined_Respondent, related_query_name='disc') def result(self): return format_html( '<a href="{0}result/{1}">View result</a>', settings.SITE_URL, self.id, ) class Meta: verbose_name = "DISC Respondent" verbose_name_plural = "DISC Respondents" class MBTIRespondent(BaseRespondent): first_col_component = models.CharField(max_length=32, null=True) first_col_score = models.CharField(max_length=32, null=True) third_col_component = models.CharField(max_length=32, null=True) third_col_score = models.CharField(max_length=32, null=True) fifth_col_component = models.CharField(max_length=32, null=True) fifth_col_score = models.CharField(max_length=32, null=True) seventh_col_component = models.CharField(max_length=32, null=True) seventh_col_score = models.CharField(max_length=32, null=True) personality = models.ForeignKey(MbtiPersonality, on_delete=models.SET_NULL, null=True) # combine = GenericRelation(Combined_Respondent, related_query_name='mbti') def result(self): return format_html( '<a href="{0}result/mbti/{1}">View result</a>', settings.SITE_URL, self.id, ) class Meta: verbose_name = "MBTI Respondent" verbose_name_plural = "MBTI Respondents" I want to be able to display only … -
in my django project i get a 'ModelFormOptions' object has no attribute 'concrete_model' error
I have added a form for my django rest project. However, I keep getting a 'ModelFormOptions' object has no attribute 'concrete_model' error. In my User class I have added a new field 'password' and I was trying to create a form. and call the serializer upon it. My Model: class User(models.Model): gender = models.CharField(max_length=10, blank=False, choices=GENDER) first_name = models.CharField(max_length=20, blank=False) last_name = models.CharField(max_length=20, blank=False) position = models.CharField(max_length=50, blank=True) birthday = models.DateField(auto_created=False, blank=False) email = models.EmailField(max_length=50) phone = models.CharField(max_length=15, blank=False) password = models.CharField(max_length=100, default='something') Form class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'password') Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = UserForm fields = '__all__' Here is the Error that occures: AttributeError at /users/ 'ModelFormOptions' object has no attribute 'concrete_model' -
Fetch child data with parents in Django queries
I have two Model Product and ProductBundle. ProductBundle have a foreign key of Product Model. How can I access a list of all product with there productbundle. class Product(models.Model): title = models.CharField(verbose_name="Product Title", max_length=500) class ProductBundle(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name="product") bundle_product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name="bundle_product",default="") quantity = models.IntegerField(default="1") I want to fetch all product with there productbundle ids like parent to childs in a single variable. Thanks. -
icons to represent a MultiSelectField field
I have a MultiSelectField field, ie it returns more than one option, these options are, dog, cat, fish, birds and so on. I would like that when the profile was viewed and that person had registered with cat and dog in the profile were shown the icons of cat and dog, but I could not think how to develop this logic -
DRF Modelserialize returns only key
I'm using Django 1.5 and Django REST Framework 2 I have overridden create method to add validation and return Response manually. my view is like class MultiUserCreateListView(generics.ListCreateAPIView): model = MultiUser serializer_class = MultiUserSerializer def get_queryset(self): users = MultiUser.objects.get_shared_users(user=self.request.user) return users def create(self, request, *args, **kwargs): email = request.DATA.get('email', None) access_level = request.DATA.get('access_level', None) name = request.DATA.get('name', None) user = User.objects.filter(email=email) if user: return Response({'message': 'Email address already in use.'}, status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(data=request.DATA) new_user = create_active_user(request, self, email, email, password=None, is_shared=True) if new_user: if serializer.is_valid(): multi_user_obj = MultiUser( user=self.request.user, shared_user=new_user, access_level=access_level ) multi_user_obj.save() serializer2 = MultiUserSerializer(data=multi_user_obj) return Response(serializer2.data, status=status.HTTP_201_CREATED) else: return Response({'message': 'Unable to create user. Try again'}) But the response contains only key with empty value for the fields defined in the MultiUserSerializer {"id": "", "shared_user_name": "", "shared_user_email": "", "access_level": "", "invitation_sent_on": null, "invitation_accepted_on": null, "is_invitation_sent": "", "is_invitation_accepted": "", "created": null, "updated": null} While printing print(multi_user_obj.id) gives the correct id. Why is it not serializing? -
How do I count elements in the view-context and form for popdown menus when testing
I limit querysets to request.user. Each user should only see and work on his own data. How can I count the resulting elements in the context and in the form to test them against a ORM queryset. I read 2 days of documentation and did not get much further. #models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User class Order(models.Model): order_number = models.CharField(max_length=10) ordertext = models.TextField(max_length=1000, help_text='Description of Order') user = models.ForeignKey(User,on_delete = models.CASCADE,related_name="Order") class Delivery(models.Model): order_number = models.ForeignKey(Order,on_delete = models.CASCADE,related_name="Delivery") delivery_number = models.CharField(max_length=10) summary = models.TextField(max_length=1000, help_text='Description of Delivery') user = models.ForeignKey(User,on_delete = models.CASCADE,related_name="Delivery") #views.py from booking.models import Delivery, Order from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin class NewDelivery(LoginRequiredMixin, CreateView ): ''' Limit Order in context and form to request.user ''' model = Delivery template_name = 'book/Delivery/form.html' success_url = reverse_lazy('delivery') def get(self, request, *args, **kwargs): super().get( request,*args, **kwargs) form_class = self.get_form_class() form = self.get_form(form_class) try : form.base_fields['order'].queryset = Order.objects.filter(user__in=[self.request.user,]) except KeyError : pass def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Title'] = 'New Delivery and assign Order' try : context['form'].fields['order'].queryset = Order.objects.filter(user__in=[self.request.user,]) except KeyError : pass # return context To test View and Form I want something like : (get orders … -
Django Rest Framework: finding model instance with url slug, not pk (lookup_field, retrievemodelmixin)
I want to use RetrieveModelMixin. Default setting is finding with pk, but I want to find a model instance with another model field. Then, how can I do this? I tried to add lookup_fields = 'usename' but it didn't make it. #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='', blank=True, null=False) username = models.CharField(max_length=100, blank = False, null = True) post = models.ForeignKey(Post, related_name='post', on_delete=models.CASCADE, null =True) introduction = models.TextField() #serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' lookup_fields = 'username' #urls.py path('test/<slug:username>/', views.ProfileDetail.as_view(),name='profiles-detail'), #views.py class ProfileDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_fields = 'username' def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) This results Expected view ProfileDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. How can I fix this error? Thanks. -
Disqus showing same comments on all pages with unique page.url and page.id set
I'm adding disqus to my django application and can not get it to load a new thread of comments on each page. I have tried everything and followed the documentation, which states to set the variables in disqus javascript template before using. Here is my 'post_detail.html' that needs disqus comments: {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body|safe }}</p> </div> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ var disqus_config = function () { this.page.url = '{{ request.build_absolute_uri }}'; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = '{{ request.get_full_path }}'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable this.page.title = '{{ post.title }}' }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://bytewise-com.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> {% endblock content %} The variables in this function are set correctly, per https://help.disqus.com/developer/javascript-configuration-variables ... this.page.url = '{{ request.build_absolute_uri }}'; this.page.identifier = '{{ request.get_full_path … -
How can I use both OR & AND conditions in django filters?
In my code i have some filter conditions where i have to use OR condition in between some AND conditions in django filter.Here,is my code def get_initial_queryset(self): filterCondition={'iType':1} if status: statusCondition={'iApprovedStatus': status} filtercondition.update(statusCondition) ....... EIDlist=[1,2,5,7] EIDcondition={'EID__in':EIDlist] TIDlist=[5,8,9,10] TIDcondition={'TID__in':TIDlist] filtercondition.update(EIDcondition) filtercondition.update(TIDcondition) executeQuery = ENTITY_TEMPLATES.objects.filter(**filterCondition).order_by('-dtCreatedOn') Here,i need to apply OR condition between EIDlist and TIDlist. But, in filtercondition it will take as AND and i'm getting wrong resultset.How can i do this query? Any suggestions? -TIA -
Django: CSRF middleware and mixed POST/GET forms
I would like to crate a form whith two submit buttons: Save, let's say, and Back to edit. (The form is meant for a preview / confirm view of stuff that is currently being edited). For obvious reasons the Save button has a formaction attribute with value post and the other button get. For the post action to work, I include the usual csrfmiddlewaretoken in the form. So far all works well, the only problem is that the csrfmiddlewaretoken value is now included in the GET requests (which seems to be discouraged for security reasons). Currently I add some custom javascript that finds all submit buttons with get action and adds a click handler that removes the csrfmiddlewaretoken from the field before submit. This seems a rather wierd and roundabaout way to do things. Question: Is there a better / more standard / more stable way to handle this situation? -
How to send asynchronous HTTP requests from Django and wait for results in python2.7?
I have several API's as sources of data, for example - blog posts. What I'm trying to achieve is to send requests to this API's in parallel from Django view and get results. No need to store results in db, I need to pass them to my view response. My project is written on python 2.7, so I can't use asyncio. I'm looking for advice on the best practice to solve it (celery, tornado, something else?) with examples of how to achieve that cause I'm only starting my way in async. Thanks. -
FB.Event.subscribe('comment.create') run 2 times when create a comment from a facebook comment web plugin
I want to call an ajax 1 time function whenever someone create a comment on the facebook comment plugin. But the sever call the ajax function twice. I have already looked up for a day but nothing can help me. here is my code window.fbAsyncInit = function fb() { FB.Event.subscribe('comment.create', function () { function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ url: 'http://127.0.0.1:8000/ajax/comment/', type: "POST", data: { 'id': $('#fbcomment').attr('data') }, dataType: 'json', success: () => { } }); }); }; Here is my facebook js (I put it before <body>): <div id="fb-root"></div> <script>(function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = 'https://connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=v3.2'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> my urls.py link: re_path(r'^ajax/comment/$', views.Action.comment, name='comment'), here is the view: def comment(request): id = int(request.POST.get('id')) film = get_object_or_404(Film, pk=id) film.comment = film.comment + 1 film.save() return JsonResponse(id, safe=False) Please help me. sorry for my poor english. This is what i get -
How to store data from APIs like cricbuzz in django databases?
I am in a task of create a cricbuzz like webapp. With API client library, I get json data. How I can store these data into django database.