Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX success not JSON serializable
I am implementing AJAX in my Django project. Users can navigate through their favorite items in their account. I have two models, Product for the products details, SavedProduct with username and product_id (foreign key from Product). At first users land into their account from a link, then they sould navigate from page to page with AJAX. So far whenever I hit one of the navigation button a list of dictionaries is created in my view. But I can't pass it back to AJAX, I get a TypeError: Object of type Page is not JSON serializable. What I want is my list of dictionnaires to reach AJAX so it can change my DOM. My views.py: def account(request): user_id = request.user sub_list = SavedProduct.objects.filter(username=user_id) paginator = Paginator(sub_list, 5) page_number = request.GET.get('page') saved_list = paginator.get_page(page_number) context = { 'paginate': True, 'saved_list': saved_list, } if request.method=='POST': user_id = request.user sub_list = SavedProduct.objects.filter(username=user_id) results = [] for fav in sub_list: products_json = {'or_name':0, 'sub_name':0, 'or_brand':0, 'sub_brand':0} products_json['sub_name']=(fav.sub_product.real_name) products_json['sub_brand']=(fav.sub_product.real_brand) products_json['or_name']=(fav.original_product.real_name) products_json['or_brand']=(fav.original_product.real_brand) results.append(products_json) paginator = Paginator(results, 5) page_number = request.POST.get('page') saved_list = paginator.get_page(page_number) data = json.dumps(saved_list) return JsonResponse(data) return render(request, 'account/account.html', context) My AJAX: $(".nav_button_2").on("click", function(event) { event.preventDefault(); var page = $(this).val(); console.log (page); var url = … -
how to make add() with through_defaults different for each object m2m Django?
I have a question about Django add(*objs, bulk=True, through_defaults=None) with new through_defaults argument. https://docs.djangoproject.com/en/3.0/ref/models/relations/#django.db.models.fields.related.RelatedManager.add I have a intermediate model that is used as through model in many-to-many relationship. Relations are recursive and symmetrical (model points to itself). class GroupingModel(models.Model): """ Intermediate model for Many-to-Many recursive relationship between series. """ from_series = models.ForeignKey( 'TvSeriesModel', on_delete=models.CASCADE, related_name='group', ) to_series = models.ForeignKey( 'TvSeriesModel', on_delete=models.CASCADE, related_name='group_to', ) reason_for_interrelationship = models.TextField( verbose_name='Reason for relationship to an another series.' ) For example I have 4 primary model 'TvSeriesModel' instances : obj1, obj2, obj3 and obj4. Now I want to add m2m relationship between obj1 and obj2, obj3 and obj4 via our intermediate model ‘GroupingModel’ where I want to specify reason for this relations in field ‘ reason_for_interrelationship ’ and this reason should be different for each object. So, I would type : interrelationship related manager from primary model obj1.interrelationship.add( obj2, obj3, obj4, through_defaults ={ ‘reason_for_interrelationship’: ‘???????’ } ) And now I have a problem if I want to specify different reason for each object. Seems like it is not possible or at least not obvious for me how to do it. Problem is that I am able to specify only one common reason for relationship for … -
TypeError: Object of type ndarray is not JSON serializable
I want to serialize list of Data which looks like this [[-0.19137745 -0.08272246 -0.29323375 ... -0.07040742 0.08504822 0.11830507] [-0.21211784 -0.08182242 -0.29623193 ... -0.05424922 0.10875464 0.1036639 ] [-0.21633492 -0.08055094 -0.2975351 ... -0.06488793 0.10478106 0.0810216 ] ... [-0.14636803 -0.08461116 -0.3130865 ... -0.05071553 0.04644154 0.08371831] [-0.17098498 -0.08941076 -0.29189685 ... -0.06070996 0.08538496 0.1129984 ] [-0.19961393 -0.07552703 -0.30188963 ... -0.0616323 0.08856633 0.11165522]] shape is (9, 128) and I m using JsonResponse of Django to send a response. return JsonResponse({'use_id':user_id,'face_location':location,'embeddings':encodings,'message':message}) It is raising error like raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type ndarray is not JSON serializable -
update existing record or create if it doesn't exist django rest
I am using Django Rest Framework connected with MySQL DB. I have created a table "Product Status" #models.py class ProductStatus(models.Model): product_id = models.IntegerField(blank=False, null=False,primary_key=True) status = models.CharField(max_length=16,blank=True,null=False,validators=[alphanumeric]) #serializers.py class ProductStatusSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ProductStatus fields = ('product_id', 'status') and I would like to receive multiple records' POST requests and update records if product_id exists or create a new one if product_id is new. How can I do that? -
Error when uploading image to django server using retrofit and kotlin
I wrote the part where I upload the image using retrofit. enter image description here enter image description here And this is what the django server did. [enter image description here][3] If you do this, the django output shows up like this. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Bad Request: /app_addface/ To be honest, Android studio coding seems wrong, but I don't know how to implement it. Also, I don't know what function you should use to put into the django after receiving it from Android Studion. -
Summing Values in Dictionary Based on Certain Values
:) I'd love it if someone could lend me a hand with this... I have a list of dictionaries that state a date as well as a price. It looks like this: dict = [{'Date':2020-06-01, 'Price': 50}, {'Date':2020-06-01, 'Price': 12}, {'Date':2020-06-02, 'Price': 60}] I'd like to create a new list of dictionaries that sum all the Price values that are on the same date. So the output would look like this: output_dict = [{'Date':2020-06-01, 'Price': 62}, {'Date':2020-06-02, 'Price': 60}] How could I achieve this? Any help would be really appreciated. Thanks in advance! :D PS. Technically, the list of dictionaries is displayed like this: dict = [{'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 50}, {'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 12}, {'Date':datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}] I don't know if one version better than the other though. -
Django tables2 how to display distinct row
I want to have main table with linking value to table with details. I managed that by displaying detailed table with values form main table linked by foreignkey. The issue it that a have duplicated rows in main table that way. It there a way to display distinct value. I have tried to display data from table Factclaimcases and then replace pk - idfactclaimcases with partnumber from Factclaim but I failed. I would appreciate if somebody could look a it. views.py def claim_cases(request): items = Factclaim.objects.exclude(idfactclaimcase__isnull=True) table = tab_claim_cases(items) return render(request, 'claim_cases.html', {'table': table}) tables.py class tab_claim_cases(tables.Table): partnumber = tables.TemplateColumn('<a href="{% url "case_details" %}?idfactclaimcase={{ record.idfactclaimcase.idfactclaimcase }}">{{ record.partnumber.partnumber }}</a>') class Meta: model = Factclaim template_name = "django_tables2/bootstrap.html" fields = ("partnumber", "idfactclaimcase.thedate.thedate", "idfactclaimcase.description", "idfactclaimcase.manufacturedef") models.py class Factclaim(models.Model): idclaim = models.IntegerField(db_column='IdClaim', primary_key=True) # Field name made lowercase. claimnumber = models.CharField(db_column='ClaimNumber', max_length=50, blank=True, null=True) # Field name made lowercase. refinvoice = models.IntegerField(db_column='RefInvoice') # Field name made lowercase. accnumber = models.ForeignKey(Dimclient, models.DO_NOTHING, db_column='AccNumber') # Field name made lowercase. partnumber = models.ForeignKey(Dimproduct, models.DO_NOTHING, db_column='PartNumber') # Field name made lowercase. dateregistered = models.ForeignKey(Dimdate, models.DO_NOTHING, related_name='registration', db_column='DateRegistered', blank=True, null=True) # Field name made lowercase. dateinstalled = models.ForeignKey(Dimdate, models.DO_NOTHING, related_name='instalation', db_column='DateInstalled', blank=True, null=True) # Field name made lowercase. dateremoved … -
How to use Django For a microservice architecture. ? Is it efficient for an independant microservice?
I'm building few micro-service apps currently for learning purposes. I am happy with the micro nature of express framework and find it to be easier and good fit for independant micro-service environment with their own db. About django, I find it to be a little bigger and its not a micro framework. I'm thinking about how would a django framework fit into the micro-service world. My questions are, 1) Authentication, I tried out jwt based auth among few express apps, with expiry and refresh it seemed to flexible and nicer. Django has its own auth middle-wares and everything already, If I'm using django for independent micro services, Should i be writing custom middle-ware for each Service ? or If i Use django's admin and user management and put it as a service, then i should be still using custom middlewares in other independant django services ? 2) Is it inefficient ? Most of the django's full-stack features will not be used all the time, and needs few customization in each of it. Does it mean django is not a good fit for this ? I like django since it felt very solid and easy to develop apps, Django and Django … -
Profile's href attribute shows empty string on creation Django
After creating a new user, profile of user is created but it doesn't show default image. When I check view page source, src attribute show empty string like src=''. But when I go to profile link where I can update my profile then at that time it automatically load default image and and all the posts created by that user will get that default image. New user created and new post added by user when I click user profile, it automatically load default image and all posts created by that user get the default image. View page source mdoels.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] view.py @login_required def profile(request): Profile.objects.get_or_create(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(data=request.POST, instance=request.user) p_form = ProfileUpdateForm(data=request.POST, instance=request.user.profile, files=request.FILES) if u_form.is_valid() and p_form.is_valid(): … -
App not compatible with buildpack while push to heroku
I have tried all the solutions related to this issue. Nothing worked for me. I am using Django and I put Procfile,requirements.txt, runtime.txt file where manage.py is located. As I know this is the root directory of my project. Can anyone plz help me out? git push -f heroku master Enumerating objects: 718, done. Counting objects: 100% (718/718), done. Delta compression using up to 4 threads Compressing objects: 100% (522/522), done. Writing objects: 100% (718/718), 11.44 MiB | 314.00 KiB/s, done. Total 718 (delta 184), reused 682 (delta 172) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku-community/apt.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to ewallet-food. remote: To https://git.heroku.com/ewallet-food.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/ewallet-food.git' -
Django rest +vue.js excel file download corrupted
Hi Have problem with downloading excel file from serve by url. The file is corrupted etc.. below is my download function vue downloadFile() { axios({ url: this.scenario.file, method: 'GET', headers: {'Accept': 'application/vnd.ms-excel'}, responseType: "arraybuffer" }).then(response => { const url = window.URL.createObjectURL( new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}) ); const link = document.createElement("a"); link.href = url; link.setAttribute('download', `file.xlsx`); this.myresponseObject = response; // this line is just to save - url= window.URL.createObjectURL this.blobUrl=url; // this line is just to save response object fro checking document.body.appendChild(link); link.click(); window.URL.revokeObjectURL(url); link.remove(); }); }, in this code the url of the file which stored in the object scenario is - this.scenario.file = "http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" I have saved the "response" to look at it after download attempt: myresponseObject:Object config:Object adapter:ƒ xhrAdapter(config) data:undefined headers:Object maxContentLength:-1 method:"get" responseType:"arraybuffer" timeout:0 transformRequest:Array[1] transformResponse:Array[1] url:"http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" validateStatus:ƒ validateStatus(status) xsrfCookieName:"XSRF-TOKEN" xsrfHeaderName:"X-XSRF-TOKEN" data:ArrayBuffer headers:Object content-length:"1345" content-type:"text/html; charset=utf-8" date:"Mon, 08 Jun 2020 10:24:40 GMT" server:"WSGIServer/0.2 CPython/3.7.7" vary:"Cookie" x-content-type-options:"nosniff" x-frame-options:"DENY" request:XMLHttpRequest status:200 statusText:"OK" And url created by window.URL.createObjectUR is: "blob:http://127.0.0.1:8000/8a40ab70-1ce4-42d2-9176-935c10ef1526" Which is different from the original: url:"http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" Guess it should be like this. So, excel file downloaded is 2kb and is corrupted, formats or file extension is invalid Spent day on it..... Regards -
(Django) Having trouble wrapping my head around follower/target models in Models.py
I have just started with making a similar site to Pinterest and the site has follower/target system that I have barely any understanding of. So far, my models.py code is below: from django.db import models class User(models.Model): username = models.CharField(max_length=45, null=True) email = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200) nickname = models.CharField(max_length=45, null=True) target = models.ManyToManyField(self, through='Follow') follower = models.ManyToManyField(self, through='Follow') class Meta: db_table = 'users' class Follow(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='targets') target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') class Meta: db_table = 'follows' This code was made with reference to another StackOverflow thread Django models: database design for user and follower However, I am having trouble understanding how using "related_name='targets' in 'follower' and "related_name='followers'" in 'target' where I can't see any 'targets'(plural) or 'followers'(plural) in other areas of models.py Should I get rid of that related_name, since there is no such table called "followers" or "targets"? And if you spot major errors in my code or logic, can you tell me? Thanks! -
How to send javascript variables to django server using django?
I just started learning web development, My objective: To display selected columns of a CSV file in server on the client page So for some context on what I'm trying to do is, There are a few CSV files on my Django server. The client HTML page has a dropdown to select a file from a list of files and something like a filter for what columns to be displayed. I'm trying to get the values of the file and the filters using a button onclick method and send the values as an ajax request to the Django views.py. I will then use those variables to get the file, and the selected columns and use the render() function to render the HTML page dynamically My Questions: first of all, is what I'm doing the best way to handle my requirement? since I'm new to web-dev I don't know all the possible methods of achieving my requirement and I am doing it the only way I can think of. if what I'm doing is right, how do I send an ajax request to the server's views.py I can't seem to find the right code snippet/tutorial on how to send ajax request … -
No module named 'django.contrib.admin.templatetags.admin_static'
my django version is 3.0.5 and django-suit version is 0.2.28 but why does this error happen? the whole error information is as follows: File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\suit\admin.py", line 8, in <module> from suit.widgets import NumberInput, SuitSplitDateTimeWidget File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\suit\widgets.py", line 6, in <module> from django.contrib.admin.templatetags.admin_static import static ModuleNotFoundError: No module named 'django.contrib.admin.templatetags.admin_static' -
Scheduling my crawler with celery not working
Here I want to run my crawler with celery every 1 minute. I write the tasks as below and called the task in the view with delay but I am not getting the result. I run celery -A mysite worker -l info celery , rabbitmq broker , scrapy and django server in different terminals. The CrawlerHomeView redirects to the task list successfully by creating the task object.But the celery is not working It is throwing this error in the celery console ValueError: not enough values to unpack (expected 3, got 0) [2020-06-08 15:36:06,732: INFO/MainProcess] Received task: crawler.tasks.schedule_task[3b537143-caa8-4445-b3d6-c0bc8d301b89] [2020-06-08 15:36:06,735: ERROR/MainProcess] Task handler raised error: ValueError('not enough values to unpack (expected 3, got 0)') Traceback (most recent call last): File "....\venv\lib\site-packages\billiard\pool.py", line 362, in workloop result = (True, prepare_result(fun(*args, **kwargs))) File "....\venv\lib\site-packages\celery\app\trace.py", line 600, in _fast_trace_task tasks, accept, hostname = _loc ValueError: not enough values to unpack (expected 3, got 0) views class CrawlerHomeView(LoginRequiredMixin, View): login_url = 'users:login' def get(self, request, *args, **kwargs): frequency = Task() categories = Category.objects.all() targets = TargetSite.objects.all() keywords = Keyword.objects.all() form = CreateTaskForm() context = { 'targets': targets, 'keywords': keywords, 'frequency': frequency, 'form':form, 'categories': categories, } return render(request, 'index.html', context) def post(self, request, *args, **kwargs): form … -
How to efficiently reverse a QuerySet to iterate and save all objects in Django?
I have two models Book and Chapters with a foreign key relation. I'm trying to INSERT a Chapter in between an already existing chapters QuerySet that is ordered by order field. Example: Say I already have chapters 1 to 10. Now I need to add a new chapter between 1 and 2. So the new chapter should take the place of the current chapter 2 in the database. So all the chapters after 2 and including itself should have an order of order + 1 to make room for the new chapter. I think I am halfway to achieve this, but I am stuck when trying to slice the QuerySet (Negative indexing is not supported.). Documentation reference. My code: models.py class Book(PubDateUpdDateMixin, models.Model): title = models.CharField(max_length=80) slug = models.SlugField(unique=True, blank=True) description = models.CharField(max_length=3000) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='authors') class chapter(PubDateUpdDateMixin, models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='chapters') title = models.CharField(max_length=40) content = models.TextField(max_length=30000) slug = models.SlugField(unique=True, blank=True) order = models.IntegerField(null=True) views.py class ChapterCreate(LoginRequiredMixin, CreateView): login_url = reverse_lazy('login') model = Chapter slug_url_kwarg = 'book_slug' form_class = ChapterForm template_name_suffix = '-create' def get_object(self): return Book.objects.get(slug=self.kwargs['book_slug']) def get_context_data(self, **kwargs): context = super(ChapterCreate, self).get_context_data(**kwargs) context['book'] = Book.objects.get(slug=self.kwargs['book_slug']) return context def form_valid(self, form): book = self.get_object() … -
Retrieving Form data (from an A HTML page) in a python function pointing to a 'B' HTML page
I have an 'A' HTML page (URL: AppName/A) with an A_Form. After submitting the A_form, the user shall go to the 'B' HTML page (URL:AppName/A/B) where other forms should pop up depending on the data of the A_Form submitted earlier. After submitting the A_Form data, i want to get these data in the python parameter function pointing to the 'B' HTML page (URL:AppName/A/B). In, 'A' HTML code, i have directed the data form to the 'B' HTML URL: {% csrf_token %} {{ A_Form.as_p}} <input type="submit" value="Submit"/> </form> In views.py, A HTLM python function code: def Afunction_view(request): AForm = A_Form() if request.method == 'POST': A_form_result = A_Form(request.POST) BForm = B_Form() CForm = C_Form() return render(request, 'AppName/B.html'{'BForm':BForm,'CForm':CForm}) else: AForm = A_Form() return render(request, 'AppName/A.html'{'AForm':AForm}) In views.py, 'B' HTML python function code:: def Bfunction_view(request): BForm = B_Form() CForm = C_Form() if request.method == 'POST': else: BForm = B_Form() CForm = F_Form() return render(request, 'AppName/B.html'{'BForm':BForm,'CForm':CForm}) The problem with this approach is that after the form in the 'A' HTML page is submitted the user is directed to the 'B' HTML page and the B function is exectued with values on the request parameter... so is it more convenient to put all forms in the … -
How Can I split datetime field field django rest frameworks [closed]
I've used datetime field in my dajngo model. but it was throwing invalid datetime error. so i want to split datetime in two field date field and time field with out changing model. some things like this https://gist.github.com/toshism/1571984 It was working perfectly in django template, But i didn't know to accomplish this features in django rest frameworks. -
Django download fiile
I'm quite new to using Django and I am trying to develop a website where the user is able to download a report file, these files are then stored in a folder static/doc/location.txt. I have in management/commands from django.core.management.base import BaseCommand, CommandError import json import os Print the report def service_area_by_region_top_category_count(self, services_in_service_area_by_region, region_name, limit): print('#### ' + region_name + ':') data_folder = "static\\location\\" file_to_open = data_folder + "location.txt" with open(file_to_open, "a") as file_prime: file_prime.write(str('#### ' + region_name + ':')+ '\n') region_queryset = services_in_service_area_by_region[region_name] data_folder = "static\\location\\" file_to_open = data_folder + "location.txt" with open(file_to_open, "a") as file_prime: for category in Category.objects.all().annotate( service_count=Count(Case( When(services__in=region_queryset, then=1), output_field=IntegerField(), )) ).order_by('-service_count')[:limit]: print(" - " + category.name + ": " + str(category.service_count)) file_prime.write(str(" - " + category.name + ": " + str(category.service_count))+ '\n') Everything working well but the file instead to be saved on the path static/doc/location.txt is saved on the root of the site with the name (static\location\location.txt). txt file created -
Running mysql and django inside docker-compose fails. Why is it unable connect to database?
version: "3.0" services: backend: build: ./backend ports: - "3600:8000" depends_on: - mysql redis: image: redis mysql: image: mysql:5.6 environment: - MYSQL_DATABASE=django-app - MYSQL_ROOT_PASSWORD=password This is my docker-compose.yml #!/bin/sh cd src rm *.sqlite3 python manage.py makemigrations python manage.py migrate daphne -b 0.0.0.0 -p 8000 literature.asgi:application This is my docker entrypoint for the backend. But whenever I do docker-compose up. It fails to migrate the database succesfully and I get the error saying "Can't connect to mysql". But if I restart just the django-app container then it works fine. All migrations are finished and django-admin works. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django-app', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'mysql', 'PORT': '3306', } } It works fine if I use SQLite instead. -
Insert comment form on Post detail page. django- blog app
I have trying this from 2-3 days. I want to insert my comment form on post detail page. My form is not showing on that page. I have followed this tutorial for the comment model. I have another app for account which is used for signup purpose. model.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.title def publish(self): self.published_date = timezone.now() self.save() def approved_comments(self): return self.comments.filter(approved_comment=True) class Comment(models.Model): post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(verbose_name ='Username',max_length=200) text = models.TextField(verbose_name ='Comment') email = models.EmailField(default='') created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text view.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) @login_required def comment_approve(request, pk): comment = get_object_or_404(Comment, pk=pk) comment.approve() return redirect('post_detail', pk=comment.post.pk) @login_required def comment_remove(request, pk): comment = get_object_or_404(Comment, pk=pk) comment.delete() return redirect('post_detail', pk=comment.post.pk) urls.py path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'), path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('post/<int:pk>/', views.post_detail, name='post_detail'), … -
download a dynamic image with content in django
this will be the output of my work as of done as shown in the above image, the picture and the content on the image is **Purely dynamic**. this is what I used to write to make it happen here my question is that, how can we download the image including the content on it. waiting for the best response from the community. pls, help with this issue. -
How to update table with jquery in django?
I have created in my django app a table in which in the last two columns I have insert an edit and delete button. To do that I have created a partial_book_list.html that contains the body of my table with all data. In other words: base <table class="table table-sm" id="myTable" style="width:100%"> <tbody> {% include 'commesse/includes/partial_book_list.html' %} </tbody> partial_book_list.html {% for commessa in commesse %} <tr> <td>{{commessa.codice_commessa}}</td> <button type="button" class="btn btn-warning btn-sm js-update-book" data-url="{% url 'book_update' commessa.id %}"> </button> <button type="button" class="btn btn-danger btn-sm js-delete-book" data-url="{% url 'book_delete' commessa.id %}"> </button> </td> </tr> {% endfor %} After that I have created a modal form with the following jQuery save function: var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#myTable tbody").html(data.html_book_list); $("#modal-book").modal("hide"); } else { $("#modal-book .modal-content").html(data.html_form); } } }); return false; }; data.html_book_listi is given my the following views: def save_book_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True commessa = Informazioni_Generali.objects.all() data['html_book_list'] = render_to_string('commesse/includes/partial_book_list.html', { 'commessa': commessa }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) In other … -
Has anyone tried django-friendship package? Problem following an user
I recently installed this package to my site to add a follower system but is not working. This is my views.py i defined the context 'users' who takes all the site users and exclude current login user and then i defined the context 'following' who takes all the following users. views.py from django.contrib.auth.models import User from friendship.models import Friend, Follow, Block class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name='posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['users'] = User.objects.exclude(id=self.request.user.id) context['following'] = Follow.objects.following(self.request.user) def change_follower(request, operation, pk): follow = User.objects.get(pk=pk) if operation == 'add': Follow.objects.add_follower(request.user, other_user, follow) elif operation == 'remove': Follow.objects.remove_follower(request.user, other_user, follow) return redirect(request.META['HTTP_REFERER']) urls.py from django.urls import path, re_path from .views import PostListView from . import views app_name='blog' urlpatterns = [ re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.change_follower, name='change_follower'), ] The button to follow a user is not working. I have tried this to follow a user and then show the following list but is not working: Html <h2>Users list</h2> {% for user in users %} {% if user in following %} {{ user.username }} <a href="{% url 'blog:change_follower' operation='remove' pk=user.pk %}"><button type="button">Following</button></a> {% elif not user in following %} <a href="{% url 'blog:change_follower' operation='add' pk=user.pk … -
How to serialize user permissions in Django Rest Framework?
I'm building an application with a Django rest backend and a React frontend and working on authorization and authentication. Authentication works well, but I'm a bit stuck when it comes to telling the frontend what the user is authorized to do in terms of add/edit/view/delete for a model. For example, if a user cannot edit a story, I don't want to display the 'Edit Story' button. When working through the Django documents, I consider it easiest to send the user's permissions from Django backend to the React frontend. Therefore I want to serialize the user permissions. This is my View: class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_permissions(request): logged_in_user = request.user return Response(data=logged_in_user.get_all_permissions()) def get_object(self): return self.request.user This is my Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'user_permissions') When i call the UserAPI the field user_permissions is empty. "user": { "id": 35, "username": "HII", "user_permissions": [ ] } I wonder how i can not access the user_permission via my API. I'm happy for any hint and clarification.