Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object has no attribute 'key' django drf
i have this model city and trying to get foreign table data geeting models.py: class City(BaseModel): name = models.CharField(_("City Name"), max_length=80, null=False, blank=False) state_name = models.ForeignKey(State, to_field="uid", on_delete=models.DO_NOTHING, max_length=55, null=False, blank=False) city_type = models.ForeignKey(TypeOfCity, to_field="key", on_delete=models.DO_NOTHING, max_length=15, null=False, blank=False) city_tier = models.ForeignKey(CityTier, to_field="key", on_delete=models.DO_NOTHING, max_length=10, null=False, blank=False) status = models.SmallIntegerField(_("Status: 1 for Active; 0:Inactive"), default=1) class TypeOfCity(models.Model): key = models.CharField(verbose_name=_("key"), max_length=15, unique=True) value = models.CharField(verbose_name=_("value"), unique=True, max_length=15) status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1) views.py: @api_view(['POST']) def cityFetch(request): try: data =decode_data(request.data.copy()) try: queryset = City.objects.filter(uid=data['uid']).values('name','city_type','city_type__value','status') serializer_obj = CitySerializer(queryset,many=True) return CustomeResponse(request=request, comment="Get Single City", message="Get Single City", data=json.dumps(serializer_obj.data, cls=UUIDEncoder), status=status.HTTP_200_OK) except City.DoesNotExist: return CustomeResponse(request=request, comment="City Not Found", message="City Not Found",data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) except Exception as e: print(e) error_str = UID_KEY_IS_MISSING if type(e) is KeyError else UID_IS_NOT_VALID return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), comment=error_str, message=error_str, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) I am getting this queryset: <QuerySet [{'name': 'test', 'city_type': 'normal_city', 'city_type_id__value': 'Normal City', 'status': 1}]> but maybe its trying to find key and i am getting this error: 'str' object has no attribute 'key' -
Django dynamic categories Using Models
Im trying to make dynamic category using foreign key in django but not able to save drop down category this is my view.py @login_required(login_url='login') @admin_only def add_product(request): name = request.POST.get('name') description = request.POST.get('description') price = request.POST.get('price') select = request.POST.get('dropdown') b = Product.objects.all() categories = Category.objects.all() if request.method == 'POST': b = Product.objects.create(name=name, description=description, price=price, category=select) return render(request, 'product.html', {'b': b, 'category': categories }) this is models.py class Category(models.Model): categoryname = models.CharField(max_length=255, null=True) def __str__(self): return self.categoryname class Product(models.Model): name = models.CharField(max_length=255, blank=False, null=True) description = models.CharField(max_length=255, blank=False, null=True) price = models.CharField(max_length=50, blank=False, null=True) date = models.DateTimeField(auto_now_add=True, null=True) category = models.ForeignKey(Category, on_delete= models.CASCADE, null=True) def __str__(self): return self.name this is html for add product {% block content %} <div class="container"> <div class="row"> <form class="center-align" action="{% url 'addproduct' %} " method="POST"> {% csrf_token %} <div class="input-field col s12"> <input value="" id="name" name="name" type="text" class="validate"> <label class="active" for="name">ProductName</label> </div> <div class="input-field col s12"> <input value="" id="des" name="description" type="text" class="validate"> <label class="active" for="des">Description</label> </div> <div class="input-field col s12"> <input value="" id="price" name="price" type="text" class="validate" required> <label class="active" for="price">Price</label> </div> <div class="input-field col s12"> <select name="dropdown" class="browser-default"> <option value="" disabled selected>Choose your option</option> {% for item in category %} <option value="{{ item.categoryname }}">{{ item.categoryname }}</option> … -
Django Models: Set Staticfile as ImageField
I have a Django project with a model that uses an ImageField. I need to set this ImageField to an image I've stored in my staticfiles, or alternatively somewhere in my project files. In short: I have a staticfile or image file located somewhere in my Django project path. I have an ImageField I need to set this ImageField as the staticfile or locally stored file. I am fine with redundancy, such as this staticfile then being uploaded to my media_root. How can I set an ImageField to an image stored in my Django project? -
Ranking organizations based on their ratings in django
I am building an app which lists different products based on their average user ratings. I have two questions, how to calculate the average ratings on basis of ratings given by the user and second, how to display them in a ranked list based upon their ratings. I would greatly appreciate if someone could point me in the right direction. -
How do i allow only my friends to see my post
I'm a Django beginner, how do I allow only my friends, people who follow me (from_user) and people I follow (to_user) to see my post. I tried this but I'm not getting any results. def home(request): friends_posts=[] if request.user.is_authenticated: posts=Image.object.exclude(imageuploader_profile=request.user) for p in posts: if p.imageuploader_profile in request.user.friends.all(): friends_posts.append(p) context={'friends_posts':friends_post} return render(request, 'home.html', context) Models.py class Profile(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL) friends=models.ManyToManyField('Profile' related_name='my_friends') class FriendRequest(models.Model): to_user=models.ForeignKey(settings.AUTH_USER_MODEL) from_user=models.ForeignKey(settings.AUTH_USER_MODEL) class Image(models.Model): imageuploader_profile=models.ForeignKey(settings.AUTH_USER_MODEL) upload_image=models.ImageField() -
Chunk wise deleting data from database in django
just say i fetched data in chunks from a table with 20 million entries and i need to process the whole data and need to delete whole data only once everything is processed (my condition is i cant delete inside the loop where it is getting fetched) chunk = 10000 id_gte = 1 id_lt = 20000000 delete_query = MyModel.objects.none() for i in range(id_gte, id_lt, chunk): data = MyModel.objects.filter(id__gte=i, id__lt=i+chunk) print(data) delete_query |= data now if i want to delete the data...that i fetched in the loop, so i can do delete_query.delete() So my doubts are. Does the time to delete the data that is deleted depends on that how much data i am deleting at once? Like above i am trying to delete the whole 20000000 rows at once. Will it be better to delete the data in chunks? Say in delete_query, i use a loop to get the cached chunks of queryset of size 10000 and delete them? So overall it will take maybe the same time, but it will lock the db for smaller times? Does any evaluation done to delete the data from database? if yes, then is the query re-evaluated to delete the data. I mean … -
how do i set radio button as checked based on database values in django template?
here is my html code <input type="radio" name="cast" id="open" style="margin-left:10px;text-align:left;" value="Open" {% if data.cast %}checked{% endif %} required>Open <input type="radio" name="cast" id="sebc" style="margin-left:10px;text-align:left;" value="SEBC" {% if data.cast %}checked{% endif %} required>SEBC <input type="radio" name="cast" id="sc/st" style="margin-left:10px;text-align:left;" value="SC/ST" {% if data.cast %}checked{% endif %} required>SC / ST <input type="radio" name="cast" id="other" style="margin-left:10px;text-align:left;" value="Other" {% if data.cast %}checked{% endif %} required>Other I did this but it didn't work for me. the data.cast is variable having database value. -
Django Rest-framework: Migration No changes detected
I'm new to python and django, I'm creating a simple shopping app. I have followed all the steps to create django rest-framework project, run the server and it works. What I did is created a new folder called Models (deleted the pre-defined models.py) and created inside it many model classes in addition of an __init__.py file as I red and imported all the classes inside it. When running python manage.py makemigrations it return ''No changes detected''. Here is the structure: quickstart/ . . `Models/ __init__.py model1.py model2.py . . . tutorial/ manage.py -
how to render django model permission in my own templates in tabular format
I want to render django model permission in my own template. I tried this one called django-tabular-permission package. But it only works for django admin. I didn't know either it works for custom template or not. My requirements is somethings like django tabular permission but in my own templates. Any suggestion would be appreciated. I'm new to django and i love django model permission concept. -
Django Models: Set ImageField Default
I'm working on a Django project and using S3 as storage. I have a model that has a photo ImageField, however I'd like to specify a default as something from my staticfiles. The user can change this later, but initially I would like to supply one of a few specific random images from my own static files. Something like: class StoreObject(models.Model): ... photo = models.ImageField(upload_to='media', default='what/goes/here?') ... How can I do this? I found a few relevant answers here, but none are exactly what I need. Programmatically saving image to Django ImageField -
How can I run a project in a local server using Pycharm?
when I try to run a project in a local server using Pycharm, I can't do that with these errors. So would you mind telling me how should I solve this problem? Thank you in advance. Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 11, in <module> from django.conf import settings File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 17, in <module> from django.conf import global_settings ImportError: cannot import name 'global_settings' from 'django.conf' (/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 21, in <module> main() File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Python Console import sys; ... ...print(sys.path) ['/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/third_party/thriftpy', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages', '/Users/apple/GoogleDrive/project_django'] Development environment Mac: mojave 10.14.6 Python: 3.7.5 Django: 2.2.2 Pycharm: 2019.3.1 (community edition) -
Design patten to access internal python api server on local and production
I have django project which has restful api framework, and some commands. For now, I can accesing api like, python manage.py mycommand url = "http://localhost/api/tasks" r_get = requests.get(url) If only development on localhost. But sometimes port need to be changed on production. Even more my production environment is clustering. API server and Commandline server will be separate on docker-swarm How should I write the python code?? What is the good practice for this purpose?? -
How to setup login page using django-microsoft-auth in a django project
I am using django-microsoft-auth in my Django project. I followed this guide. Now, I'm able to log in through Microsoft account(address: http://localhost:8000/admin ) but I don't know how to add a view that will say "Login using Microsoft" and how to link that view with Microsoft authentication page. It will be great if someone can tell me how to do this. -
What is the right way of including and extending templates in django
I have a page template, as shown. <!DOCTYPE html> <html> <head> <base href=''> <meta charset='utf-8'></meta> <meta name='description' content=''></meta> <meta name='author' content=''></meta> <meta name='keywords' content=''></meta> <meta name='viewport' content='width=device-width, initial-scale=1'></meta> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> <title></title> </head> <body> {% include "waffle.html" %} </body> </html> And a waffle template as shown {% block content%} {% endblock %} And an index thats supposed to extend the waffle, as shown: {% extends "waffle.html" %} {% block content%} The home page look and feel starts here. {% endblock %} And a view thats supposed to display my templates, as shown from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, "index.html") My problem is that this is not working, and I have absolutely no idea. I am coming from php and trying to learn django, but this templating thing is frustrating me. Any ideas of what I might be doing wrong here -
How to add a user in the admin page?(getting error)
Django version: 2.1.5 When I tried to add a user in the admin page it gave me this error: OperationalError at /admin/auth/user/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://localhost:8000/admin/auth/user/add/ Django Version: 2.1.5 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\themi\Envs\project\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 298 Python Executable: C:\Users\themi\Envs\project\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\themi\\OneDrive\\Desktop\\myfirstdjango', 'C:\\Users\\themi\\Envs\\project\\Scripts\\python38.zip', 'c:\\users\\themi\\appdata\\local\\programs\\python\\python38-32\\DLLs', 'c:\\users\\themi\\appdata\\local\\programs\\python\\python38-32\\lib', 'c:\\users\\themi\\appdata\\local\\programs\\python\\python38-32', 'C:\\Users\\themi\\Envs\\project', 'C:\\Users\\themi\\Envs\\project\\lib\\site-packages'] Server time: Sun, 22 Mar 2020 07:47:59 +0000 I know this question has been answered before but the solutions didn't work for me. -
django annotate unexpected limit 21
I want use django ORM to finish count group by, but select sql unexpected limit 21 every time. I don't want the limit, why limit 21 appear, and how can I get all data? model: class Company(models.Model): company_no = models.CharField(primary_key=True, max_length=128) name = models.CharField(max_length=128) is_test = models.BooleanField(default=False) class Meta: db_table = 'company' class User(models.Model): symbol = models.BigIntegerField(primary_key=True) is_test = models.BooleanField(default=False) class Meta: db_table = 'user' class UserEmploy(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='symbol', to_field='symbol', related_name='employ') company = models.ForeignKey(Company, on_delete=models.CASCADE, to_field='company_no', db_column='company_no', related_name='user_employ') class Meta: db_table = 'user_employ' django code in my views: employ_qs_exclude_test = UserEmploy.objects\ .exclude(user__is_test__in=utils.IS_TEST_MODE)\ .values("company__name") \ .annotate(employ_count=Count('user', distinct=True))\ .order_by('company') sql log: SELECT `company`.`name`, COUNT(DISTINCT `user_employ`.`symbol`) AS `employ_count` FROM `user_employ` INNER JOIN `user` ON (`user_employ`.`symbol` = `user`.`symbol`) INNER JOIN `company` ON (`user_employ`.`company_no` = `company`.`company_no`) WHERE NOT (`user`.`is_test` IN (1)) GROUP BY `company`.`name`, `company`.`created_at` ORDER BY `company`.`created_at` DESC LIMIT 21; -
How to query mutations in react and fetch results in a div
All the examples I have been coming across they are fetching Inside a list box which is not understandable . Please help its really urgent. Thank you so much in advance -
Programming Error: relation "first_app_people" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "first_app_people"
I am trying to deploy my django app on heroku. But there is error which I don't understand what type of error is this.Please help to solve this error: Programming Error: relation "first_app_people" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "first_app_people" models.py class People(models.Model): name = models.CharField(max_length=220) slug = models.SlugField(unique=True) money = models.IntegerField() status = models.CharField(max_length=120, null=True, choices=Status) date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.name def get_absolute_url(self, *args, **kwargs): return reverse("first_app:detail", kwargs={"slug": self.slug}) views.py from django.shortcuts import render, get_object_or_404, redirect from .models import People from .forms import PeoplesForm def home_page(request): form = People.objects.all() stock = form.count() sell = form.filter(status='Fowara_Chowk').count() sold = form.filter(status='Station').count() context = { 'form': form, 'stock': stock, 'sold': sold, 'sell': sell, } return render(request, 'index.html', context) def create_view(request): form = PeoplesForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'create.html', context) def detail_view(request, slug): form = get_object_or_404(People, slug=slug) context = { 'form': form } return render(request, 'detail.html', context) def update_view(request, slug): form = People.objects.get(slug=slug) update_form = PeoplesForm(instance=form) if request.method == "POST": update_form = PeoplesForm(request.POST or None, instance=form) if update_form.is_valid(): update_form.save() return redirect('/') context = { 'form': update_form, } return render(request, 'update.html', context) def delete_view(request, … -
Folium map not getting rendered within iFrame in django
I am trying to use folium maps within django. From views.py, map_html is passed onto sample_map.html as context variable. Inside sample_map.html, I am trying to render the map_html within an iFrame. (I have to use iFrame as folium returns complete html) Issue: The map is getting rendered, but outside of iFrame. I am able to render some plain html like <html><body>It works</body></html> onto the iframe without any issues. views.py import folium def show_map(request): m = folium.Map([17.3850, 78.4867], zoom_start=10) map_html = m.get_root().render() context = {'map_html': map_html} return render(request, 'sample_map.html', context) sample_map.html <!DOCTYPE html> <html lang="en"> <body> <iframe id="foo"></iframe> <script src="https://code.jquery.com/jquery-3.4.1.min.js" .. ></script> <script> $(document).ready(function() { var iframe = document.getElementById('foo'), iframedoc = iframe.contentDocument || iframe.contentWindow.document; // iframedoc.body.innerHTML = "<html><body>Content gets rendered within iframe as expected</body></html>" iframedoc.body.innerHTML = "{{map_html|safe}}" // content gets rendered outside the iframe }); </script> </body> </html> sdfas -
Jquery autocomplete not filtering JSON data from django
I tried the Jquery autocomplete for entering country name in a input field. Instead it is binding all the JSON data and the search does not filter from the JSON data. JQUERY Autocomplete function for country $("#ddlCountry").autocomplete({ source: function(request, response) { $.ajax({ type: 'GET', url: 'country', dataType: "json", data: { term: request.term }, success: function(data) { console.log(request.term) response($.map(data, function(item, key) { return { label: item.country_name, value: item.id } })); }, error: function(xhr) { console.log('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText); } }); }, minLength: 2, select: function(event, ui) { e.preventDefault() }, focus: function(event, ui) { e.preventDefault() }, }); Views.py def country_list(request): if request.method == "GET": if request.is_ajax(): obj_country_list = Country.objects.values("id", "country_name") return HttpResponse(json.dumps(list(obj_country_list))) JSON DATA {"id": 1, "country_name": "Afghanistan"}, {"id": 2, "country_name": "Albania"}, {"id": 3, "country_name": "Algeria"}, {"id": 4, "country_name": "Andorra"}, {"id": 5, "country_name": "Angola"}, {"id": 6, "country_name": "Antigua and Barbuda"}, {"id": 7, "country_name": "Argentina"}, {"id": 8, "country_name": "Armenia"}, {"id": 9, "country_name": "Australia"}, {"id": 10, "country_name": "Austria"}, {"id": 11, "country_name": "Azerbaijan"}, {"id": 12, "country_name": "Bahamas"}, {"id": 13, "country_name": "Bahrain"}, {"id": 14, "country_name": "Bangladesh"}, {"id": 15, "country_name": "Barbados"}, {"id": 16, "country_name": "Belarus"}, {"id": 17, "country_name": "Belgium"}, {"id": 18, "country_name": "Belize"}, {"id": … -
Is it safe to send form's data (POST) asynchronously to the server?
I would like to know (I know almost nothing about this) if it's dangerous to send a form using the post method and a function like the following one. I started to questioning this method because the html code can be modified. If not, what should I change? As example, the following function is provided: script.js function fname(){ var https = new XMLHttpRequest(); https.open("POST", "url", true); https.setRequestHeader('X-CSRFToken', getCookie('csrftoken')); var varname = "data_from_input"; https.send(varname); } -
Define two fields on serializer in DRF in which one of them is required
I want to create a serializer that let users to login with their username or phone number, Now if they use a phone number or username I need different validations. I know that I can achieve this in the view, however, I'm looking for a solution to handle this situation in the serializer. -
How to handle media file errors in django templates?
Here I successfully uploaded files in database(working fine). The issue here is file is stored in the database and if in case the media folder gets deleted it will raise an error [WinError 2] The system cannot find the file specified: ... So my question is how can I handle this error. If the file is in database but not in the media folder then I want to handle this error and display the template without error. How can I do this ? template {% for document in documents %} <tr> <td>{{forloop.counter}}</td> <td>{{document.filename|truncatechars:15}}</td> <td>{{document.file.size|filesizeformat}}</td> <td>{{document.category}}</td> <td>{{document.file.url}}</td> <tr> {% endfor %} -
django pagination category wise
How Can use pagination in my Category page in django def englishStatus(request): allpost=[] catpost=Content.objects.values('category','id') cats={item['category'] for item in catpost} for cat in cats: if cat=="englishStatus": post=Content.objects.filter(category=cat) n=len(post) allpost.append([post,range(1,n),n]) paginator=Paginator(allpost,4) page=request.GET.get('page') try: allpost=paginator.page(page) except PageNotAnInteger: allpost=paginator.page(1) except EmptyPage: allpost=paginator.page(paginator.num_pages) params={'allpost':allpost} return render(request,'status/englishStatus.html',params) I cant able to do pagination -
how to use ajax in postlistview as well as in postdetailview
I have a post detail where i successfully use ajax to like the post section so if anyone like the post it is asynchronously referesh the section. however i can't do it in the post list view. its not working asynchronously. Anyone who can help me to solve it. here is my views.py: @login_required def like_post(request): # posts = get_object_or_404(Post, id=request.POST.get('post_id')) posts = get_object_or_404(post, id=request.POST.get('id')) is_liked = False if posts.likes.filter(id=request.user.id).exists(): posts.likes.remove(request.user) is_liked = False else: posts.likes.add(request.user) is_liked = True notify.send(request.user, recipient=posts.author, actor=request.user, verb='liked your post.', target=posts, nf_type='liked_by_one_user') context = {'posts':posts, 'is_liked': is_liked, 'total_likes': posts.total_likes(),} if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) if request.is_ajax(): html = render_to_string('blog/likes_home.html', context, request=request) return JsonResponse({'form': html}) the likes_home section is for postlistview my likes_home.html: <script> $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like_post" %}', data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('#like-home').html(response['form']) console.log($('#like-home').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); </script> <form action="{% url 'like_post' %}" method="POST"> {% csrf_token %} {% if post.is_liked %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">dislike</button> {% else %} <button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">like</button> {% endif %} </form> and my …