Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not supporting GET method JSON body?
this: curl "http://localhost:8000/v1/post" \ -H 'Content-Type: application/json' \ -H 'Accept-Encoding: gzip' \ -d $'{ "url": "/my-test-url" }' with this: class PostView(APIView): permission_classes = ([AllowAny]) throttle_scope = 'public_get' @method_decorator(cache_page(API_CACHE_TTL_PUBLIC_GET)) def get(self, request, format=None): print(request.data['url']) result = {} return Response(result) crashes on the print line... KeyError: 'url' However, changing the GET into a POST: curl -X "POST" "http://localhost:8000/v1/post" \ -H 'Content-Type: application/json' \ -H 'Accept-Encoding: gzip' \ -d $'{ "url": "/my-test-url" }' class PostView(APIView): permission_classes = ([AllowAny]) throttle_scope = 'public_get' @method_decorator(cache_page(API_CACHE_TTL_PUBLIC_GET)) def post(self, request, format=None): print(request.data['url']) result = {} return Response(result) will print it fine. This causes me to believe either Django can't handle GET request body payload and that I must use URL parameters instead with GET --- or that I'm missing something. What am I doing wrong here? -
FullCalendar Events do not refresh after Ajax adds a new event
I am using FullCalendar in Django app. A Django form is used to collect data and add create an event, using an Ajax call to the view. When I create a new event, I successfully add the event. The problem is when I add the event I have to reload the page manually to see the new event in the calendar - which is defeating the purpose of using Ajax! Below is the part of the script that handles the form success I use, can some please point me in the right direction? function handleFormSuccess(data, textStatus, jqXHR){ $myForm[0].reset(); // reset form data $('#addEventModal').modal('hide') var event_arr = $.parseJSON(data); $('#calendar').fullCalendar('removeEvents'); $('#calendar').fullCalendar('addEventSource', event_arr); $('#calendar').fullCalendar('rerenderEvents' ); } -
Django user permissions on variable data
Ran into a problem that has me scratching my head, documentation hasn't really pulled me any luck so I figured I'd see if anyone else has been in this situation. So let's say I have a model (among others): Organization That sort of acts like a psuedo-tenant. The thing is, users within my app may or may not have permissions to multiple organizations, some only 1, some this, some that. Point is, there's no clear structure on where permissions lay for each user. By default it should be none as it is now until manually granting, but instead of granting permissions to all organizations has anyone ran into a similar situation of being able to control permissions in a granular fashion? It is important to note that these 'organizations' are loaded dynamically via an API to an external product. I realize this can be done by crafting my own sort of permissions system outside of Django but my main question is can this be done with conventional Django permissions or is this out of scope? Thanks -
Django rest framework serializer ignores extra_kwargs or custom attribute
I am trying to make an api which is slightly different for the client and the main user. So I want to add the client later if the role is client. class StoreSerializer(serializers.ModelSerializer): class Meta: model = models.Store fields = ["id", "name", "location", "location_lat", "location_lng", "client"] def create(self, validated_data): user = self.context["request"].user if user.role == Roles.CLIENT.name: validated_data["client"] = user.client The dumbed down model lookst like this class Store(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) When I now call the serializer with the user that has the role client I get this response: {"client":["This field is required."]} Which is correct. But the weird thing happens we I add extra_kwargs to the StoreSerializer. If I change the serializer to: class StoreSerializer(serializers.ModelSerializer): class Meta: model = models.Store extra_kwargs = { "client": { "required": False } } ... Or change it to class StoreSerializer(serializers.ModelSerializer): client = serializers.UUIDField(required=False) .... I get the same response. How can this be? Client should not be required right? -
JS code not working on all data retrieved from Django Model
I'm retrieving an endDate field from Django model using forloop on HTML page. I want to check whether all the endDate coming are less that today's date or not. For that I'm using JS code. My code is able to perform checking only on first date retrieved but it's not working on other dates. Here's my HTML code for retrieving data: {% for p in object_list %} <h4>{{ p.jobName }}</h4> <p><b style="color: red">Expires On: </b><b>{{ p.endDate }}</b></p> <a href="{{ p.get_absolute_url }}" target="_blank">View info</a> <input type="hidden" id="endDate" name="variable" value="{{ p.endDate }}"> <span id="check"></span> {% endfor %} JavaScript code to check date: <script type="text/javascript"> var endDate = document.getElementById("endDate").value; var ToDate = new Date(); if(new Date(endDate).getTime()<=ToDate.getTime()){ document.getElementById("check").innerHTML = "Expired"; document.getElementById("check").className = "label danger"; } else{ document.getElementById("check").innerHTML = "Active"; document.getElementById("check").className = "label success"; } </script> I have 2 {{ p.jobName }} right now. First one should show Expired while second should show Active. My code is working only for first date i.e., for Computer Admin only. Here's what I'm getting the output: Can anybody tell me what's the issue? Thanks -
unable to unpack list of dictionary in django
I have as list of object as below : this_json_reponse = ['{"queskey": 1, "ques": "test question 1", "ans": "test ans 1"}', '{"queskey": 2, "ques": "test question 2", "ans": "test ans 2"}', '{"queskey": 5, "ques": "bfxgrdytreyt4etgest4", "ans": "3353tet4"}', '{"queskey": 6, "ques": "tet4w64t", "ans": "f464etrtd"}', '{"queskey": 7, "ques": "fdszf3r3647", "ans": "gry5757"}'] I will be receiving this from another api call. I need to simply list all the queskey and ques present : 1 : test question 1 2 : test question 2 ... I tried unpacking this with nested loop as below : <ul> {% for this_item in this_json_reponse %} <li>{{ this_item }}</li> {% for a,b in this_item.items %} <li>{{ a }}</li> {% endfor %} {% endfor %} </ul> sadly I'm unable to do so after long hit/trial. -
Form data not saving data to database - Django
I can't save form data to the database, everytime I try, I get a different error. Here's my form model class Meta: model = Asistente exclude = ('evento',) widgets = {'nombre': forms.TextInput(attrs={'class': 'form-control'}), 'telefono': forms.TextInput(attrs={'class': 'form-control'}), 'num_asistentes': forms.TextInput(attrs={'class': 'form-control'})} Here's the code to my view. def post(self, request, evento_id): evento = Evento.objects.filter(id=evento_id).first() form = RegistroAsistenteForm(request.POST) if form.is_valid(): registro_asistente = form.save(commit=False) registro_asistente.evento.pk = evento_id registro_asistente.save() else: form = RegistroAsistenteForm() return HttpResponseRedirect('/evento-reg/' + str(evento_id) + '/asistente/')``` There are times when I don't get any error, it just don't do anything. -
How to the name that matches the ID without refreshing/submitting the form in Django?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. My page currently loads, but there is never a call to the function/url that searches for the name to display it on the page (because there isn't one). I'm not sure where I might be missing the part that connects these two areas of the code or how to connect these, … -
How can I get images from RSS feed?
I'm trying to implement this code: https://github.com/ahernp/django-feedreader How would I retrieve also the images from the RSS feed? -
Having django select the right option for a html select tag
I have a template in django that is a pretty simple table that loads up based on the list passed into it from the view. a snippet of the HTML code: {% for hou in bookings_list %} <tr value={{hou.pk}}> <td><a href="mailto:{{hou.user.user.email}}"> {{ hou.user.user.first_name }} {{ hou.user.user.last_name }}</a></td> <td> <select id="room_number" name={{hou.pk}} class="select form-control"> <option value=-1 id=-1> ------ </option> {% for room in room_list %} <option value={{room.id}} id={{hou.pk}}>{{ room.room_name }}</option> {% endfor %} </select> </td> <td> .. more stuff ..</td> </tr> {% endfor %} (bookings_list is a list of bookings for housing that the user has booked (includes room they are assigned to unless no one assigned them a room from a new booking so it is NULL), the room list is a list of all possible rooms for the person in charge to select to assign to a user via the booking) I have ajax working with a jquery change call that when the select is selected it gives the room_id to what ever room.id was selected on the front end and saves the record in the view. But if I reload this page, the ------ always shows up. I know I have to figure out how to set the … -
How would you model this in Django?
I want to upload a list of companies to my web app and then run some long background scripts on each company (ie. Webscraping). Each upload will be essentially be a batch task. I suspect I will probably need to queue these batch processes with something like Redis or Celery, though I am not sure because the batch should start immediately after being being submitted. I am mainly having trouble figuring out how to create my Models for this logic. So any help there would be greatly appreciated. Right now I've set up a Company model and a Batch model. I'm unsure on how to link these models together appropriately so I can sum up the number of employees from each company in a batch. Please reference these pictures for visual details. -
Display different content based on Boolean
I want to allow only manager to create view a content on my website, So I added an entry to my model "Profile" manager = models.BooleanField(default=False) By default is false If false the user cannot see the content. So I tried : {% if profile == manager %} SHOW THE CONTENT {%else%} Does not show the content {% endif %} But nothing change. What did I do wrong ? -
Get Topics ordered by recent Entries
Suppose that I have models: class Entry(models.Model): topic = models.ForeignKey(Topic) date_created = models.DateTimeField() class Topic(models.Model): title = models.CharField(max_length=100) I want to create a queryset that returns Topics which has Entries whose creation date is in last 24 hours. Topics should be ordered so that the first topic has the latest Entry. I tried this with Postgres, but the ordering is lost: Topic.objects.filter(entry_set__date_created__gte=timezone.now() - datetime.timedelta(hours=24))\ .order_by('entry_set__topic', '-entry_set__date_created').distinct('entry_set__topic') I found a solution to a similar problem but it is written in raw sql, and I couldn't convert it to django-orm. -
Annotate existing model objects in Django
Is there a way to use something like Django's annotate method, but for a collection of existing model instances instead of a queryset? Say I have a model like this (all irrelevant details removed): class Node(Model): parent = ForeignKey('self', related_name='children') If I were fetching some nodes and wanted the child count for each one, I could do this: nodes = Node.objects.filter(some_filter=True).annotate(child_count=Count('children')) for node in nodes: print(node.child_count) But what if I already have a collection of Node objects, instead of a queryset? I essentially want the annotation equivalent of prefetch_related_objects. I'm picturing something like this: nodes = list(Node.objects.filter(some_filter=True)) annotate_objects(nodes, child_count=Count('children')) for node in nodes: print(node.child_count) Is there anything like this built into Django? Digging through the docs has not been fruitful for me. -
Django problem with loading CSS and/or JS
Hello, I've got a project to do and I've been wanting to implement CSS and JS to my Django project WITHOUT using Bootstrap. And as you can see I have personal_portfolio/static/css/navbar.css But when I load static files and use the tag inside my base.html the page doesn't apply my stylesheet. I do not understand why ! Whereas when I use bootstrap I have no problem ! I've been wanting to use only CSS and JS cause I want to learn those as well and the project I have requires me to do it myself and not use Bootstrap. Thanks a lot, I hope you all can help me ! -
Django serializer: required_fields
Is it possible to set required fields as a list inside serializer? I don't wont to determine each field with other line like this: name = serializers.CharField(read_only=True) description = serializers.CharField(read_only=True) date_start = serializers.DateTimeField(read_only=True) date_end = serializers.DateTimeField(read_only=True) I expect next behavior: class CampaignStepFirstSerializer(serializers.ModelSerializer): class Meta: model = Campaign fields = ( 'name', 'description', 'date_start', 'date_end', ) required_fields = fields -
Django request.user gives Anonymous in the response view after callback from payment gateway
Payment gateway (3rd party website) sends post data to a callback url (my website) which can be accessed using request.POST But request.user gives Anonymous in the response view. On adding decorator @login_required to the view, request.POST becomes empty but request.user returns authenticathed user. I need to access both request.user and request.POST form data at the same time to save transaction into database. # @login_required def response(request): if request.method == "POST": MERCHANT_KEY = settings.MERCHANT_KEY data_dict = {} for key in request.POST: if request.POST[key]: data_dict[key] = int(request.POST[key]) PaymentHistory.objects.create(user=request.user, **data_dict) return render(request, "response.html", {"paytm": data_dict}) return HttpResponse(status=200) -
Reference name from Django database, NOT the id
I am sending an email with object ID in a model, but I want to send the object names. I have two models: class Uniform(models.Model): category = models.CharField(max_length = 50) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(max_length = 10) def __str__(self): return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price) class Transaction(models.Model): employee_id = models.ForeignKey(Employee, on_delete = models.PROTECT) uniform = models.ForeignKey(Uniform, on_delete = models.CASCADE) date = models.DateTimeField(default=timezone.now) def __str__(self): return '{}: {} - {}'.format(self.employee_id, self.uniform, str(self.date)) And forms.py class TransactionForm(forms.ModelForm): class Meta(): model = Transaction fields = '__all__' My Views.py def employeeCloset(request): form = TransactionForm() if request.method == 'POST': form = TransactionForm(request.POST) if form.is_valid(): subject = 'Checked out item from Me' message = 'It is the responsibility of the team member to maintain all articles identified so that they are presentable and worn upon arriving according to standards required in the Employee Handbook. I understand I will be charged the deposit according to the cost identified below: \n {} \n These costs will be deducted from the team member’s paycheck and will be credited upon return of article(s). \n Any item that is not returned by the end of the pay period the … -
Add multiple entries to a database in one post using charfield
I am building a todo app and for now people can only add one "task" at the time. I would like to allow user to have multiple text area (5 for example) and so they can add multiple tasks in one post. As you can see on the picture, only one input is available, I cannot add more than that without error. I thought that maybe I could add multiple charfield in my model "todo" but that seem ugly. -
Scrape code from website with python and beautiful soup
My project is about scraping 5 shopping websites. I found useful data from StackOverflow and from youtube. But I am stuck on one website. one div class used style display, none and hidden visibility after that all div classes are hidden. I tried to use ajax, google chrome extension for javascript, and applied different methods which I applied on the other 4 but this website is bit hard for me. If someone helps me to read those tags so that I can scrape data from a website. Website URL is : Website currently, I am using simple code for parse. here is the code which I used. y = requests.get(url) soup = BeautifulSoup(y.text, "html.parser") products = soup.find('div', class_='container min-w1170') products = products.find('div', class_='row mgt25') print(products) products = products.find_all("div", class_="findify-components-common--grid__column findify-components-common--grid__column-6") print(products) until first print, all div classes are working but after that, I am unable to find data from next div classes. -
How can I run a function after a user gets registered Django
I am developing a server using Django and wanted when a user registered to run a function that would create a directory with the username. The folder with the new user name will be saved in Collections. My code is as follows: Models.py from django.db import models from django.contrib.auth.models import (BaseUserManager,AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, username, first_name, last_name, email, password=None): """ Creates and saves a user with the given variables and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, first_name, last_name, email, password=None, is_admin=True): """ Creates and saves a superuser with the given variables and password. """ user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, is_admin = is_admin, ) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=100, unique=False) last_name = models.CharField(max_length=100, unique=False) is_active = models.BooleanField(default=True, unique=False) is_admin = models.BooleanField(default=False, unique=False) user_collection = models.CharField(max_length=500, default='NotCreated', unique=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'last_name', 'email'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin Directory images Is there … -
Jquery selector returns the same class
I have written a dynamic page which loads the products from the context object. the number of products in the object, number of times the loop will run and i have created a hidden input. in each iteration the value of hidden input will be the primary key of the product. but when i use jquery to fetch the value of clicked product, the id of first product is returned. Any product i click only the first products id is been returned. {% for album in list1 %} <div class="col-lg-3" id="div1"> <div class="card" style="width: 20rem;"> <input type="hidden" class="custId" value={{ album.id }}> {{ album.product_name }} Category : {{ album.product_category }} Price : {{album.id }} $('.k').click(function(){ var a = $('.custId').val(); alert(a); console.log(a) }); -
how to get userId from token in django
I create API in django with django-rest-framework. I have a model called Comment, and each Comment has a UserId. I am creating the users by rest-auth. Each User has a token which I use on frontend. from django.db import models import uuid from django.utils.timezone import now from django.contrib.auth.models import User class Comment(models.Model): CommentId= models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) DataCreated = models.DateField(default=now, editable=False) UserId = models.ForeignKey(User, on_delete=models.CASCADE, default=uuid.uuid4, editable=False) Name = models.CharField(max_length=120, default="") class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('CommentId', 'DataCreated', 'UserId', 'Name') I create a simpre view which save new Comment @api_view(['POST']) def addComment(request): serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The point is that in request.data I receive data like Name and Token and not UserId, so I am wondering how to get UserId from Token? -
Django migrations with multipule databases
I have a django projects that has 2 apps and each app runs on a different DB (lets call them default and DB2). I have created a router to manage the data and added the router to my settings.py When I run migrate I get Applying analytics.0001_initial... OK but in the default DB the only thing that gets updated is the django_migrations table showing that the app analytics has been migrated with 0001, and in the DB2 the table itself isn’t even created at all. Going to the django shell and trying to do obj.objects.all() gives me table DB2.table_name does not exist I also verified in sql DB2 exists but doesn’t have any table from what I created My router: class DB2Router(object): """ A router for apps that connect directly to the DB2 database. This router allows apps to directly update the DB2 database rather than using raw SQL as in the past. The router forces the use of the DB2 database for any app in the "apps" list. """ db = "DB2" apps = ["analytics"] def db_for_read(self, model, **hints): if model._meta.app_label in self.apps: return self.db return None def db_for_write(self, model, **hints): if model._meta.app_label in self.apps: return self.db return None … -
Javascript Counter up on HTML span tag element using jquery.counterup.min.js doesn't work
So I am currently developping a Django app, and I amy trying to set up a counter to display a given integer on the main page. Here is the javascript stuff I load on my HTML template (that is not the entire file): <script type="text/javascript" src="{% static 'EpiDB/jquery-3.2.0.min.js' %}"> </script> <script type="text/javascript" src="{% static 'EpiDB/jquery.tablesorter.min.js' %}"> </script> <script type="text/javascript"> $(document).ready(function() { $("#annotable").tablesorter(); } ); </script> <script type="text/javascript" src="{% static 'EpiDB/jquery.searchable-1.0.0.min.js' %}"> </script> <script type="text/javascript"> $(function () { $( '#annotable' ).searchable({ searchField: '#annotsearch', striped: true, oddRow: { 'background-color': '#e2e9f3' }, evenRow: { 'background-color': '#ffffff' }, searchType: 'fuzzy' }) }); </script> <!-- popper js --> <script src="{% static 'EpiDB/popper.min.js' %}"></script> <!-- bootstrap js --> <script src="{% static 'EpiDB/bootstrap.min.js' %}"></script> <!-- easing js --> <script src="{% static 'EpiDB/jquery.magnific-popup.js' %}"></script> <!-- swiper js --> <script src="{% static 'EpiDB/swiper.min.js' %}"></script> <!-- swiper js --> <script src="{% static 'EpiDB/masonry.pkgd.js' %}"></script> <!-- particles js --> <script src="{% static 'EpiDB/owl.carousel.min.js' %}"></script> <script src="{% static 'EpiDB/jquery.nice-select.min.js' %}"></script> <!-- swiper js --> <script src="{% static 'EpiDB/slick.min.js' %}"></script> <script src="{% static 'EpiDB/waypoints.min.js' %}"></script> <script src="{% static 'EpiDB/jquery.counterup.min.js' %}"></script> All content of my page using the other javascripts is working fine except the counter up. So I read bit about the way …