Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show only one objects if there are few in Django?
I'm trying to user a list but still it shows all the values. allexpelorer1 = Destination.objects.filter(destination = pk).order_by('-pk') allexpelorer = [] for checkhu in allexpelorer1: if Destination.objects.filter(destination = pk, user_pk = checkhu.user_pk) not in allexpelorer: allexpelorer.append(checkhu) -
Django admin - How to display custom query results in default list view?
How can I write a custom query in Django admin and display the results in the default list view? Query: SELECT user,count(tag) as total_tags FROM group by user; Expected results in default list view: User Total tags John 30 Mark 15 -
How do I serialize ManyToMany Field data in Django?
So I'm working on Django back-end and React front-end. I have a many-to-many field in one of my models, and trying to serialize. I've googled some related issues and tried things out, but none worked. Let me show you my code first. models.py class Category(models.Model): objects = models.Manager category = models.CharField(max_length = 20) class Content(models.Model): objects = models.Manager() title = models.CharField(max_length = 100, null=True) category = models.ManyToManyField(Category) serializers.py class ContentSerializer(serializers.ModelSerializer): category_name = serializers.SerializerMethodField() class Meta: model = Content fields = [ 'title', 'category_name' ] def get_category_name(self, obj): categories = self.context['book'].category.all() return categories Finally, views.py @api_view(['GET']) def each_book(request, pk): this_book = Content.objects.get(pk=pk) serialized = ContentSerializer( this_book, context={ 'request':request, 'book' : this_book }, ) return Response(serialized.data) I keep on getting error saying Object of type Category is not JSON serializable. What do you think is the problem? Thanks a lot in advance. :) -
I am new to Django can anyone help me with the below task....?
Go through the sample JSON file given here - https://drive.google.com/open?id=1xZa3UoXZ3uj2j0Q7653iBp1NrT0gKj0Y This JSON file describes a list of users & their corresponding periods of activity across multiple months. Now, design and implement a Django application with User and ActivityPeriod models, write a custom management command to populate the database with some dummy data and design an API to serve that data in the JSON format given above. -
Sorting items by category in Django
I am a newcomer to Django and I want to know how can I categorize objects I've created in admin panel and sort them by those categories when rendered. This is what I tried but I don't know if it's how it works: class Post(models.Model): CATEGORY = ( ('popular', ('Popular Posts')), ('new', ('New Posts')), ('suggestions', ('Music Suggestions')), ) category = models.CharField('Post Category', max_length=40, choices=CATEGORY, default='popular') title = models.CharField('Title of the post',max_length=50) content = models.TextField('Page content', max_length=500) posted = models.DateTimeField('last updated') -
django.db.utils.NotSupportedError: NOWAIT is not supported on this database backend
I want to use select_for_update(nowait=True) in my Django project with MySQL database, but MySQL does not support NOWAIT. I don't have to wait until the transaction is complete; just raise an exception, if the object is locked. How can I achieve this? -
how to increment a like button in django with ajax?
i have a post in a community and i have implemented the like button in django + ajax but i notice that when i do like a post it increments all the post's likes.how can i solve it ? here is my template: {% for post in posts %} <div class="w3-container w3-card w3-white w3-round"> <a target="_blank" href="{{ post.author.profile.avatar.url }}"> <img src="{{ post.author.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"></a> <h4> <a href ='{% url 'profile' post.author.pk %}'>{{ post.author.profile.prenom|title }} {{ post.author.profile.nom|title }}</a> </h4> <span class="w3-opacity">{{ post.created|date:"d-m-Y H:i" }}</span> <br> <hr class="w3-clear"> <p> {{ post.contenu }}</p> <button type="button" class="btn btn-default btn-sm"> {{ post.comment_set.count }} <a href='#'><span class="glyphicon glyphicon-comment"></span> </a> </button> {% if request.user in post.liked.all %} <button type="button" class="btn btn-default btn-sm"> <span id='{{ post.id }}'>{{ post.liked.count }} </span> <a name="{{ post.id }}" style="color: blue;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a> </button> {% else %} <button type="button" class="btn btn-default btn-sm"> <span id='{{ post.id }}'>{{ post.liked.count }} </span> <a name="{{ post.id }}" style="color: black;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a> </button> {% endif %} {% if request.user == post.author %} <button type="button" class="btn btn-default btn-sm"> <a href='{% url 'delete' post.id community.id %}'><span class="glyphicon glyphicon-trash"></span> </a> </button> {% endif %} <br> <br> </div> <br> {% empty %} … -
How to restrict access to Chatting service only to registered websites
I am making a chatting service (something like Zendesk) and a website must be registered in order to use the service. There will be a frame which the website owner places in the .html file and the rest is up to me. Problem Anyone can start using the service right now (by reading the requests and copying them in Postman). I want a method to restrict access only to those websites that have registered to use the service. Failed solutions (to give an idea of what I am trying to do) A stupid idea was to read and send the website URL with JavaScript and check if it exists in the database, but that can easily be forged. I also tried generating unique tokens for each registered website, but the token is something that must be send with the request for validation and since it is something that public can see (the token is placed with the frame) that token is indeed meaningless. (Maybe I don't understand how tokens work) At this point, seems like this is inevitable, any Ideas? (Back-end is written in Django 3.1 and My database tables look like this, if it helps - Ignore the details, … -
How can I connect Django with Gulp SCSS broswer-sync?
I am trying to use SCSS using gulp with Django and I want to make this auto sync with using browser-sync. However, Django localhost cannot find the both CSS and template html files. Here's the gulpfile.js that I wrote. const gulp = require(‘gulp’); const sass = require(‘gulp-sass’); const browserSync = require(‘browser-sync’).create(); ... const watch = () => { browserSync.init({ server: { notify: false, port: 8000, proxy: ‘localhost:8000’ } }); gulp.watch(‘./static/scss/**/*.scss’, style); gulp.watch(‘./templates/**/*.html’).on(‘change’, browserSync.reload); gulp.watch(‘./static/js/**/*.js’).on(‘change’, browserSync.reload); }; exports.watch = watch; Also, my templates html and CSS file location are as follows: myproject ㄴstatic ㄴcss ㄴstyle.css ㄴscss ㄴstyle.scss ㄴtemplates base.html ㄴshop shop.html cart.html ㄴreservation ... How can I connect to my Django local host with using gulp? port is 8000 -
Django: Can I send HTTP response before executing post_save signal?
I have a form page when I submit it, Django executes a post_save signal and I am executing a workflow there. I am facing one issue that till workflow is not being executed it is not sending HTTP response to the front end. One solution can be using Celery to append the workflow in the queue. But I want to know if the HTTP response can be sent before the signal workflow execution? -
я генерирую pdf из html, локально все работает!! развернул на сервере, фотка загруженная через браузер не подгружаеся пдфке. использовал weasyprint [closed]
я генерирую pdf из html, локально все работает!! развернул на сервере, фотка загруженная через браузер не подгружаеся пдфке. использовал weasyprint html_string_front = render_to_string('pdf_student_front.html', data) html_front = HTML(string=html_string_front, base_url=request.build_absolute_uri()) result_front_student = html_front.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/student-front.css')], presentational_hints=True) в чем может проблема -
django how to fetch all users in django allauth
I installed django allauth. And then build a User model in models: class User(AbstractUser): age = models.PositiveIntegerField(default=0, verbose_name='pv', blank=True) class Meta: verbose_name = "用户信息" verbose_name_plural = verbose_name def __str__(self): return self.username in settings: AUTH_USER_MODEL = 'news.User' After migrate, system doesn't create a User table,I can only see a auth_user table in database, and my users is in auth_user, but I have no idea how to fetch them out from auth_user, because I can't build a User model base on the auth_user table, and I don't know how to fetch the table in django. Any friend can help? -
django superuser_only decorator - how do I introspect the original function?
I am finding it extremely hard to get at the decorated function in the case of @superuser_only. However, I can do this without a problem with @login_required First, let's take another decorated function, this time with @login_required. @login_required def status(request, rdbname): .... stuff .... If I more or less from views import status as func I can then introspect the view's name and its signature: (Pdb++) func.__wrapped__ <function status at 0x117c91550> (Pdb++) func <function status at 0x117c918b0> (Pdb++) getfullargspec(func) FullArgSpec(args=['request'], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) (Pdb++) getfullargspec(func.__wrapped__) FullArgSpec(args=['request', 'rdbname'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) (Pdb++) func.__name__ 'status' (Pdb++) func.__wrapped__.__name__ 'status' However, if I change the decorator to superuser_only things aren't so good. (Pdb++) func <function superuser_only.<locals>._inner at 0x118bb5ee0> (Pdb++) func.__wrapped__ *** AttributeError: 'function' object has no attribute '__wrapped__' (Pdb++) func.__name__ '_inner' (Pdb++) getfullargspec(func) FullArgSpec(args=['request'], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) I don't see the actual name of the function, status anymore. I also don't see the full signature anymore, only request. Worse, as far I know this function is just called _inner. How can I access the status object, in the same sense that I could examine __wrapped__? Taking a look at django/contrib/auth/decorators.py I could see login_required but … -
Django ArrayField not storing data properly
I stumbled up strange issue today, I could not properly add item to ArrayField() in django. The document is straight forward: https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield Here is my model: class AppealStateChangeLog(models.Model): agent = models.ForeignKey( User, on_delete=models.CASCADE, related_name='appeal_change_log_appeal_id', ) codes = ArrayField( models.CharField(max_length=10, blank=True), default=list ) I could not add codes like this # some where in code codes = ['11111','22222','33333'] c= AppealStateChangeLog( agent=appeal.agent, codes=[str(a) for a in codes] if codes else [] ) c.save() This code only adds ['11111'] in codes field, I was expecting all three values. The strange things is when I try to update the values it updates successfully as: item = AppealStateChangeLog.objects.get(id=123) codes = ['11111','22222','33333'] item.codes = codes item.save() This stores all three values. I even tried to create using AppealStateChangeLog.objects.create() method but it only add first value of the array i.e ['11111']. Postgres version: 12 django version: 1.10 (it's an old system I know :) ) -
Is stripe send message to confirm payment?
I'm integrating stripe payment in my project. All payment process is done in test data, but i can't test using real card number, so i need to know that when someone enter the card number for billing, he get confirmation message in his mobile or via mail or automatically confirm payment or what happens ? anyone there to know about this. -
How to custom django allauth User model?
I installed django allauth. In the mysql database I can see a table named:auth_user, it contains superuser and regular user. But know I want to use this table and I want to customize User table,so I first add to settings: AUTH_USER_MODEL = 'news.User' and then in models: from django.db import models class User(AbstractUser): age = models.PositiveIntegerField(default=0, verbose_name='pv', blank=True) class Meta: verbose_name = "用户信息" verbose_name_plural = verbose_name def __str__(self): return self.username But I received errors: The field admin.LogEntry.user was declared with a lazy reference to 'news.user', but app 'news' doesn't provide model 'user'. The field socialaccount.SocialAccount.user was declared with a lazy reference to 'news.user', but app 'news' doesn't provide model 'user'. -
I am trying to create a like and dislike button for different posts on a page using JavaScript and Django but it seems to work first post only
For the most part, I've managed to create a thumbs up and thumbs down icon working as a like and dislike button, it increases and decreases the count as well for the FIRST POST ONLY, and whenever I click on a like button in any post beside the first post, the button doesn't toggle for that post, it toggles for the first post instead and shows count there. When I refresh the page, the count for other posts gets updated but the button never toggles. main.js function likeOnClick(id) { // $('#likes').click(function () { var postId; // postId = $('#likes').attr("data-postId"); postId = id; console.log("I went inside the function", postId); var currentClass = $('#likes').attr('class'); if (currentClass == 'fa fa-thumbs-up') { $("#likes").removeClass("fa fa-thumbs-up"); $("#likes").addClass("fa fa-thumbs-down"); $.get('like_post/', { post_id: postId, ld: 'l' }, function (data) { $('#like_count').html(data); // $('#likes').hide(); }); } else{ $("#likes").removeClass("fa fa-thumbs-down"); $("#likes").addClass("fa fa-thumbs-up"); $.get('like_post/', { post_id: postId, ld: 'd' }, function (data) { $('#like_count').html(data); }); } // }); }; HTML {% for d in page_obj %} <div class="secondSection"> <div class="container"> <div class="card" id = "cardID"> <h4><a href="profile/{{d.created_by}}" class="userNameClick">{{d.created_by}}</a></h4> {% if request.user == d.created_by %} <a href="#" onclick="loadModal('{{d.id}}');" id="editLink">Edit</a> {% endif %} <p id="contents">{{d.postContent}}</p> <small>{{d.dateAndTime}}</small> <strong id = "like_count">{{ d.likes }}</strong> {% … -
Pass an ID from Ajax to a Django view
I have a Django view that accepts an ID and returns a Json Response. Now on Ajax, I want to call the django view with an ID. Here is my AJAX: $(document).ready(function () { $("#button").click(function () { var id = 25; $.ajax({ url: "/account/check_id/", data: { id: id, }, dataType: "json", success: function (data) { if (data.is_taken) { alert("ID is available"); } }, }); }); }); However, when I click on button, I get error message GET http://localhost:8000/account/check_id/?id=25 404 (Not Found). The ?id= is causing the error. How to remove it? -
how to populate a CreateView field based on count of model instances in Django
I have a model for players on a ladder. class Player(models.Model): # Availability choice list available = 'AVL' injured = 'INJ' away = 'AWY' retired = 'RET' AVAILABILITY_CHOICES = [ (available, 'available'), (injured, 'injured'), (away, 'out of town'), (retired, 'retired') ] # Player fields first = models.CharField('First Name', max_length=30) last = models.CharField('Last Name', max_length=30) cell = models.CharField('Cell Phone', max_length=12) email = models.EmailField('Email') # changed field type availability = models.CharField('Availability', choices = AVAILABILITY_CHOICES, \ max_length = 15, default='AVL') ranking = models.IntegerField(default = 99) I am also using a CreateView to create a new player. class PlayerCreateView(CreateView): model =Player num_players = Player.objects.all().count() print('There are {} players'.format(num_players)) context_object_name = 'player' fields = ['ranking', 'first', 'last', 'cell', 'email', 'availability'] template_name = 'player_create.html' success_url = reverse_lazy('players') I can't believe I'm asking this (still new to Django) but I haven't found a way to pre-populate the player's ranking field. So basically I need to count the number of existing players and populate the ranking field. It can't be based on ID because some players may have been deleted. In the model I tried using a variable for the default, but Django threw a fit. (NameError: name 'Player' is not defined) ... evidently because you can't reference … -
How to extract PDF data using camelot and store them in a POSTGRES Database table?
I want to implement a function to extract PDF file data and store them in a postgres database table using django rest_framework. How I do this? Can give me snippets for this? -
Django: What do I need to do to get the csv file to actually load into the model?
I am having a problem getting my upload.html to be fully functional. The html page shows okay and I can even select an csv file for upload. It does not do anything when clicking on the "Add data" button. What do I need to do to get the csv file to actually load into the model. Below is the code for upload.html shown below: {% extends "myapp/base.html" %} {% load bootstrap5 %} {% block body_block %} <div class="container"> <h1>Please select csv file for upload</h1> <form action="" method="POST" enctype="multipart/form-data" class="form-control" > {% csrf_token %} {{ form }} </form> <button type="submit" class="btn btn-primary">Add data</button> </div> {% endblock %} Below is the forms.py from django import forms from .models import Csv class CsvForm(forms.ModelForm): class Meta: model = Csv fields = ('file_name',) Below is the views.py from django.shortcuts import render from .forms import CsvForm from .models import Csv import csv def upload_file_view(request): form = CsvForm(request.POST or None, request.FILES or None) # check whether it's valid: if form.is_valid(): form.save() form = CsvForm() obj = Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for row in reader: # this is not working yet. print(row) obj.activated=True obj.save() context = {'form': form,} return render(request, 'csvs/upload.html', context) below … -
Getting error when i run server,Please suggest
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 409, in check messages.extend(check_resolver(pattern)) File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 409, in check messages.extend(check_resolver(pattern)) File "C:\Users\JIGNESH PATEL\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() -
Fetching choices from API and update choices in Django froms
I would like to update a form charfield (actually it should be a select) depending on other dropwdown selection. in this case, cities belonging to provinces. Model: class Branch(models.Model): name = models.CharField(_("Nombre"), max_length=100) province = models.CharField(_("Provincia"), max_length=50, choices=utils.PROVINCIAS) city = models.CharField(_('Localidad'), max_length=150) In don't want to create a table for provinces and cities as I can get the informations from a web API (there are more than 120k cities...). The problem is that I can't figure out how to do it. If I use choices (empty) in the city's charfield (just to render a select tag), the form raises a validation error as there is no choices, and any available options from the web API will not be a valid one. If I don't use choices, I don't konw how to render a select tag in the form... Below my JS script: const provincia = document.getElementById("id_juzgado-provincia"); const localidad = document.getElementById("id_juzgado-localidad"); provincia.addEventListener("change", () => { let prov = provincia.value; fetch( `https://apis.datos.gob.ar/georef/api/localidades?provincia=${prov}&campos=id,nombre&max=900` ) .then((response) => response.json()) .then((result) => { localidad.innerHTML = ""; const default_value = document.createElement("option"); default_value.text = "---------"; localidad.add(default_value); result.localidades.forEach((element) => { const option = document.createElement("option"); option.text = element.nombre; localidad.add(option); }); }); }); The logic is simple, according to the province … -
How do I reference other FIELD using foreign key in Django?
So I'm using Django and have a foreignkey field. Let me show you the model first. class Book(models.Model): objects = models.Manager() title = models.CharField(max_length = 30) author = models.CharField(max_length = 20) class Content(models.Model): objects = models.Manager() source = models.ForeignKey("Book", related_name='book', on_delete=models.CASCADE) key_line = models.CharField(max_length = 100, null=True) I used serializer to load the api to my React front end. But then, the source field is displayed as integer, which probably is the id of Book model. However what I want to do is load the title of each book in the source field. Any advice? FYI, other codes. views.py @api_view(['GET']) def each_book(request, pk): this_book = Content.objects.get(pk=pk) serialized = ContentSerializer(this_book, context={'request':request}) return Response(serialized.data) serializers.py class ContentSerializer(serializers.ModelSerializer): class Meta: model = Content fields = '__all__' -
How to use django signals to refresh a specific page
I am creating an ecommerce webapp and I want to update my admin page when user place order. After research i found out about Django signals, but it seems pretty confusing. The idea behind this is that, when a user places an order I want the admin page to be refreshed and show the latest updates. I tried ajax but javascript can only work with the current open page. Can anyone help me with usibg django signals this way?