Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrations duplicate/already exists problem
I have a fairly large code base in django, with several applications, and at some point I had a problem: every time I change or add models and try to do a migration, an error appears: django.db.utils.ProgrammingError: relation "appname_modelname" already exists. The problem has been going on for some time - the migration file is always created under the same number - 0114 (I could not find this file, by the way), and all new fixes are recorded in it along with the previous ones, which is why the problem grows, like snowball. I did not want to delve into the solution and just manually removed all the innovations from the database - everything that caused the "already exists" conflict to appear. So, in order for the migration to succeed, I had to manually delete all models or table fields that I created after this problem appeared. But now I'm starting to work in prod with this code and fill it with data, and it is no longer possible to delete all the data from the corresponding tables. I have no idea why this problem appeared and how to solve it and would really appreciate your advice. I tried to … -
DRF Serializer - Accept field but don't use it in `create` or `update`
I have a model Message that has a FileField. My API accepts files in Base64 encoding so they can be sent alongside other data. To know a filename and an extension, there is one more field attachment_filename in the serializer that is not a model field. It is used inside Base64Field. I want to be able to validate if there are both attachment_filename , attachment, or none of them. The problem is that if the attachment_filename is read-only, it is not present in validate - data variable. On the other hand, if it's required=False, allow_null=True, the serializer raises an error when creating a message: TypeError: ChatMessage() got an unexpected keyword argument 'attachment_filename' Code: class Base64File(Base64FileField): # todo make accept a list of extensions (finite eg. pdf, xlsx, csv, txt ) ALLOWED_TYPES = ['pdf', 'xlsx', 'png', 'jpg', 'jpeg', 'docx', 'doc', 'zip'] def get_file_extension(self, filename, decoded_file): extension = self.get_full_name().split('.')[-1] return extension def get_file_name(self, decoded_file): attachment_filename = self.get_full_name() return '.'.join(attachment_filename.split('.')[:-1]) def get_full_name(self): return self.context['request'].data['attachment_filename'] # todo validate name class ChatMessageSerializer(serializers.ModelSerializer): attachment = Base64File(required=False) attachment_filename = serializers.CharField(required=False, allow_null=True) class Meta: model = ChatMessage fields = '__all__' def validate(self, data): """ Validation of start and end date. """ attachment = data.get('attachment') attachment_filename = data.get('attachment_filename') if … -
why in my pycharm IDE template tags intellisense or html tags intellisense do not work?
there is no suggestion for template tags or html tags what should i do ? -
Python | Sum values when data is repeated on other list
So, this is something a little crazy, but I hope it has a solution. I am creating a web application to check sales on a publishing house. Up until now I got everything good: I created a model for products (books), for sales... Everything OK. I am using charts.js to display data. Here is the code for the view: def top_sales_view (request, *args, **kwargs): labels = [] #list for charts.js sold_copies = [] #list for charts.js billed = [] #list for charts.js books_all = Product.objects.all() #get all data from books for book in books_all: book_data=Sale.objects.filter(book = book.id ) #get all sales per book quantity_list = [] #set list of each quantity per sale income_list=[] #set list of each income per sale for data in book_data: quantity = data.quantity income = float(data.final_price) quantity_list.append(quantity) #list all quantity sales per book copies=sum(quantity_list) #sum all quantity sales per book income_list.append(income) #list all income sales per book billing=sum(income_list) #sum all income sales per book book ={ 'id': book.id, 'title':book.title, 'cost_center': book.cost_center, 'data' : { 'copies': copies, 'billing' : billing } } #------------- PARA CHARTS.JS ------------- if book['cost_center'] not in labels: #chech if cost_center is not on the list labels.append(book['cost_center']) #if it isn't, add it if … -
Is there a way to create a django model foreignkey field with variable choices?
Let's say I have three models device, mechanical and digital. In the device model I have a field type. The type field needs to be in a foreign key relationship with either mechanical or digital model which will be determined by the data. Is there any way to create the type field in such a way that the model in which the foreign key relationship is to be done can be chosen manually. Something like: type = models.ForeignKey(to=Choices) where the Choices could be digital and mechanical. I have tried implementing generic foreign keys but my database schema is a bit complex so that would be very difficult to maintain. Is there any other way in django that I can do the above? -
Docker - I have a django application running inside a container on my local machine. I want to connect the app to Postgres DB on my machine
What am I doing: sudo docker build -t my_service:latest . sudo docker run -p 8000:8000 -d sso_service:latest I have added my docker IP range 172.17.0.0/16 to pg_hba.conf I have tried using --network=host with docker run -
Django: Allowing user to click an accept or reject button on each item in a list in Django
I'm working on a website where a list of a varying number of matches with organisations is made for each user. I was wondering if there was a way to display to a user each element in the list with an accept and reject button next to each element so that the user can accept or reject the matches? I found some people recommending pagination but I couldn't get that to work with the list having a variable number of items. Thanks in advance. -
Cors error happening on a simplejwt authenticated webpage
I have used simplejwt in my code and I also have added django-cors-headers to my project to allow frontend development. the problem is that I have 2 APIs that need authentication to allow users to work with them and I can not send a request to these two APIs on the front end and I get the following error: Access to fetch at 'http://localhost:8000/api/user/myapi' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-auth-token is not allowed by Access-Coontrol-Allow-Headers in preflight response Here are the important parts of my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] ALLOWED_HOSTS=['*'] CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=10), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'userID', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } and here are my views.py and serializers.py # Serializers.py class myAPISerializer(serializers.ModelSerializer): class Meta: model = someModel fields = ('user', 'someField',) read_only_fields = ('user',) def create(self, validated_data): ... #Some changes return super().create(validated_data) # Views.py class PaymentView(generics.CreateAPIView): serializer_class = PaymentSerializer … -
django db with ssh tunnel
Is there a python native way to connect django to a database through an ssh tunnel? I have seen people using ssh port forwarding in the host machine but I would prefer a solution that can be easily containerized. -
NoReverseMatch in Ajax Reorder
I am running into the following issue while implementing an Ajax reorder view into my app. Essentially, my app is just a table that you can filter, reorder, and operate CRUD functions within. When I applied the filter view, the reordering doesn't work anymore. You should be able to update the ranking of each row based on dragging the row up/down ajax: class AjaxReorderView(View): def post(self, *args, **kwargs): if self.request.is_ajax(): data = dict() try: list = json.loads(self.request.body) model = string_to_model(self.kwargs['model']) objects = model.objects.filter(pk__in=list) # list = {k:i+1 for i,k in enumerate(list)} for object in objects: object.rank = list.index(str(object.pk)) + 1 model.objects.bulk_update(objects, ['rank']) # for key, value in enumerate(list): # model.objects.filter(pk=value).update(order=key + 1) message = 'Successful reorder list.' data['is_valid'] = True # except KeyError: # HttpResponseServerError("Malformed data!") except: message = 'Internal error!' data['is_valid'] = False finally: data['message'] = message return JsonResponse(data) else: return JsonResponse({"is_valid": False}, status=400) pick_list: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder … -
Got AttributeError when attempting to get a value for field `email` on serializer `VerifyAccountSerializer`
I am trying to create a verify API, which generates a random token and map it with user AttributeError at /api/verify/ Got AttributeError when attempting to get a value for field email on serializer VerifyAccountSerializer. The serializer field might be named incorrectly and not match any attribute or key on the AllVerifyOrForgotToken instance. Original exception text was: 'AllVerifyOrForgotToken' object has no attribute 'email'. models.py class AllVerifyOrForgotToken(models.Model): user = models.ForeignKey( User, verbose_name='User', on_delete=models.CASCADE ) token = models.CharField(max_length=32, unique=True) def __str__(self): return str(self.token) serializers.py class VerifyAccountSerializer(serializers.ModelSerializer): email = serializers.EmailField() class Meta: model = AllVerifyOrForgotToken fields = ('email',) def create(self, validated_data): email = validated_data.pop('email') return AllVerifyOrForgotToken.objects.create(**validated_data) viewsets.py class VerifyViewset(mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = (AllowAny,) queryset = AllVerifyOrForgotToken.objects.all() serializer_class = VerifyAccountSerializer def perform_create(self, serializer): email = serializer.validated_data['email'] try: user = User.objects.get(email=email) serializer.save( token=token_generator(32), #function to generate random string user=user, ) except User.DoesNotExist: raise APIException(detail='User does not exist') -
select data in a time interval in minutes django orm
How are you? I need some help please. I am working in Django and I need to make a query of all sales between 00:00 and 00:30 minutes, so every 30 minutes I need to see the sales. I was putting together something like this but it is not working. SalesOrder.objects.annotate(Sum('subtotal')).filter(created_at__time__range= ('00:00:00:00', '')).filter(created_at__time = hour_now) This is a SQL query that delivers the correct data. SELECT sum(subtotal) as tot FROM sales_salesorder ss where extract(minute from created_at::time) between 31 and 59 and created_at::date = now()::date and extract(hour from created_at) = extract(hour from CURRENT_TIME); The problem is that I can't leave the sql query because I have to pass it through a for loop to return the data, that's why the most effective way is to use the ORM, that's the reason of my question. -
AttributeError at /coordinator 'Coordinator' object has no attribute 'agent'
Expected Outcome: I want to query the parent objects which are relevant to the coordinator. Please help on how I can achieve such. The Error is occuring after running the following queryset, user.coordinator.agent.parent_set.all() Models class Coordinator(models.Model): user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) region = models.CharField(max_length=15, null=True, blank=True, choices=REGION) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) created_at = models.DateTimeField(auto_now_add=True) class Agent(models.Model): user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) coordinator = models.ForeignKey(Coordinator, null=True, blank=True, on_delete=SET_NULL) region = models.CharField(max_length=15, null=True, blank=True, choices=REGION) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True,) address = models.TextField(null=False, blank=False) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) created_at = models.DateTimeField(auto_now_add=True) class Parent(models.Model): agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=SET_NULL) surname = models.CharField(max_length=150, null=False, blank=False) first_name = models.CharField(max_length=150, null=False, blank=False) other_name = models.CharField(max_length=150, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) region = models.CharField(max_length=15, null=True, blank=True, choices=REGION) dob = models.CharField(max_length=10, null=False, blank=False) -
How to get a specific field within another django model?
I want to be able to get a specific field in a django model which is referenced through foreignkey. Here is my views.py file: def add_watchlist(request, name): stuff = Watchlist() thing = listing.objects.get(title = name) id = thing.id stuff.listing_id = id stuff.user = request.user stuff.save() things=Watchlist.objects.filter(user = request.user) return render(request, "auctions/watchlist.html",{ "items":things }) Here is my models.py: class User(AbstractUser): pass def __str__(self): return f"Cool kid {self.username}" class listing(models.Model): creator=models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") price=models.IntegerField() title=models.CharField(max_length=64) description=models.CharField(max_length=2056) src=models.CharField(max_length=1024, blank=True) def __str__(self): return f"{self.title} goes for a price of {self.price}, put forth by {self.creator} and here's the description: {self.description}" class bid(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidder") price=models.IntegerField() def __str__(self): return f"{self.user} bid {self.price}" class comment(models.Model): title=models.CharField(max_length=64) user=models.ForeignKey class Watchlist(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") listing=models.ForeignKey(listing, on_delete=models.CASCADE, related_name="listing") def __str__(self): return f"{self.user} adds {self.listing.title} to the watchlist" I hope to be able to find the title of the listing model and display it through html on watchlist. So far, I've only been able to display the whole listing model. Here is my watchlist.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Watchlist</h2> {% for item in items %} <ul> {{item.listing}} </ul> {%endfor%} TODO {% endblock %} {{item.listing.title}} is what I want, but that does not work. I'm a beginner … -
Right-click while the page is running Ajax
I have a table that loads empty (no rows) and then I run an Ajax call -inside a django for-loop- to populate the table with data from a python function that each time returns one row/item. The reason I am doing this is to allow for users to be able to interact with the table while the data are loading on the background (especially useful when loading big data). I also have a jquery function that when I right-click on a row, it produces a context menu for that specific row. The problem is that the right click does not work until all data in the table are loaded. How can I make it so that the right-click script can be ran while the page is still loading? I suspect that it could have something to do with the right-click script being inside a $(document).ready(); function, but even when I remove this, nothing changes. I still cant trigger the right-click function while the Ajax is running in the background. Anyone has any ideas? PS: I found this answer to something similar: https://stackoverflow.com/a/28621626/10895906 which mentions that an Ajax call needs a time out to allow for interaction to run, but the … -
Sheduled Data Scraping of Exel local file with Django
I am currently trying to write a script that import automatically data from an excel file to a model in django, but the import task must be periodic (every day), I have already tried to make it by django import-export but I couldn't find a way to schedule this task, can someone help me or can show me on discord, Thank you. -
Broken image is shown when fetched from mysql database in django
Iam trying to fetch image from my database but the image is broken I don't know correctly what I missed Please give me a solution. VIEWS.PY def display_images(request): allimages = GetImage.objects.all() return render(request, 'show.html', {'images': allimages}) MODELS.PY class GetImage(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to="media/") class Meta: db_table = "gallery" URLS.PY from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('show', views.display_images), ] if settings.DEBUG: urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) SETTINGS.PY STATIC_URL = 'static/' STATIC_ROOT=os.path.join(BASE_DIR,'static') MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') SHOW.HTML !DOCTYPE html> <html lang="en"> <head> <title>Django Display Images</title> <meta charset="utf-8"> <link rel="stylesheet" .min.css"> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Title</th> <th>Image</th> </tr> </thead> <tbody> {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/> </td> </tr> {% endfor %} </tbody> </table> </div> </body> </html> Please give one solution regarding about this fetching images. -
ThumbnailerJSONSerializer to representation returns self.context['request'], instance, KeyError: 'request'
I have models.py update_data = dict(topic=topic, subtopic=subtopic, chat_id=chat.id, message=VisitorMessageSerializer(m).data) serializers.py class VisitorMessageSerializer(NonNullModelSerializer): photo = ThumbnailerJSONSerializer(alias='core.Message.photo', read_only=True) class Meta: model = Message fields = ['id', 'created_at', 'text', 'photo', 'author_agent', 'document', 'reply_markup', 'is_read', 'has_author', 'clientside_id'] here is a NonNullModelSerialzer: class NonNullModelSerializer(serializers.ModelSerializer): def to_representation(self, instance): result = super(NonNullModelSerializer, self).to_representation(instance) return OrderedDict([(key, result[key]) for key in result if result[key] is not None and result[key] != {}]) I can't get update_data because to_representation returns KeyError to_representation self.context['request'], instance, KeyError: 'request' -
How to loging to django with login form? With or without Ajax
Problem: If user is loggedin, I want to show greet user else show the form and when the valid data is submitted, log in the user and show greet message. I am trying to pass the data on submit and update the user status to login. I tried with and without ajax but with both ways I could not figure out solution. Could you please help me why its failing? And how I can solve this? HTML Form: {% if user.is_authenticated %} <h5 class="title billing-title ls-10 pt-1 pb-3 mb-0"> Welcome {{ user.username }}! </h5> {% else%} <div class="login-toggle"> Returning customer? <a href="#" class="show-login font-weight-bold text-uppercase text-dark">Login</a> </div> <form class="login-content" name="ajaxLogin" method="POST" action="{% url 'ecommerce:ajaxlogin' %}"> {% csrf_token %} <p>If you have shopped with us before, please enter your details below. If you are a new customer, please proceed to the Billing section.</p> <div class="row"> <div class="col-xs-6"> <div class="form-group"> <label>Username or email *</label> <input type="text" class="form-control form-control-md" name="username" id="id_email" required> </div> </div> <div class="col-xs-6"> <div class="form-group"> <label>Password *</label> <input type="password" class="form-control form-control-md" name="password" id="id_password" required> </div> </div> </div> <div class="form-group checkbox"> <input type="checkbox" class="custom-checkbox" id="remember" name="remember"> <label for="remember" class="mb-0 lh-2">Remember me</label> <a href="#" class="ml-3">Lost your password?</a> </div> <button class="btn btn-rounded btn-login" … -
Django objects.all() not updating without server restart [closed]
django objects.all() only seems to be updating after server restart. For example, I would make a category called 'Education' and it shows up on the admin site, but when I'm using in the form, it will not show up unless I restart the live server. forms.py: def tuplelistmaker(list): output = [] for x in list: newtuple = (x.pk, x) output.append(newtuple) print(output) return output class PostForm(forms.Form): title = forms.CharField(max_length=100, label='Post Title') short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) content = forms.CharField(widget=CKEditorWidget()) status = forms.NullBooleanField(label='Ready to Publish?') image = forms.ImageField(label='Select a cover image:') captioned_image = forms.ImageField(label='Select a captionable image:') caption = forms.CharField(max_length=200) category = forms.ChoiceField(choices = tuplelistmaker(list(PostCategory.objects.all()))) embed = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100})) tags = forms.CharField(widget=forms.Textarea(attrs = {"rows":1, "cols":150})) models.py: class PostCategory(models.Model): category = models.CharField(max_length=100) categorySlug = models.SlugField(max_length=100) def __str__(self): return self.category class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts') short_description = models.TextField() updated_on = models.DateTimeField(auto_now=True) content = RichTextField() created_on = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=Status, default=0) cover_image = models.ImageField(upload_to = 'coverimages', null =True, blank = True) captioned_image = models.ImageField(upload_to = 'captionedimages', null=True, blank = True) caption = models.CharField(max_length=300) featured = models.IntegerField(choices=Featured, default=1) category = models.ForeignKey(PostCategory, on_delete=models.CASCADE, null=True, blank=True) embedded_code = models.TextField(blank=True, null=True, default='null') tags = models.TextField(blank=True, null=True) class Meta: … -
filtering in serializers Django rest framework
I am new to Django, in my probject a room has different statues for example: registered, available, each status has a start date, I have to get the start_date when the status is registered. how can I do that in serializer? Thanks in advance! in model.py: class RoomStatus(models.Model): room = models.ForeignKey(Room, on_delete=models.DO_NOTHING, related_name='rooms') class RoomStatusChoices(models.IntegerChoices): REGISTERED = 1 RESERVED = 2 AVAILABLE = 3 room_status = models.SmallIntegerField(choices=RoomStatusChoices.choices, default=RoomStatusChoices.AVAILABLE) start_date = models.DateTimeField(default=timezone.now()) In serializers.py: class RoomStatusSerializer(serializers.ModelSerializer): class Meta: model = RoomStatus fields = ['id', 'start_date'] class RoomSerializer(serializers.ModelSerializer): rooms = RoomStatusSerializer(many=True) class Meta: model = Room fields = ['id', 'rooms'] in views.py: class RoomViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet, UpdateModelMixin): queryset = Room.objects.all() serializer_class = RoomSerializer -
Django - Change client encoding from WIN1252 to UTF8
So I have my Django application deployed on a Heroku server and when I try to query for Post I get this. How I query // Command to get into postgres heroku pg:psql // Query SELECT * FROM posts; What I get back ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252" I'm decently sure what is happening is that someone created a post where the body has an emoji in it. I'm using Postgresql it supports UTF8 for storing. I'm just not sure what part of Django is causing it to encode to WIN1252 instead of UTF8. How change client encoding from WIN1252 to UTF8 models.py class Post(models.Model): uuid = models.UUIDField(primary_key=True, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) Setup: Postgresql Django 3.2.9 -
Dynamic URL in DRF Modelviewset
I'm working on a url where I'm filtering the News according to category. So all i am doing is passing the name of the category in url in this manner 127.0.0.1:8000/news/category/sports/ or 127.0.0.1:8000/news/category/entertainment/. Here's my code snippet views.py class CategoryAPI(viewsets.ModelViewSet): serializer_class = CategorySerializer # lookup_field = 'slug' # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def get_queryset(self): category = Category.objects.all() return category @action(methods=['get'], detail=False, url_path=r'list/(?P<name>[\w-]+', url_name='category') def get_category(self, request, category=None): return Category.objects.all().order_by(name) class PostAPI(viewsets.ModelViewSet): serializer_class = PostSerializer # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def get_queryset(self): news_post = News.objects.all() return news_post serializers.py class PostSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) dislikes = serializers.SerializerMethodField(read_only=True) views = serializers.SerializerMethodField(read_only=True) # author = serializers.StringRelatedField() # category = serializers.StringRelatedField() def get_likes(self, obj): return obj.likes.count() def get_dislikes(self, obj): return obj.dislikes.count() def get_views(self, obj): return obj.views.count() class Meta: model = News fields = ('id','category','post_type','title','content','hash_tags','source','author','views', 'likes','dislikes','status') class CategorySerializer(serializers.ModelSerializer): posts = PostSerializer(many=True, read_only=True) parent = serializers.StringRelatedField() class Meta: model = Category fields = ['name', 'slug', 'parent','posts'] urls.py router = DefaultRouter() router.register('news', views.PostAPI, basename='news'), router.register('category', views.CategoryAPI, basename='category'), router.register('news-images', views.NewsImageAPI, basename='news-image'), router.register('comment-room', views.CommentRoomAPI, basename='comment-room'), router.register('comment', views.CommentAPI, basename='comment') urlpatterns = [ ] urlpatterns += router.urls So all I want to do is instead of passing the name of the category in the url, how can I create it dynamically. Otherwise … -
I made an emailing client using django for backend and js at the frontend. 2 users were logged in at the same time. A weird issue happened
Question Contd.... So my email host was smtp.gmail.com. One registered user logged in with correct credentials of their gmail account whereas the other had not given a correct password during registration but was logged in. So when user 2(with wrong credentials) clicked on the send button, with me as the recipient of the mail, I received a mail from user 1's account. Requesting some insights on the problem. Views.py given below from django.http.response import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse from django.shortcuts import redirect, render from django.urls import path from Email.regForm import registrationForm from Email.loginForm import loginForm from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.core.mail import send_mail import json from django.conf import settings #Create your views here. user = None password = None def loginPage(request): form = loginForm() if request.method == 'POST': global user user = authenticate(request,username = request.POST['email_id'],password = request.POST['password']) try: if user is not None: global password password = request.POST['password'] print(password) settings.EMAIL_HOST_PASSWORD = password print(type(user)) print(user.get_username()) login(request,user) return redirect("https://mailitappbyrb.herokuapp.com/emailpage") else: return HttpResponseBadRequest("Invalid Attempt") except: return Http404("Something Went Wrong..Please Try Again") return render(request,'loginpage.html',context={'form':form}) def registrationPage(request): form = registrationForm() if request.method == 'POST': form = registrationForm(request.POST) if form.is_valid(): try: User.objects.create_user(username … -
Getting all the objects in the JavaScript from Django
I want to get all my object models from the database and store them in someway, the model I have is: class Device (models.Model): patientId = models.IntegerField(unique=True) deviceId = models.CharField(unique=True,max_length=100) hour = models.DateTimeField() type = models.IntegerField() glucoseValue = models.IntegerField() I'm sending them in views.py: device_list = list(Device.objects.all()) context = {"filename": filename, "deviceList": device_list, } In JS I managed to get each object like that: {% for item in deviceList%} console.log( "{{item}}" ); {% endfor %} What I want is to store those objects in some way, but I don't really know how, because they are coming like that Model object (1).