Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uncaught SyntaxError: Unexpected identifier pls help me
I tried to display the message but it won't display This is views def allmessage(request, room): room_details = Room.objects.get(name=room) messages = Message.objects.filter(room=room_details.id) return JsonResponse({"messages":list(messages.values())}) This is display method This link doesn't work /getMessages/{{room}}/ in my terminal $(document).ready(function(){ setInterval(function(){ $.ajax({ type: "GET" url: "/getMessages/{{room}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='chat-box'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('There is an error') } }); },1000); }) </script> and also have this problem pls help thank you -
Error when trying to access an item in a for loop
Greetings all I'm trying to get a value if it is equal to a string in looping through items. But I'm getting error "Dictionary entries must contain key/value pairs" and I don't know how to fix that. I'm new to python programming and I'm struggling to find information of how it should be done. I'm using python3.x My code looks like this for index, debtor in enumerate(case.get_debtors): if debtor.type==1: context = { "recipientName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''), "debtorRole": "Длъжник", "debtorAddress": debtorAddress, "publicExecutorDefaultBankAccount": "ygvyvb", "courtStaff": f"{case_details.systav}".replace('None', ''), "courtName": f"{case_details.courtName}".replace('None', ''), "archNumber": case.id, "debtorName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''), "creditorName": f"{creditor.first_name} {creditor.middle_name} {creditor.last_name}".replace('None', ''), #creditor.type==2 "creditorAddress": creditorAddress, "executionListDate": executionListDate, "exListIdentifier": exListIdentifier, "amount": amount, "amountDate": amountDate, "agreementInterest": agreementInterest, "penaltyInterest": penaltyInterest, "expences": expences, "taxPublicExecutor": taxPublicExecutor, "brokerage": brokerage, "measuresSum": measuresSum, if debtor(index).postcode1=="1000": "recipientNameNAP": "ТД НА НАП – СОФИЯ", "recipientAddressNAP": "Адрес: ул.„Аксаков” № 21 1000 София", "BASE_DIR": f"{settings.BASE_DIR}".replace("""\\""", "/"), } Please help me. I know it is something simple, but I can't find a solution -
Trouble with Django Channels AllowedHostsOriginValidator
Everytime I use the AllowedHostsoriginValidator I'm unable to get a websocket connection. it immediately handshakes, rejects and disconnects : (where 'my ip' is my ip) WebSocket HANDSHAKING /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] WebSocket REJECT /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] WebSocket DISCONNECT /ws/joingroup/8598969d-3dfa-4017-849c-dcbb71c1f9f0/ [my ip:62745] application = ProtocolTypeRouter({ # (http->django views is added by default) "http": get_asgi_application(), 'websocket': AllowedHostsOriginValidator( URLRouter( uppicdoapp.routing.websocket_urlpatterns ) ) , }) my settings.py file i have: ALLOWED_HOSTS = ['127.0.0.1', '10.0.2.2', 'my ip'] now when I remove that allowedhostsoriginvalidator, I am able to connect! Is there something I'm missing for the ALLOWED_HOSTS setting? -
I want find a point in between given points rectangle using python if possible in django
Here in my given points i was tried to match from django query, please help me to best way. y=800.2816162109375 1200, 750 block_list = Block.objects.filter( Q(block_coordinates__topRight__y__gte=y)&Q(block_coordinates__botRight__y__gte=y)& Q(block_coordinates__topLeft__x__gte=x)&Q(block_coordinates__topRight__x__lte=x)& Q(block_coordinates__topLeft__y__lte=y) | Q(block_coordinates__botLeft__y__gte=y) ).values('block_id','block_coordinates') ``` -
Program 'pip.exe' failed to run: The file or directory is corrupted and unreadable
While I was trying to download Django, I got this error that can be found in here. These are some clues for you: Before I downloaded django, I activated the virtual environment but maybe something went wrong with it because I couldn't see anything changed after activating. And one more thing is I'm trying to download Django in my external USB. -
django get id for traverse a list
i want to convert my list into dict to have my id so i try this in my views def img2(request): posts = Post.objects.all() i=[] for p in posts: print(p.id) i.append(p.id) #post={'id':str(p.id)} #print(i) '''def Convert(lst): res_dct = {str(lst[i]): lst[i] for i in range(0, len(lst), 1)} return res_dct # Driver code d=Convert(i)''' d = {str(i[k]): i[k] for k in range(0, len(i), 1)} print(d) for j in d: print(j) return render(request, 'imgg.html', d) then i want to display every id in html and this is my html file: test {% for n in d %} {{n}} {% endfor %} so.. nothing happened and i don't know what's the problem some help plz and thx a lot in general i have a model form post and another one for images with foreignkey and i want to display every post with first image uploded so i have my db with post and images but i never get the first image to display at home page then i try to make a dict with all post_id with for i will try to display every single image_post for her post if u have another method i will be thankfull ^^ -
Getting error when attempting to add items into the database
So, I am actively trying to create categories with subcategories. My current app is listings, and the idea is to create a ManyToManyField inside my Listing models. Here is my code inside models.py. from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=150, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Blist(models.Model): name = models.CharField('Business Name', max_length=250) address = models.CharField('Address', max_length=300) city = models.CharField('City', max_length=100) zip_code = models.CharField('Zip Code', max_length=10) phone_number = models.CharField('Phone Number', max_length=20) web = models.URLField('Website') def __str__(self): return self.name But when I go into the shell to add items into the category, I'm getting errors: django.db.utils.ProgrammingError: column listings_category.name does not exist LINE 1: SELECT "listings_category"."id", "listings_category"."name",... What am I doing wrong here? -
Adding dictonary values while using HttpResponseRedirect
I want to redirect to the existing page and display a queryset which would be determined based on the values submitted via the form. The dictionary values I get from function get_context_data display correctly. The dictionary values I try and add in the post function do not display correctly. def post(self, request, *args, **kwargs): RoomBookingsForm = BookRoomsForm(request.POST or None) self.object = self.get_object() # assign the object to the view context = self.get_context_data( *args, **kwargs) context.update({'room_type_queryset': RoomType.objects.all().filter()}) print("all context values") print(context) if request.method == 'POST': return HttpResponseRedirect(self.request.path_info, context ) As well as context.update I also tried context['room_type_queryset'] = RoomType.objects.all().filter() Based on the two print statements above I got all context values {'object': <AmericanHotel: Caesars Palace>, 'americanhotel': <AmericanHotel: Caesars Palace>, 'slug': 'caesars-palace', 'view': <hotel.views.HotelDetailSlugView object at 0x00000210575117F0>, 'cart': <Cart: 5>, 'hotel_extra_photos': <QuerySet [<AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>, <AmericanHotelPhoto: Caesars Palace>]>, 'room_type': <QuerySet [<RoomType: Caesars Palace, Triple>, <RoomType: Caesars Palace, Double>]>, 'room_type_queryset': <QuerySet [<RoomType: Caesars Palace, Double>, <RoomType: Caesars Palace, Triple>]>} The results from room_type are correctly displayed in red. {% for instance in room_type %} <H1 style="color:red">{{instance}}</H1> {% endfor %} The results from … -
Django - How to store emojis in postgres DB properly?
I'm running the latest version of Django on postgres. I'm trying to store emojis in my postgres DB in a way that a React Native app can properly render it. Below I have the initial emojis variables setup that'll go into the talbe. I've copy and pasted the emojis from here. As you can see I'm getting an error from PyCharm regarding it being a "BAD_CHARACTER". How do I store emojis in my postgres DB so that a React Native app can render it properly? -
postgres performance is very slow with django
I made a very small web-app in django with sqllite3 and then I just connected the same app to postgres db in which I reccreated the tables using makemigrations and then now when I am using even the admin page, with just one superuser - admin - its very very slow. I tried postgresql.conf file to set the parameters - seq_page_cost = 1.0 and random_page_cost = 1.0 and restarted postgres.sql from services, but to no avail. is there anything I need to do apart from this ?? please let me know. -
Django/Foundation CSS Accordion Not Displaying Contents
When using the sample code here in my Django template, the information in the accordion-content div will not display on the screen, but inspecting the HTML shows that it exists. In my provided code I have both my dynamic version of the accordion and the sample code copy pasted to show both do not work, but that the information is seemingly loaded into the webpage. I can provide more information but I am unsure what would be relevant so I only included my HTML and a screenshot of the webpage. Is it possible Django is interfering with the Foundation CSS/JS? Base.html {% load static %} <!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/foundation.css' %}"> <link rel="stylesheet" href="{% static 'css/select2.css' %}"> {% block css %}{% endblock %} </head> <body> <!--Need to fix top bar--> <div class="top bar"> <div class="top-bar-left large-offset-1 medium-offset-1"> </div> <div class="top-bar-right"> <ul class="dropdown menu" data-dropdown-menu> <li class="menu-text">Reading List Website</li> {% if user.is_authenticated %} <li><a href="/logout/">Logout</a></li> {% else %} <li><a href="/login/">Login</a></li> {% endif %} </ul> <ul class="menu"> {% if user.is_authenticated %} {{ user.username }} {% else %} Guest {% endif … -
"created" value of TimeStampedModel is showed diffrently
I am creating the review part in my Django project. When the new review is created, the page will show the new review without redirect(with javascript), and after the page is redirected it will show the same review from DB. but the there is some difference between the created time of new review from javascript and the other one from DB. On the template, the review from DB is showed exactly my local time. But the new review created from javascript that takes the value of "created" from the backend, is different from the same review form DB after redirect. for example, 27-November-2021-00:11 (after the new review is rendered with JS without redirect) 27-Novembre-2021-09:47 (after redirecting, the new review from DB) It seems to me maybe the first one is not applicated UTC time. but printing the value of "created", the console shows 2021-11-27 00:49:57.878138+00:00 the hours are the same as the first one but the minutes are the same as the last one... I can't understand. because these two values are from the same thing, "created" of the TimeStamped Model. How could I make this value the same? models.py class TimeStampedModel(models.Model): """TimeStampledModel Definition""" created = models.DateTimeField( auto_now_add=True ) updated … -
API connection and getting the returned result
I'm sorry for my bad english Hello, I am using a brokerage firm for payment instrument. The API connection is successful and I get the result. But I can't use the returned result information. payment_card = { 'cardHolderName': kartisim, 'cardNumber': kartno, 'expireMonth': kartskt_ay, 'expireYear': '2030', 'cvc': karcvc, 'registerCard': '0' } buyer = { 'id': adres.id, 'name': adres.adres_uye.username, 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': adres.adres_uye.email, 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': adres.adres_detay, 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [] for bas in uye: basa = { 'id': str(bas.id), 'name': str(bas.sepet_urun.urun_baslik), 'category1': str(bas.sepet_urun.urun_anakategori.anakategori_baslik), 'category2': str(bas.sepet_urun.urun_altkategori.altkategori_baslik), 'itemType': 'VIRTUAL', 'price': str(bas.sepet_fiyat) } basket_items.append(basa) print(basket_items) request_payload = { 'locale': 'tr', 'conversationId': '123456789', 'price': str(sepetf), 'paidPrice': str(sepetf), 'currency': 'TRY', 'installment': '1', 'basketId': str(sepetid), 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, 'basketItems': basket_items } payment = iyzipay.Payment().create(request_payload, options) print(payment.read().decode('utf-8')) return HttpResponse(payment["status"]) I cannot use the returned result information. The returned result is as follows The error I get is as follows: 'HTTPResponse' object is not subscriptable -
React django permissions
I am still new in react when I tried to delete an element from API(django rest framework) in my case it's not working Error message : Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/events/delete/3' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.enter image description here -
How to save timeslot details when creating a booking instance django
I have a django app in which I am implementing a booking system. I have created a TimeSlot model that has a start_time, end_time, and time_slot_owner. I want to implement a booking system in which the timeslot details, such as the start_time, end_time, and time_slot_owner are added to the Booking Model once it has been created. My TimeSlot model: class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() My Booking Model: class Booking(models.Model): bookings_owner = models.ForeignKey(User, on_delete=models.CASCADE) # time_slot = models.ForeignKey(TimeSlot, on_delete) meals_booked = models.IntegerField(default=0, validators=[MinValueValidator(0)]) start_time = models.TimeField() end_time = models.TimeField() restaurant = models.ForeignKey(User, on_delete=models.CASCADE, related_name="restaurant") What I have in my create_booking function so far in views.py def create_booking(request): instance = Booking() data = request.POST.copy() data["bookings_owner"] = request.user form = BookingForm(data or None, instance=instance) if request.method == "POST" and form.is_valid(): start_time = request.POST.get("start_time") print(start_time) form.save() return HttpResponseRedirect(reverse("food_avail:view_bookings")) return render(request, "food_avail/create_booking.html", {"booking": form}) When I click on Book: It leads me to this page where I can enter number of meals I want to book: Once I enter the number of meals I want the final page to show the following details for each booking: Booking.booking_owner.username | TimeSlot.time_slot_owner.username | TimeSlot.start_time | TimeSlot.end_time | Booking.meals_booked -
Reportlab pdf prints only one page
I am able to create table with reportlab as shown below, but it prints only on one page, how I can print data to multiple pages def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) table = Table(lines, colWidths=10 * mm) table.setStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) table.wrapOn(c, width, height) table.drawOn(c, 0 * mm, 5 * mm) styles = getSampleStyleSheet() ptext = "This is an example." p = Paragraph(ptext, style=styles["Normal"]) p.wrapOn(c, 50 * mm, 50 * mm) # size of 'textbox' for linebreaks etc. p.drawOn(c, 0 * mm, 0 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='users.pdf') -
how to create object in django
is it possible to create new product using the scrap.py in django ? when never i run scrap.py i get this error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. my app models file from django.db import models from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() content = models.TextField(max_length=400) def __str__(self): return self.name scrap.py file from models import Product Product.objects.create( name = 'BMW', age =25 , content = 'cool car' ) -
I need to create a login system with Django
I need to create a login system with Django using something like @login_required, but I don't wanna use the Users in "AUTHENTICATION AND AUTHORIZATION", Users are stored in my app. Can someone help me? I need to store login info in cache or something? -
Why I get an error when adding __init__(self) method to Django rest framework viewset class?
I Am keep getting a error when trying to build a Django API. I have this class: from uuid import UUID from django.shortcuts import render from django.http.response import JsonResponse from django.http.request import HttpRequest from rest_framework import viewsets, status from rest_framework.parsers import JSONParser from rest_framework.response import Response from Instruments import serializers from Instruments.services import InstrumentsService from rest_framework.decorators import api_view from Instruments.services import InstrumentsService from Instruments.models import Instrument from Instruments.serializers import InstrumentsSerializer # Application views live here class InstrumentViewSet(viewsets.ViewSet): # instruments = Instrument.objects.all() def __init__(self): # self.instrument_service = InstrumentsService() # self.instruments = Instrument.objects.all() super().__init__() def list(self, request: HttpRequest): try: self.instruments = Instrument.objects.all() serializer = InstrumentsSerializer(self.instruments, many=True) # data = self.instrument_service.get_instruments() data = serializer.data return JsonResponse(data, status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse( {"Status": f"Error: {exc}"}, status=status.HTTP_400_BAD_REQUEST, safe=False, ) when the init() method is defining even if it is just doing pass the django server gives me this error when I send a request: TypeError at /api/ __init__() got an unexpected keyword argument 'suffix' If I remove or comment out the init() method it works.why?? -
Accessing static file images through url not working django
I am currently trying to configure my django project so that I can access static file images via url. However, it is currentely saying that the image does no exist. Here are my settings for static files: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, '/static/images') Here are my base project urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) And my folder structure is, in the root of my project: static->images->[all images in here] Upon trying to access an image via url like this: http://127.0.0.1:8000/images/*proper image name* It tells me that the image doesn't exist. Does anyone know why this may be happening? -
Python remote developer skills requirement
As an absolute beginner in python programming language, I find the language interesting and easy to learn. However, I intend to take up a job later as a python developer. My problem is I'm a little confused on what core areas to dwell on primarily rather than attempting to know all the classes, libraries and modules. I get overwhelmed. What core areas and possibly tutorials do I concentrate on? -
Put DISLIKE by removing LIKE. Django
Maybe someone can help. There is a Django project where I am trying to add a LIKE / DISLIKE function. I figured out how to add or remove LIKE / DISLIKE. But my logic has a gap in that the user can put both LIKE and DISLIKE (this is not entirely correct). Therefore, I want to make a "feint with the ears" as follows: if the user puts LIKE, then changes his mind and puts DISLIKE, then DISLIKE would be added, and LIKE would be canceled automatically (as happens on YouTube). I have the following views: class AddLikeView (View) class RemoveLikeView (View) class AddDisLikeView (View) class RemoveDisLikeView (View) As far as I understand, I need to write some kind of logic in AddDisLikeView and RemoveLikeView. Tell me please. class AddDisLikeView(View): def post(self, request, *args, **kwargs): blog_post_id = int(request.POST.get('blog_post_id')) user_id = int(request.POST.get('user_id')) url_from = request.POST.get('url_from') user_inst = User.objects.get(id=user_id) blog_post_inst = News.objects.get(id=blog_post_id) try: blog_dislike_inst = BlogDisLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst) except Exception as e: blog_dislike = BlogDisLikes(blog_post=blog_post_inst, disliked_by=user_inst, dislike=True) blog_dislike.save() return redirect(url_from) class RemoveLikeView(View): def post(self, request, *args, **kwargs): blog_likes_id = int(request.POST.get('blog_likes_id')) url_from = request.POST.get('url_from') blog_like = BlogLikes.objects.get(id=blog_likes_id) blog_like.delete() return redirect(url_from) -
Unable to send multiple to database in Django
My aim is to send all the Added items to my database. There is no error while posting data to the database but my form populates the database with only one entry, i.e., "The value of the last input among all inputs". I am new to Django development, please guide me on where I am doing wrong. My Html looks like this: Tables in my database: Primary key Table: Foreign Key Table: Table that already contains items. Table that is made to receive the items from table one. I am just trying to learn how to post data of multiple inputs, otherwise there isn't any logic behind this operation. From models.py: class Item(models.Model): Id = models.AutoField(primary_key=True) itemName = models.CharField(max_length=30,unique=True) cId = models.ForeignKey(Category,on_delete=CASCADE) def __str__(self): return self.itemName class TransferedItems(models.Model): Id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) item = models.ForeignKey(Item, on_delete=CASCADE) From views.py: def transfer(request): if request.method == "POST": a = request.POST.get("a"); obj = TransferedItems(item_id = a); obj.save(); return HttpResponse("sent") else: return HttpResponse("form submission failed") From HTML: <html lang="en"> <body> <div class="maindiv"> <div class="divA"> <label for="coffee">Coffee</label> <select name="coffee" id="coffee"> {% for opt in opts %} <option value="{{opt.Id}}"> {{opt.itemName}} </option> {% endfor %} </select> <button onclick="addtocart()">ADD</button> </div> <div class="divB"> <form method="post" id="cart-screen-form" action="transfer"> {% csrf_token … -
Django render or redirect not working in view after AJAX POST
I am using navigator.geolocation to get an update on location with it's provided watchPosition function with following code: function updatePosition() { if(navigator.geolocation) { navigator.geolocation.watchPosition(calculateDistance); } else { console.log("Geolocation is not supported by this browser.") } } If then new location coordinates I fetch is under a kilometer in distance, I issue a post request and try to render another view. I use google maps API to calculate the distance with function computeDistanceBetween. Here is the code: function calculateDistance(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var dis = google.maps.geometry.spherical.computeDistanceBetween(pos, mapOptions.center); if(dis <= 1000 && dis >= 0 && rendered == false) { var url = '/app/near_park/'; var csrftoken = getCookie('csrftoken'); $.ajax({ url: url, type: "POST", data: { csrfmiddlewaretoken: csrftoken, in_proximity : 1 }, success: function() { rendered = true; console.log("Success"); }, error: function(xhr, errmsg, err) { console.log(xhr.status+": "+xhr.responseText); } }); } } Here is the view handling the post request: def index_close(request): context_dict = {} try: current = Owner.objects.get(user=u) context_dict['checked_in'] = current.checked_in except: context_dict['checked_in'] = False print("##########") #return redirect(reverse('dogpark:register')) return render(request, 'dogpark/index_close.html', context=context_dict) Whenever I get a location update using the sensor utility of dev tools, I do see the print of hash marks on terminal but the redirect or … -
serializer.data not showing any data
I'm still getting to know DRF but when I run the command serializer.data it returns an empty set. Here is what I'm working with models.py import datetime from django.db import models from django.db.models.fields.related import ForeignKey from django.utils import timezone from accounts.models import CustomUser class IndustriaCategoria(models.Model): name = models.CharField(max_length=20, null=False, blank=False) def __str__(self): return self.name class Post(models.Model): category = models.ForeignKey(IndustriaCategoria, on_delete=models.CASCADE) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=512, null=False, blank=False) body = models.TextField() timestamp = models.DateTimeField(default=timezone.now) link = models.URLField(max_length=500, null=True) ups = models.IntegerField(default=0) score = models.IntegerField(default=0) hotness = models.IntegerField(default=0) serializers.py from django.db.models import fields from rest_framework import serializers from .models import IndustriaCategoria, Empresa, Post, Comment class IndustriCategoria(serializers.Serializer): class Meta: model = IndustriaCategoria fielst = ('__all__') class PostSerializer(serializers.Serializer): class Meta: model = Post fields = ('__all__') I have a management command which creates some data so I can just start throwing commands. Here is where the problem comes up: >>> from accounts.models import CustomUser >>> from forum.models import IndustriaCategoria, Post >>> from forum.serializers import PostSerializer, IndustriaCategoria >>> u = CustomUser.objects.all().first() >>> i = IndustriaCategoria.objects.all().first() >>> post = Post(category=i, author=u, title='hello world', body='this is a test', link='https://helloworld.com') >>> post.save() >>> serializer = PostSerializer(post) >>> serializer.data {} Any idea why I got an empty …