Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Injecting Django attributes into Java script
I am trying to add the title of my post to a javascript but I am doing wrong it is not showing correctly. My objective is the show the title and the link of the Django page to the Facebook sharing button. The name of the app is score Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) design = models.ImageField( blank=False, null=True, upload_to=upload_design_to) Here is the post-details.html <!-- Share Buttons TODO --> <div class="icons"> <ul> <a target="_blank" class="facebook-btn" href="https://facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"><li class="facebook"><i class="fab fa-facebook-f"></i></li></a> <a target="_blank" class="twitter-btn" href="https://twitter.com/intent/tweet/?text={{ request.build_absolute_uri }}"><li class="twitter"><i class="fab fa-twitter"></i></li></a> <a target="_blank" class="linkedin-btn" href="#"><li class="linkedin"><i class="fab fa-linkedin"></i></li></a> </ul> </div> <!-- Share Buttons --> Here is the script function init() { let postUrl = encodeURI(document.location.href); let postTitle = score=> score['title']; console.log(postTitle); } init(); My question: how to get the console to show the name of the {{ object.title }}, currently it is showing score=> score['title'] -
django: template show timezone also for the datetime
I am sending the following datetime timezone aware object to django template current_time = timezone.now() In my template i am showing it using {{ current_time }} it displays as: Feb. 10, 2021, 3:25 a.m I want it to display as Feb. 10, 2021, 3:25 a.m UTC I dont see which timezone the time is. So i want to be more clear by adding the timezone. how can i do this in django template -
I am getting a programming error in django after changing the models.py and deleting all my migrations besides __init__.py
I am getting a programming error - ProgrammingError at /admin/appointed/patient/ I changed my model from having an occupation =models.CharField(max_length=100) to frontlineWorker = models.BooleanField(default=False) and then went to delete all the migrations I made I then did python3 manage.py makemigrations python3 manage.py migrate which worked fine and created my new models. However, after entering into my localhost which is currently running this server, I get the programming error above because column appointed_patient.frontlineWorker does not exist I have tried to see my psql, and have tried $ python3 manage.py reset_db using django-extensions to reset my tables. this gives me psycopg2.errors.InsufficientPrivilege: must be owner of database appointed2 psycopg2.errors.InsufficientPrivilege: permission denied to create database when i run psql and try to see my tables for my database, I do not see anything either. Does anyone have any suggestions for me to try? Thank you -
Unable to set post id for Django and Vue application
Am trying to use vue to submit a comment on a post to the backend. am unable to get the post id. The app has a feed like twitter. I want users to be able to comment on post without going to the detail view. methods: { commentPost(post_id) { console.log('commentPost:', post_id); if (this.body.length > 0) { var post = { 'post_id': post_id, 'body': this.body, 'user': this.user, 'created_at': this.created_at }; fetch('/api/add_comment/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, credentials: 'same-origin', body: JSON.stringify(oink) }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } }, However when i click on the submit button. In the browser log i get commentPost: undefined. How can i set the post id -
Empty query parameters in url
Using Django==2.2.13, djangorestframework==3.8.1 This is a question to establish "what is the right thing to do", rather than "how to do it". I have a backend API route that takes some optional query parameters. The frontend has noticed that if they call: https://my_domain.com/some_path/?foo= They trigger a ["natural"] behavior that checks for the foo value, and similar to a bad value, takes the empty value and responds: { "objective": [ "Select a valid choice. is not one of the available choices." ] } I think that if an endpoint supports a query param, or a hundred of them, if I am not trying to filter by them I should not include them like that: https://my_domain.com/some_path/ (if you don't want to filter by it then don't use it) The other side thinks that all query parameters should be in, empty or not. (if you include an empty query param, then you want all -- unfiltered) The question is, what is the "right" thing to do, methodology/pattern-wise? tl;dr in case you are curious, this is the basic look of the endpoint: in views file: class SomeView(viewsets.ModelViewSet): filter_class = SomeViewFilter ... In the filters file: class SomeViewFilter(django_filters.FilterSet): ... the_query_parameter = EnumMultipleChoiceFilter( choices=[(my_val.name, my_val.name) for … -
member-related permission checking rest-framework
So This is how I currently validate permissions. I have a base class like this class MemberPermission(permissions.BasePermission): """ The Base Permission class that every member-permission must inherit from. Provides reusable functions to validate the existence of permissions, as well as facilitates additional context validation. To check permissions, we need to get the member object first. However, as the approach to do the same differs per view, the `get_member` method must be suitably overwritten by subclasses. """ CHECK_METHODS = [] PERMISSION_LABEL = None message = 'permission denied' @classmethod def get_member(cls, view, request, obj=None): # returns the member-object for the current view. This method # may vary greatly for different permissions because # the approach to lookup the box for the request's user might differ # References the box-id in the url by default box = get_object_or_404(api_models.Box, id=view.kwargs.get('box_id')) return get_object_or_404(api_models.Member, box=box, user=request.user) @classmethod def get_overwrite_channel(cls, view, request, obj=None): # returns the overwrite-channel-object for the current view # This method may vary greatly for different permissions # because the approach to lookup the box for the request's # user might differ. Returns None by default return None def validate_additional_context(self, view, request, member, obj=None): # check for implementation of additional permission-logic # subclasses must …