Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting a TypeError at / 'str' object is not a mapping when I do this <a class="item" href="{% url 'home' %}">.
I am trying to set up links inside a tags, and when I do this procedure as seen in the code, it gives me the error specified. It use to work fine but then decided not to template code: href="{% url 'home' %} urls code: urlpatterns = [ path('admin/', include('admin_llda.urls') ), path('about/', views.about, name = 'about'), path('dashboard/',views.dashboard, name = 'dashboard'), path('',views.homepage, name = 'home') ] -
PyCharm doesn't autocomplete Django "models" in 2018.3.2
I've created my Django project with PyCharm. When I use the "objects" attribut in my model, he don't recognize "objects". Screenshot I've visited this page, but I haven't Django option in settings : "Settings/Languages & Frameworks/Django" ! -
Django migrations not detecting unique=True change
I am getting the following error after trying to add a foreign key from CrackingJob.hash_mode_numeric > HashMappings. Initially i was trying to set the FK directly to HashMappings.hash_mode_numeric without the unique constraint and it rightly gave the error, but after adding unique=True i still get the error. Even when i try to just use the PK (auto generated unique id) as FK, like in the code below, it gives the error. django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "appname_hashmappings" Relevant code: https://pastebin.com/AJdnPvPS class HashMappings(models.Model): hash_name = models.CharField(max_length=255, unique=True) hash_mode_numeric = models.IntegerField(unique=True) example_hash = models.TextField(max_length=2500) supported = models.BooleanField(default=0) class Meta: ordering = ['hash_name'] def __str__(self): return f'{self.hash_name}' class CrackingJob(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL) description = models.CharField(max_length=255) hash_mode_numeric = models.ForeignKey(HashMappings, on_delete=models.CASCADE) -
How to add logs in django
I am new to django I want to print log information in my console how to do that. and also what is the use of that things in django, why we need that one. -
Bootstrap layout with cards h-100
I am working with Bootstrap at the moment. I loop round & create lots of these cards (one for each task in the project. The problem is, if the card has a bigger title, then each card is not the same height. I want to be able to standardize the height, Originally I used: <div class="card"> Then I tried, the below, which does indeed make all the cards a standard height. <div class="card h-100"> As you can see on the second one, it removes the space between each row of cards, so I'm not sure how to standardise the size, while still retaining the spacing? Any ideas will be greatly appreciated: <div class="row"> <div class="col-sm-3"> <div class="card"> <h5 class="card-header">65 :new task from closed screen</h5> <div class="card-body"> <p class="card-text"> <table class="table table-hover"> <tr> <td>Created By</td> <td>kikee</td> </tr> <tr> <td>Project</td> <td>netshock</td> </tr> <tr> <td>Priority</td> <td class="table-danger">High</td> </tr> </table> <table class="table table-hover"> <tbody> <tr class="table"> <th scope="col"><form action="/complete/" name="form2", id="form2" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='8ALiONJGxPQaAnTYwsBUUnpny1YnyntTOccxk7VG7rTsltn2hT63KTTlv7rS09m3' /> <button name="donebutton" type="submit" value=65 data-toggle="tooltip" data-placement="top" title="Complete Task" class="btn btn-success"><i class="fas fa-check"></i></button></th> </form> <td> <!-- Button trigger modal --> <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#EditModal65"> <i class="far fa-edit"></i> </button> <!-- Modal --> <div class="modal fade" id="EditModal65" tabindex="-1" … -
Specifying field names in serializer class acting as another serializer class's field
Suppose for below ModelSerializer class class UserSongSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() song_likes = serializers.ReadOnlyField() # This is model's property field song_shares = serializers.ReadOnlyField() song_plays = serializers.ReadOnlyField() song_price = serializers.ReadOnlyField() genre = GenreSerializer(many=True,required=False,context={'key':5}) language = LanguageSerializer(many=True, required=False) Passing specific context kwarg like below genre = GenreSerializer(many=True,required=False,context={'fields':['name']}) Since I want to retrieve only name field in Genre model class in some specific cases, I overrided GenreSerializer class's get_fields_name method so that I can mention specific fields only when required via context class GenreSerializer(serializers.ModelSerializer): def get_field_names(self, *args, **kwargs): """ Overriding ModelSerializer get_field_names method for getting only specific fields in serializer when mentioned in SerializerClass arguments """ field_names = self.context.get('fields', None) if field_names: return field_names return super(GenreSerializer, self).get_field_names(*args, **kwargs) class Meta: model = Genre fields = '__all__' However, I am unable to get any 'fields' (getting None) key inside overrided get_fields_name method. I know of other ways as well like using StringRelatedField but that would change the output representation to "genre":[ "Pop", "Rock" ] Whereas, I want to stick to my original representation "genre": [ { "id": 3, "name": "Pop", "created_date": "2018-09-05T17:05:59.705422+05:30", "updated_date": "2018-09-20T14:43:02.062107+05:30", "status": false }, { "id": 4, "name": "Rock", "created_date": "2018-09-05T17:06:06.889047+05:30", "updated_date": "2018-09-17T16:45:22.684044+05:30", "status": true }, { "id": 5, "name": "Classical", "created_date": … -
Django: Group by date over a datetime field
I have for example a model like this: class Transaction(models.Model): amount = models.FloatField() seller = models.ForeignKey(User, related_name='sells', on_delete=models.CASCADE) buyer = models.ForeignKey(User, related_name='purchased', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) I want to group by all transactions seperated by each date and find some of them. If the created_at is of type DateField I could simply find the count on each day by this query: Transaction.objects..values('created_at').annotate(count=Count('created_at_date') But this doesn't work DateTimeFeilds. My question is how can i find total count of transactions for each date for this model type. -
Django: Group by date then calculate Sum of amount for each date
I have a django model like. it stores total transactions happened over time periods. class Transaction(models.Model): amount = models.FloatField() seller = models.ForeignKey(User, related_name='sells', on_delete=models.CASCADE) buyer = models.ForeignKey(User, related_name='purchased', on_delete=models.CASCADE) created_at_date = models.DateField(auto_now_add=True) my question: is that how can i find total amount of transactions for each day. for each day it should calculate Sum of all transactions in that day. I need for example do this for last 7 days. -
Add button for child model in Django admin
Django 1.11. I have 2 models, Foo and Bar: class Foo(models.Model): name = models.CharField() class Bar(models.Model): name = models.CharField() foo = models.ForeignKey(Foo) In the Foo detail page in the Django admin, I list all child Bars underneath the Foo details: @admin.register(Foo) class FooAdmin(admin.ModelAdmin): def bars(self): html = '' bs = self.bar_set.all() for b in bs: html += '<a href="%s">%s</a><br>' % (reverse('admin:app_bar_change', args=(b.id,)), b.name) html += '<a href="%s">Add a bar</button>' % (reverse('admin:app_bar_add')) return html bars.allow_tags = True fields = ('name', bars) readonly_fields = (bars,) As you can see, I also add a button to add a new Bar. This works, but what I want is to automatically prepopulate the Foo dropdown when adding a new Bar. I.e. I want to add a Bar to the currently open Foo. How can I do this in Django? -
Hosting django in webfaction
I am hosting the Django project in webfaction, I followed https://docs.webfaction.com/software/django/getting-started.html As mentioned in the above link I deleted the myproject default project folder created when adding the Django app in webfaction. problem is I entered my domain name in the browser and I got the URL not found error. I checked the error.log file I found something like WSGI script not found in myproject folder(but I already removed the myproject folder as mentioned in above link). httpd.conf(appche settings) WSGIDaemonProcess vyan_tender processes=2 threads=12 python-path=/home/sivagctece/webapps/vyan_tender:/home/sivagctece/webapps/vyan_tender/vyantender/vyan_tender:/home/sivagctece/webapps/vyan_tender/lib/python2.7 WSGIProcessGroup vyan_tender WSGIRestrictEmbedded On WSGILazyInitialization On WSGIScriptAlias / /home/sivagctece/webapps/vyan_tender/vyantender/vyan_tender/vyan_tender/wsgi.py wsgi.py file path I mentioned in httpd.conf file is from vyan_tender project WSGIScriptAlias / /home/sivagctece/webapps/vyan_tender/vyantender/vyan_tender/vyan_tender/wsgi.py but in the error.log file I got WSGI script not found in myproject folder(deleted) [Fri Jan 04 09:32:54.434127 2019] [wsgi:error] [pid 186346:tid 140172880013056] [client 127.0.0.1:32788] Target WSGI script not found or unable to stat: /home/sivagctece/webapps/vyan_tender/myproject django project wsgi.py file looks like import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vyan_tender.settings") application = get_wsgi_application() Can anyone help me how can I resolve this issue. I googled a lot but no use -
How to request on Financialcontent JSquote API
I'm new to using financialcontent, any insights as to how could I use the FC jsquote api? I'm using django I'm trying to use this endpoint but it gives me a 404 error http://feeds.financialcontent.com/treandlit/JSQuote?Ticker=CSCO+MSFT I dont know if financialcontent is still alive or I had my account_name wrong? Just to be sure, how do I get the account_name? -
Django show all items and related
I've been struggling with this for past 2 days and I really need some new input! First my configs: models.py class Category(models.Model): name = models.CharField(max_length=200) objects = models.Manager() class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name class Item(models.Model): name = models.CharField(blank=False, max_length=200) description = models.TextField(blank=False, null=True) date = models.DateTimeField(blank=False, null=True) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) order = models.IntegerField(blank=True, null=True) active = models.BooleanField(blank=True, default=False) objects = models.Manager() class Meta: verbose_name_plural = 'items' class ItemImage(models.Model): image = models.ImageField(blank=True, null=True) order = models.IntegerField(blank=True, null=True) main = models.BooleanField(blank=True, default=False) cover = models.BooleanField(blank=True, default=False) item = models.ForeignKey(Item, related_name='items', blank=True, null=True, on_delete=models.SET_NULL) objects = models.Manager() class Meta: verbose_name_plural = 'item images' views.py def index(request): all_items = Item.objects.filter(active=True) pics = [] for a in all_items: images = ItemImage.objects.filter(main=True) pics.append(images) propert = Item.objects.filter(active=True) context = { 'pictures': pics } return render(request, 'gallery/index.html', context) Template: <div id="image-popups" class="grid"> {% for pic in pictures %} <div class="item"> <img class="lazy" src="{{ pic.image.url }}" data-mfp-src="{{ pic.image.url }}" data-effect="mfp-zoom-in"> </div> {% endfor %} </div> My goal is to get all Items filtering for "active=True" and all of their related images with the value "main=True". I thought about just querying the ItemImage model with "main=True" filter, but I will need to retrieve … -
Django ORM queryset substring on a column
Consider below column in mysql table Employee. emp_number 4-PQR-A111 3-MNO-333 2-DEF-222 1-ABC-111 I need to write django orm query for below mysql query which splits on emp_number column by '-' and matches against last index. SELECT * from Employee WHERE substring_index(emp_number, '-', -1) = '111'; I cannot write endswith on a column like below: Employee.objects.filter(emp_number__endswith='111').values('emp_number') This will return below 2 records and I am expecting only one record. 4-PQR-A111 1-ABC-111 Any help would be appreciated. Thanks. -
How to generate a Query Set as a django view using elasticsearch-dsl for a model or set of model
I am using elasticsearch-dsl for searching (including full-text search) of fields in my model. I was able to make the index model (this might not be the right way to put/say this) for the models. I used the parent-child example given in elasticsearch-dsl github source code here. This is what my models look like: app_1/models.py class User(AbstractBaseUser): email=models.EmailField( verbose_name='email address', max_length=255, unique=True,) username_validator = UnicodeUsernameValidator() username = models.CharField(max_lenght=50) first_name=models.CharField(max_length=45) last_name=models.CharField(max_length=45) gender = models.CharField(max_length=7) class UserDetails(models.Model): user=models.OneToOneField('User',on_delete=models.CASCADE) date_of_birth=models.DateField() street_name=models.CharField(max_length=55) town=models.CharField(max_length=45) country = CountryField() app_2/model.py class Question(models.Model): user=models.ForeignKey('User',on_delete=models.CASCADE) question=models.TextField(max_length=400) answers=models.ManyToManyField('Answer',related_name='question_answers') upvote=models.IntegerField() ... My Elasticsearch-dsl model for was very similar to the parent-child example discussed above from the github source code. This is what it looks like; class Comment(InnerDoc): """ Class wrapper for nested comment objects. """ author = Object(User, required=True) created = Date(required=True) content = Text(required=True) class Post(Document): """ Base class for Question and Answer containing the common fields. """ author = Object(User, required=True) created = Date(required=True) body = Text(required=True) comments = Nested(Comment) question_answer = Join(relations={'question': 'answer'}) ... Pardon the wrong indentations. How can write a view that takes in a search input submitted by a user and generates a query set(elastic search query) for all the fields of my models in … -
Django turn pandas dataframe into queryset
I have a django app that renders querysets into tables. I need to perform a few modifications of the underlying querysets and it would be the most convenient to convert the querysets into dataframes, do some magic there and then convert the resulting dataframe back into a queryset so that I can feed it into the existing render. Converting a queryset into a dataframe seems straightforward, but I ccan't find a way to convert that back. tables.py class StuffTable(tables.Table): class Meta: model = Stuff template_name = 'django_tables2/semantic.html' views.py import django_pandas.io as dpd from django_tables2.tables import Table from .models import Stuff from .tables import StuffTable def index(request): context = dict() template = 'gui/index.html' stuff = Stuff.objects.all() # do pandas stuff with the data df = dpd.read_frame(stuff) df = ... modified_stuff = convert_df_back_to_qs(df) # how to do this? table = StuffTable(modified_stuff) context['table'] = table return render(request, template, context) How can I do this? -
Recursive Python Function Crippling Django Site Performance
I have a Django site with a Category model, each instance of which can hold zero to n subcategories. class Category(models.Model): ... parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='subcategories') I need to build a HTML nested list of all categories. The categories are store in a MySQL database. As a down and dirty way of getting this off the ground, I initially did this via a recursive function. This worked fine initially, but now there are over 800 categories and it's causing requests to slow down drastically. When running the development server, it's taking at least 60 seconds a go. Here's the function, simplified slightly: def get_category_map(categories, root=False): category_map = '' if categories: if root: category_map += '<ul id="root">' else: category_map += '<ul>' for category in categories: category_map += '<li>' subcategories = category.subcategories.all() if subcategories.count() == 0: category_map += '<a class="category-link" href="' + reverse('my_app:category_page', args=(category.pk, category.slug)) + '">' + category.title + '</a>' else: category_map += '<span class="category-drop-down">' + category.title + '</span>' # Recursive call here cripples performance. category_map += get_category_map(subcategories) category_map += '</li>' category_map += '</ul>' return category_map with the function initially called as follows: get_category_map(Category.objects.filter(parent=None), root=True) It generates the result I want, but at the expense of efficiency and … -
Django Rest Auth - Custom registration logic for social views
I'm building a REST API with Django Rest Framework and Django Rest Auth. My users have a consumer profile. This profile should get created as soon as a user signs up. Here is the serializer that I wrote for the registration: from profiles.models import UserConsumerProfile from rest_auth.registration.serializers import RegisterSerializer class CustomRegisterSerializer(RegisterSerializer): def custom_signup(self, request, user): profile = UserConsumerProfile.objects.create(user=user) profile.save() I connected this serializer in the settings: REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "accounts.api.serializers.CustomRegisterSerializer" } It works flawlessly when the users signs up using his email. But when he signs up using facebook, no consumer profile gets created. I thought the social view would also use the register serializer when creating users? How can I run custom logic after a social sign up? -
How to calculate column sum for models with many-to-one relationship?
I have a small issue and I kinda got stuck myself. Maybe you could help me with a suggestion in order to achieve the following scenario. Requirement: I am trying to work at a food journal application. What I want is to display on the home page all the jurnals along with the total of the record's calories added to a specific jurnal. My homepage posts look like this: Posts My models class Journal(models.Model): date_juornal = models.DateField(auto_now=False, auto_now_add=False) note = models.TextField(default="", blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Record(models.Model): journal = models.ForeignKey(Journal, on_delete=models.CASCADE) food = models.ForeignKey(FoodType, on_delete=models.CASCADE) qty = models.IntegerField(default=0) class FoodType(models.Model): food = models.CharField(max_length=100, default="") calories = models.IntegerField(default=0) My View* class HomeView(ListView): def get(self, request): if request.user.is_authenticated(): journals = Juornal.objects.filter( user=request.user).order_by('-date_juornal') rec1 = Record.objects.annotate(kcal=F('foodtype__calories')) rec2 = rec1.annotate(total=(F('kcal') * F('cantitate')) / 100) context = { 'journals': journals, 'records': records } return render(request, 'nutriapp/home.html', context) else: return redirect('login') -
How to send email when a form gets submitted [Django-rest-framework]
I have made an api for submitting a contact form in my application. Whenever the form gets submitted i want it to send that details to myself through email. Here is my code what i am using: models.py class ContactForm(models.Model): name = models.CharField(max_length=255) email = models.EmailField(max_length=254) phone = models.CharField(max_length=20) message = models.TextField() def __str__(self): return self.name class Meta: db_table = 'contact_form' views.py from rest_framework.generics import ( CreateAPIView, ) from .serializers import ( ContactCreateSerializer ) class ContactCreateApiView(CreateAPIView): queryset = ContactForm.objects.all() serializer_class = ContactCreateSerializer serializers.py class ContactCreateSerializer(ModelSerializer): class Meta: model = ContactForm fields = [ 'name', 'email', 'phone', 'message', ] Is there any who can help me? Any help would be appreciated. -
Django REST API Listview
Currently I'm trying to develop personal blog with Django/REST API, and I have trouble for that. There are a number of posts in blog and I want to control those posts with Hyperlink. I made it by using ModelViewSet, however, whole data in detailView is also shown in ListView. The thing is, I only want "url" and "title" of posts to be shown in ListView while DetailView contains full data. Here is my code and current results given by REST framework. Don't mind IndexView # serializers enter image description here # views enter image description here # Post List in REST API enter image description here # Post instance in REST API enter image description here -
Function running in background all the time (and startup itself) in Django app
I create simple Django app. Inside this app I have single checkbox. I save this checkbox state to database if it's checked in database I have True value if checkbox is uncecked I have False value. There is no problem with this part. Now I created function that prints for me every 10 second all the time this checkbox state value from database. Function I put into views.py file and it looks like: def get_value(): while True: value_change = TurnOnOff.objects.first() if value_change.turnOnOff: print("true") else: print("false") time.sleep(10) The point is that function should work all the time. For example If I in models.py code checkbox = models.BooleanField(default=False) after I run command python manage.py runserver it should give me output like: Performing system checks... System check identified no issues (0 silenced). January 04, 2019 - 09:19:47 Django version 2.1.3, using settings 'CMS.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. true true true true then if I visit website and change state is should print false this is obvious. But as you notice problem is how start this method. It should work all the time even if I don't visit the website yet. And this part confuse me. How to … -
Django Ecommerce is there a difference between filters and categories
Could anyone point my nose in the right direction. I am building my first ecommerce python django site. I already have filters in place: In plain English when you sort something you are putting it into a category so my question is how do I set about creating product categories. Is this just another word for filter. I want have a different header for each product categorie should I have a different app for each product? -
why am i hitting this error "[remote rejected] master -> master (pre-receive hook declined)"?
I'm trying to take my django app live on heroku but am hitting this error on "git push heroku master". git push heroku master Counting objects: 231, done. Delta compression using up to 4 threads. Compressing objects: 100% (221/221), done. Writing objects: 100% (231/231), 739.46 KiB | 0 bytes/s, done. Total 231 (delta 21), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to aajkakaam. remote: To https://git.heroku.com/aajkakaam.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/aajkakaam.git' -
How to implement modal pop-up in django template?
This is my view: class group1DeleteView(LoginRequiredMixin,DeleteView): model = Group1 def get_success_url(self,**kwargs): company_details = get_object_or_404(Company, pk=self.kwargs['pk']) selectdatefield_details = get_object_or_404(Selectdatefield, pk=self.kwargs['pk3']) return reverse('accounting_double_entry:grouplist', kwargs={'pk':company_details.pk, 'pk3':selectdatefield_details.pk}) def get_object(self): pk = self.kwargs['pk'] pk2 = self.kwargs['pk2'] get_object_or_404(Company, pk=pk) group = get_object_or_404(Group1, pk=pk2) return group def get_context_data(self, **kwargs): context = super(group1DeleteView, self).get_context_data(**kwargs) context['profile_details'] = Profile.objects.all() company_details = get_object_or_404(Company, pk=self.kwargs['pk']) context['company_details'] = company_details selectdatefield_details = get_object_or_404(Selectdatefield, pk=self.kwargs['pk3']) context['selectdatefield_details'] = selectdatefield_details return context In my group1_confirm_delete.html: <div class="modal fade" id="modal-default"> <div class="modal-dialog"> <div class="modal-content"> <form id="item_delete_form" method='post' class="form" role="form" action="{% url 'accounting_double_entry:groupdelete' pk=company_details.pk pk2=group1_details.pk pk3=selectdatefield_details.pk %}"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Delete {{group1.group_Name }}</h4> </div> <div class="modal-body"> <p>Are you sure you want to Delete {{group1.group_Name }}</p> </div> <div class="modal-footer"> {% csrf_token %} <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button> <input type="submit" class="btn btn-danger" value="Delete"> </div> </form> <script type="text/javascript"> jQuery('.modal-content'); var form_options = { target: '#modal-default', success: function() { } } $('#item_delete_form').ajaxForm(form_options); </script> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> And in my group1_details.html I have put a delete group button like this: <a class='btn btn-danger' data-toggle="modal" href="{% url 'accounting_double_entry:groupdelete' pk=company_details.pk pk2=group1_details.pk pk3=selectdatefield_details.pk %}" data-target="#modal-default">Delete Group</a> But whenever I click on my delete group button it does perform any action or no modal … -
How To Download a pdf File with python to local machine
I have created the web application using Django 1.11 , I need to download files over the FTP or HTTP to my local system from application (Using Browser) using python. Thanks for help