Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling djangorestframework API functions from a chrome extension (django)
I'm able to log in from the chrome extension with django-rest-auth: https://django-rest-auth.readthedocs.io/ I was told in #django on freenode that I need to use the sessionid it gives me as a cookie when I make requests to the API. At the moment, after I log in (which works), whenever I try to make requests to the API, I get 401 Unauthorized errors. Anyone know why? My jquery code (irrelevant code has been omitted): API = { create_tutorial : function(){ $.ajax({ url: API.url_base + '/api/create_tutorial/', type: 'POST', datatype:'json', data: { title: $('#title').val(), }, xhrFields : { withCredentials: true, }, success: function(d) { Data.current_working_tut = d.id; Template.resets.reset_tut_create_form(); $('#create-tut-2-tab').click(); }, }); }, } My DRF code (irrelevant code has been omitted) @api_view(['POST']) @permission_classes((IsAuthenticated,)) @ensure_csrf_cookie def create_tutorial(request): if request.method == 'POST' and request.is_ajax(): data = request.POST tutorial = Tutorial.objects.create( title=data.get('title'), page_url=data.get('page_url') ) return Response({'msg': 'successfully created tutorial', 'id': tutorial.id}) Please help. Thanks in advance -
'bool' object is not iterable when trying to exclude a row from a filtered queryset with django
I have two models, contestant and team, setup like so: class Contestant(models.Model): contestant_email = models.EmailField(max_length = 254) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) assigned_team = models.ForeignKey('Team', on_delete=models.SET_NULL, blank=True, null=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) class Team(models.Model): team_name = models.CharField(max_length=200) team_description = models.CharField(max_length=200) team_leader = models.ForeignKey(Contestant, on_delete=models.SET_NULL, blank=True, null=True) In a queryset, I am filtering contestants to be limited to the same team as the requesting user. I am then trying to exclude the current user from being included in the the results. My attempt is: class myteam(LoginRequiredMixin, SingleTableView): def get_queryset(self): qs = Contestant.objects.filter(assigned_team=self.request.user.contestant.assigned_team) qs = qs.exclude(id==self.request.user.contestant.id) return qs def get_template_names(self): return 'xgames/viewteam.html' def get_table_class(self): return TeamTable This gives the error 'bool' object is not iterable Why is this? What is the issue in excluding one record from a filtered set? -
I am getting empty values when i print a variable
Actually i am trying to build a virtual payment system. Its simple and easy but ITs not working. I have a veiw for UserInvoice for this payment method : class UserInvoice(View): def map_func(self, product): cart = self.request.session.get('cart', None) product_id = str(product.id) if product_id in cart: return product.price * cart[product_id] def get(self, request, id): user_orders = Order.objects.get(pk=id) args = {'user_orders':user_orders} return render(self.request, 'Home/invoice.html', args) def post(self, request, *args, **kwargs): ids = list(request.session.get('cart').keys()) cart_products = Product.get_products_id(ids) product_prices = list(map(self.map_func, cart_products)) print(product_prices) total_due = sum(product_prices) print(total_due) balance = request.session['customer']['coin'] if balance >= total_due: balance = balance - total_due print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get(id = request.session['customer']['id']) customer.coin = balance customer.save() request.session['customer']['coin'] = balance return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Failed") Here i tried to fetch cat total and customer balance. After that i want to substract total balance with Cart total. When i try to print total_due it returns me 0, and also when i try to print products prices i mean cart total it also return empty queryset.Fot that reason this method is not working properly. But i have same function to find out the cart total in cart page Here it is : class Cart(View): ## Changes def … -
Accessing Objects Attributes Within Ajax
I am adding ajax to my website. I originally had this button: {% for item in notifications %} <a class='delete' href="{% url 'delete' item.slug %}"> But changed it to Ajax. {% for item in notifications %} <a class='delete'> $(document).on('click', '.delete', function (e) { $.ajax({ url: '/users/ajax/delete/', data: { // here I was to call the 'delete' function in the 'django.notifications' package // something like 'notifications.delete(slug)' }, dataType: 'json', success: function (data) { alert("Working"); } }); }); This Ajax fires correctly, but I don't know how to get item.slug in Ajax. I guess I could do this <a class='delete' slug="{{ item.slug }}"> and access the slug, but it seems really sloppy. Is there a way to pass an object's attributes to Ajax without setting it as a value within the html code itself? Thank you. -
Server Error 500 for serving Media files on Heroku Django?
Everything is working locally with DEBUG = True, but not False. Adding the media urls to the urlpatterns fixed everything locally for DEBUG = False. But I'm still getting Server Error 500 on Heroku when trying to display these images which are located in MEDIA... Any ideas how to fix? Here is the error from heroku with DEBUG = True: -
VS Code Python extension prompts me to select an interpreter when one is selected
I am trying to debug my Django application, but VS Code's Python extension prompts me to select an interpreter any time I hit run, even after I've selected the Python executable in my virtual environment. launch.json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": ["runserver", "localhost:9000", "--noreload"], "django": true, "console": "externalTerminal" } ] } What can I do to make this pesky alert go away so I can start debugging? -
How do I reference my own record in a model in a Django view?
I have two models, Contestant and Team, which have a relationship with each other. They are defined like so: class Contestant(models.Model): contestant_email = models.EmailField(max_length = 254) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) assigned_team = models.ForeignKey('Team', on_delete=models.SET_NULL, blank=True, null=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) class Team(models.Model): team_name = models.CharField(max_length=200) team_description = models.CharField(max_length=200) team_leader = models.ForeignKey(Contestant, on_delete=models.SET_NULL, blank=True, null=True) I'm trying to build a link "My Team", which will show all the contestants on the team of the logged in contestant. I can't hardcode this, so need to get the contestants team in the view somehow so I can filter my queryset. I got as far as this attempt below: class myteam(LoginRequiredMixin, SingleTableView): def get_queryset(self): qs = Contestant.objects.filter(assigned_team__id=self.request.user__assigned_team__id) return qs def get_template_names(self): return 'xgames/viewteam.html' def get_table_class(self): return TeamTable I realize my attempt of assigned_team__id=self.request.user__assigned_team__id is incorrect, but I also realized I can't see any way to retrieve the team id of the user calling the view and use it to filter my queryset. This has to be a pretty common use case and I'm sure there is a simple solution, but I haven't been able to figure it out, and searching brings up too many unrelated results. What is the correct … -
Django collected static files are not accessible by templates
I've created a django project with some apps. Initially, I just had a single app and i had static files and templates in it. As my project grew, I added some other apps to the project which they are still accessing the statics files and templates from inside the main app. I wasn't giving much care to this problem until i tried to make a simple production and used collectstatic command. Seems i can collect my static files to the STATIC_ROOT directory but i can't access them in the templates. Here is my project structure: shop/ -myshop(main app) --statics --templates -(some other apps beside main app) -shop(directory created by project containing settings.py, manage.py) This is my relevant settings.py configurations: BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'myshop/static', ] STATIC_ROOT = BASE_DIR / 'static' After running collectstatic django creates the static directory in root of project but when i remove or rename the myshop/static i get static files 404 in runserver. I dont know how to check {% load static %} resulting path in runtime to put more information here. What's wrong? -
Retrieving current user id inside a function defined into class (CreateView)
Is possible to retrieve the current logged user id into a function defined inside a class, in views.py, using Django CreateView? Something like this: class CreationClass(CreateView): model = Mymodel def creation(self, request): form = myForm() user_id = self.request.user.id -
NoReverseMatch at /products/ Reverse for 'product-update' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P<pk>[0-9]+)/edit/$']
Struggling with some code. I have seen a lot of people have had this problem, but I can't seem to get their code fixes to work with mine (of course modifying to fit my project). I am still really new to this. I want to be able to edit a product from the list of products on product_list.html. I have created a HTML page called product_update.html in which you can edit the product, and this works. But I would like to direct an 'Edit' link on the product_list page to that product_update page. I am getting this error: NoReverseMatch at /products/ Reverse for 'product-update' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P[0-9]+)/edit/$'] Here is my code: views.py from django.http import Http404 from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import UpdateView from .forms import ProductForm, RawProductForm from .models import Product def product_list_view(request): queryset = Product.objects.all() context = { "object_list": queryset } return render(request, "products/product_list.html", context) # ------------------------------------------------------------ # class UpdateProductView(UpdateView): model = Product template_name = 'products/product_update.html' fields = ['title', 'image', 'description', 'price', 'summary', 'featured'] product_list.html {% extends 'base.html' %} {% block content %} {% for instance in object_list %} <p> {{ instance.id }} - <a href="{{ instance.get_absolute_url }}">{{ instance.title … -
Auto complete jquery not working using Django framework
I am trying to perform an autocomplete for a search box but am not getting any requests back when typing. Index.html Url.py Views.py -
Is this the correct usecase for Django/Pythong > WebApplication
I really hope this is the right place for this question or else please lmk what i can change. Also, I'm pretty much a total beginner in programming, did only a little bit of C in Uni. I recently started my Master Thesis and my task is to program a Web Application in Python/Django based on a Matlab program, which already exists. It includes a lot of user-input and uses it to calculate and visualize stuff (mostly simple formulas), but it includes plenty of tabs and user-profiles. The question is now if this is even the right way to go. I just now learned that Matlab offers its own WebApp Server (Which I'm not quite sure yet how to qualify for). Also i'm not really sure if Django is even the right Framework to use... I would be very happy if anybody could point me in the right direction here :) If you need any additonal information, please let me know, i'll do what I can. Cheers -
'str' object has no attribute 'get' error; in Django template when using dictionary
I am trying to retrieve some values from a dictionary in my template, so I defined the following template tag @register.filter('get_value_from_dict') def get_value_from_dict(dict_data, key): if key: return dict_data.get(key) and use it as follows {% for item in query_ %} <td>{{ mydictionary | get_value_from_dict:item.id }}</td> {% endfor %} However it gives me the following error: 'str' object has no attribute 'get' I made sure that I am passing an actual dictionary and not a string so this works fine in my template {% for key, val in mydictionary .items %} <p>{{ key }}</p> <p>{{ val }}</p> {% endfor %} which has some values like: sub_ITWGauJH5czYPL False sub_ITWEjGl6PTLXBN True I was wondering where can be my error? -
Django user subscribe user relation
I`m creating a simple blog now, and the main problem is to create a relation between Users. I use a default django User which should subscribe another user who is an author of post. I have only one Post model in my app class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=128) content = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) seen = models.ManyToManyField(User, related_name='blog_posts', blank=True) -
dictionary in template tag django
I would like to extract something like bellow: {% for item in query_ %} <td>{{ mydictionary[item.id] }}</td> {% endfor %} which of course gives me a syntax error. For this purpose I have defined a template tag @register.filter('get_value_from_dict') def get_value_from_dict(dict_data, key): if key: return dict_data.get(key) and then use it as follows: {% for item in query_ %} <td>{{ mydictionary | get_value_from_dict : item.id }}</td> {% endfor %} however it doesnt work and gives me the following error: get_value_from_dict requires 2 arguments, 1 provided I was wondering what I am doing wrong. -
What do these lines of code do to my django models?
Hi there I recently started learning the django rest framework by reading the django rest docs. I made it to the Authentication & Permissions chapter and came across these two lines of code; owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) highlighted = models.TextField() It says that I should add them to my models, but I dont want to do that without understanding what do they do/mean. Can anyone tell me? -
Django: Is there a way to filter out 503 'service unavilable' responses from mail_admins log handler?
I have django LOGGING configured with standard "mail admins on 500 errors": 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, When I put site into maintenance mode (django-maintenance-mode), it correctly responds with 503 "Service Unavailable" for anonymous requests. This causes a barrage of emails to admins when the site is in maintenance mode. I want to "filter out 503 response IF site is in maintenance mode" to stem the flood. But can't see a simple way to do this (e.g., logging filter would need request to check if site in maintenance mode) I know I could change the maintenance error code to a 400-level error, but that seems like non-semantic hack. Could also suspend admin emails during maintenance, but that requires remember to hack / revert settings file. Hoping someone has a clever idea how to achieve this simply, no hacks. -
How do I set upload/download progress in response? (swift & Django)
How do I get the upload and download progress? Heres how what Im doing in Xcode according to alamofire docs this is supposed to get the progress, buts only printing 0 in download and 1 in upload. AF.download("http://127.0.0.1:8000/") .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseData { response in if let data = response.value { let image = UIImage(data: data) } } let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") AF.upload(fileURL, to: "http://127.0.0.1:8000/") .uploadProgress { progress in print("Upload Progress: \(progress.fractionCompleted)") } .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseDecodable(of: HTTPBinResponse.self) { response in debugPrint(response) } Heres how I'm responding to these requests in Django // for download def test (request): file = File.objects.get(user=curUser) return FileResponse(file.file) //for upload s = File(file=f, user=curUser) s.save() return JsonResponse({'status': 'ok'}) I read that this might be because I need to set up my server so it also sends progress % back. But im not sure how I would implement this. Can someone point me to the right direction? -
React and Django REST not fully authenticating
I built a app with react, django and used DRF, I have a log in page which when successful passed a token, basically, it logs in fine but just noticed that i have a component which gets data from a particular logged in user and i used "IsAuthenticated" as a decorator, I notice it shows in the API, but not in my frontend, I removed "IsAuthenticated" decorator, and check the network then i noticed it shows: 'AnonymousUser' object has no attribute 'follow_user' ... even when im logged in react. Please help I dont understand what is going on. -
Django - Parse a list typed in by user in a form and link each element of the list with the first value of the first field of the form
I am new to django but really want to learn how to use this framework. What want to do : I have a form, that allows the user to create a new client for example. So in this form I have 3 fields : Name Description Skills The 'Skills' field is currently a text area, where the user would copy and paste a list already existing in another document(excel). Therefore, each element is separated by a splitline. What I would like to do is : create in the database the client entered by the user In the database, link the description entered by the user to the client In the database, link each skill entered by the user to the name so that I can work on them independantly of each other in further functions/apps. I don't want all of the skills to be linked to the client as one big bloc. So I read the documentation and thought about using a ForeignKey. The thing is I was unable to get an input text area when using a ForeignKey. Everytime I used it I got an empty 'select list'... An even though I would be able to get that, I … -
Django serve file in memory instead of saving on disk
I want to render plot (matplotlib) in one place of code and then in ViewSet serve to it user without saving on disk. I tried to use io library to keep file in memory, but it seems that always something is wrong. My code where I save plot on disk: def some_func(self): ...generating plot... filename = self.generate_path() # generate random name for file plt.savefig(filename, transparent=True) return filename Code of ViewSet: class SomeViewsSet(ViewSet): def create(self, request): ... some code ... path = some_func() name = path.split('/')[-1] with open(path, 'rb') as file: response = HttpResponse(file, content_type=guess_type(path)[0]) response['Content-Length'] = len(response.content) response['Content-Disposition'] = f'attachment; filename={name}' return response -
Rendering the page in django with html form
I have these two functions, one of them (first one) adds a new entry and the second one edits the entry: def add_entry(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] if util.get_entry(title) is None: util.save_entry(title, content) return redirect('entry', title) else: return render(request, "encyclopedia/add_entry.html", { "form": AddForm(), "title": title }) return render(request, "encyclopedia/add_entry.html", { "form": AddForm() }) def edit_entry(request, title): content = util.get_entry(title) if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return redirect('entry', title) return render(request, "encyclopedia/edit_entry.html", { "title": title, "content": content Here is my edit_entry.html page: {% extends "encyclopedia/layout.html" %} {% block title %} Edit page {% endblock %} {% block body %} <form action="{% url 'edit_entry' title %}" method="POST"> {% csrf_token %} <h5>Title</h5> <input type="text" value="{{ title }}"> <h5>Content</h5> <textarea cols="30" rows="10">{{ content }}</textarea> <input type="submit" value="Save Editing"> </form> {% endblock %} This is add_entry.html template {% extends "encyclopedia/layout.html" %} {% block title %} Add new entry {% endblock %} {% block body %} <h1>Create a new page</h1> {% if title %} <h6 style="color: red;">"{{title}}" page is already exists. Please, enter a different title</h6> {% endif %} <form action="{% url 'add_entry' %}" … -
How to use dispatch_uid to avoid duplication Signals correctly
Helloo, I am trying to apply using a dispatch_uid="my_unique_identifier" in order to avoid duplicate signals sent in my project. I have searched for several similar answers and read the following documentation but I am not sure what I am missing: https://docs.djangoproject.com/en/3.1/topics/signals/#preventing-duplicate-signals In my project there are posts that are written by Author, each post has a like button which when clicked by a user notification is created and sent to the author. Until here everything is fine except that 2 notifications are sent instead of 1. I have tried the following but it did not have any effect and I am still receiving 2 notifications So here it is: Here is the Like model.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) def user_liked_post(sender, instance, *args, **kwargs): like = instance if like.value=='Like': post = like.post sender = like.user dispatch_uid = "my_unique_identifier" notify = Notification(post=post, sender=sender, user=post.author, notification_type=1) notify.save() post_save.connect(Like.user_liked_post, sender=Like, dispatch_uid="my_unique_identifier") Here is the notifications model class Notification(models.Model): NOTIFICATION_TYPES=((1,'Like'),(2,'Comment'),(3,'Admin')) post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name="noti_post", blank=True, null=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="noti_to_user") notification_type= models.IntegerField(choices=NOTIFICATION_TYPES) def __str__(self): return str(self.post) My question is how to use dispatch_uid="my_unique_identifier" correctly inorder to avoid duplicated … -
No effect from the signals
I want my app users to listen to the action of creating a User instance and exactly after that initialise (create) an Account instance: Unfortunately the following does not work at all: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Account @receiver(post_save, sender=User) def create_account(sender, instance, created, **kwargs): if created: Account.objects.create(user=instance) @receiver(post_save, sender=User) def save_account(sender, instance, **kwargs): instance.account.save() and my apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals I create a user but it does not dispatch the action for the receivers to created an Account instance. At leas I cannot see them in the Django default administration region. -
How to get a column value from a HTML table using django
I have a HTML table with checkboxes. I want to read the first column value based on the row selected using the checkbox. To read the values, a function is called after selecting the checkbox and clicking a button. Table look this way <a href="{% url 'app-analyze_retina' %}"> <button onclick="" class="patient-add-btn button1"> Send for Analysis </button> </a> {% if btn_clicked %} <div> <table class="table" id="patient_list"> <thead class="thead-dark"> <tr> <th scope="col">Patient ID</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Result/Severity Level</th> <th scope="col">Tested on</th> <th scope="col">AI confidence</th> <th scope="col">Comments</th> </tr> </thead> <tbody> {% for patient in data %} <tr> <td bgcolor="mediumaquagreen"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="checks" id={{patient.0}} value="{{patient.1}}"> <label class="custom-control-label" for={{patient.0}}>{{patient.1}}</label> </div> <!-- <td bgcolor="mediumaquagreen" > {{ patient.1 }}</td>--> <td bgcolor="mediumaquagreen">{{patient.2}}</td> <td bgcolor="mediumaquagreen" >{{patient.3}}</td> <td bgcolor="mediumaquagreen">2.846</td> <td bgcolor="mediumaquagreen">-</td> <td bgcolor="mediumaquagreen" >Cristina</td> <td bgcolor="mediumaquagreen" >913</td> </td> </tr> {% endfor %} </tbody> </table> </div> {% endif %} Function to read the values def analyze_img(request): c = request.POST.getlist('checks') print(c) First I was trying to check whether I am able to read a checkbox but it returns an empty list.