Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Can you host a Django app and Strapi API on the same server using NGINX?
Is it possible to have... A static file is served from => 0.0.0.0 A Django application served at => 0.0.0.0/django A Strapi API at => 0.0.0.0/strapi ... with NGINX? I've tried server { listen 80; server_name 0.0.0.0; root /var/www/html; index index.html; location /static/ { root /home/user/app/static/; } location /django { proxy_pass http://0.0.0.1:8000; } location /strapi { proxy_pass http://0.0.0.1:1337; } } # I have my real IP not 0.0.0.0 in the file But / returns my static /django returns a django 404 page /strapi returns an html with 'not found' Is the question I'm asking "Can an NGINX location alias a port?" -
Django ModelChoiceField how to save not just the string representation but also the other database(model) row values
I have 2 models. The customer model and the customerpricing model. class Customer(models.Model): priceline= models.IntegerField() billto=models.IntegerField(null=False,default=False,db_column="billto") customername=models.CharField(max_length=500) def __str__(self): return self.customername class Meta: db_table='customer' class Customerpricing(models.Model): rep=models.CharField(max_length=10) billto=models.ForeignKey(Customer, on_delete=models.CASCADE, null=False,db_column="billto") customernm=models.CharField(max_length=60) specialterms=models.CharField(max_length=100) start=models.DateField(default=timezone.now) Here is my form. class CustomerpricingForm(forms.ModelForm): customernm=forms.ModelChoiceField(queryset=Customer.objects.all()) priceline=forms.ModelChoiceField(queryset=priceline.objects.all()) billto=Customer.objects.all() class Meta: model = Customerpricing fields = ['customernm','billto', 'priceline','rep','specialterms'] widgets= { 'rep': forms.TextInput(attrs={ 'class': 'form-control' }), 'start': forms.SelectDateWidget(empty_label=("Choose year", "choose Month", "choose day" ),attrs={ 'class': 'form-control' }), 'specialterms': forms.TextInput(attrs={ 'class': 'form-control' }), } Here's my view. def addnew(request): if request.method == "POST": form = CustomerpricingForm(request.POST) if form.is_valid(): try: form.save() return redirect('/customerpricingfile') except Exception as e: #print (e.message, e.args) print (form.errors) print(e) else: messages.error(request,"Error") else: form = CustomerpricingForm() What I want to do seems so easy. When the user selects their value from the ModelChoiceField named customernm I want to also save that model's (Customer model) other database rows aka model fields which are billto and shipto with the Customerpricingform. How can I do this? I've spent far too much time on this and your help would be greatly appreciated. -
How to properly use code coverage with django redis queue?
I'm creating a Django rest API that runs async tasks with django-rq. I run my unit tests in sync mode, just like the django-rq docs indicates. The problem is that my code coverage is low because the code that the async tasks run is not being covered. How can I fix this? -
How to force a value on created_at and updated_at in Django
I have a model in Django that have the created_at and updated_at fields. I implement certain functionality that depends on those dates, so I want to write some unit tests, but when I create the objects, they always save both fields with the current date. I assume (I looked up but I did not find any information) that Django in some way does not allow the client to updated those fields, and it does it by itself. There is any way to overwrite this behavior in a test? -
Django model save method don't work with celery
I'm working in a project using drf, django channels and celery i want to push notification on created to subscribed channel and it works well but when using celery the model create method doesn't excute save method or any signal that's my taks @shared_task() def send_notification_to_all(data, users=None): if not users: users = User.objects.values_list('id', flat=True) for user in users: Notification.objects.using('notifications').create(user_id=user, title=data['title'], message=data['message'], url=data['url']) and excute it using send_notification_to_all.delay(data) and that's my consumer class LiveNotificationConsumer(ListModelMixin, GenericAsyncAPIConsumer): serializer_class = NotificationSerializer permission_classes = (permissions.IsAuthenticated,) async def accept(self, **kwargs): await super().accept(** kwargs) await self.model_change.subscribe() @model_observer(Notification) async def model_change(self, message, observer=None, action=None, **kwargs): if message['user'] == self.scope['user'].id: await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, **kwargs): return NotificationSerializer(instance).data def get_queryset(self, *args, **kwargs): user = self.scope['user'] return Notification.objects.filter(user=user).using('notifications') -
call_command migrate problem python django
I'm trying to add dynamically app and do makemigrations and migration, but it doesn't show print ('2'). Reboots and asks to apply the migration manually some.py settings.INSTALLED_APPS += ('tests.apps.OrderConfig',) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() apps.populate(settings.INSTALLED_APPS) management.call_command('makemigrations','tests', interactive=False) print('>>WORK1') management.call_command('migrate', app_module.MODULE_NAME, interactive=False, skip_checks=True) print('>>WORK2') #this don't show Terminal: No changes detected in app 'orders' >>WORK1 Operations to perform: Apply all migrations: orders Running migrations: [11/Feb/2021 02:07:22] "GET /plugins/repository/12/ HTTP/1.1" 200 14459 C:\PythonProject\ServiceCRM3\plugins\settings_plugin.py changed, reloading. Applying orders.0001_initial...Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): orders. Run 'python manage.py migrate' to apply them. February 11, 2021 - 02:07:24 Django version 3.1.4, using settings 'ServiceCRM3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.