Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get query fields from ReadOnlyModelViewSet
Tell me, please, how you can access the fields that were sent in the GET request to the ViewSet of the following form: class MyViewSet(ReadOnlyModelViewSet): http_method_names = ['get'] queryset = User.objects.all() serializer_class = MySerializer permission_classes = (AllowAny,) def list(self, request, *args, **kwargs): request.data # < attempt to access this attribute will return an empty dictionary return super().list(request, args, kwargs) -
Python Heroku app deployment "App not compatible with buildpack" error
I am trying to deploy my app in heroku, but is failing with "App not compatible with buildpack" error. I have added requirement.txt and procfile in my project, yet it is failing. remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://codon- buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to xyz. Heroku build log is not providing much info either: -----> App not compatible with buildpack: https://codon- buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection- failure ! Push failed Can someone tell me if I am missing anything? I am trying git push method. -
Django - saving a form strips values so only the first word is saved
I am currently working on a Django project and I have run into a problem when I save a form the values get stripped down so only the first word is saved. I am quite sure that the problem is somewhere in the request.POST.get but haven't figured out how to fix it. -
Why django do not display comments?
my model : class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts') updated_by = models.ForeignKey(User, null=True, related_name='+') class Comments(models.Model): creator = models.ForeignKey(User, related_name='comment') body = models.TextField(max_length=4000) post = models.ForeignKey(Post, related_name='comment', null=True) my view: def p(request, pk): topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) return render(request, 'post.html', {'post': post, 'topic': topic}) def comments(request, pk): comment = get_object_or_404(Comments, pk=pk) return render(request, 'post.html', {'comment': comment}) my urls: url(r'^boards/(\d+)/(?P<pk>\d+)$', views.p, name='p'), url(r'^boards/(\d+)/(\d+)/$', views.comments, name='comments'), as i can understand, the problem in using primary key, in case of posts all work good, but when i try to render different models in one page it looks like that django go not like it. I tryed a lot of combinations in url pattern, but nothing that solved my problem. On post.html page all info about posts redered as well, but comments is not work -
"Toggle" manytomanyfield in Django
I have two models which simplified look like this: class Tag(models.Model): name = models.CharField(max_length=8) class Person(models.Model): tags = models.ManyToManyField(Tag, related_name='tags') I want to easily be able to toggle these tags on and off for a person, what I've been doing so far is iterating some tags that are supposed to be toggled, like: for tag in selected_tags: if person.tags.filter(pk=tag.id).exists(): person.tags.remove(tag) else: person.tags.add(tag) This does however cause lots of db queries and I'd like to be able to do it in just one query. Is there a "correct" way to do this in Django? -
Ckeditor error django
Traceback (most recent call last): File "./manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/__init__.py", line 20, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/utils/log.py", line 87, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 568, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python2.7/logging/config.py", line 711, in configure_handler klass = self.resolve(cname) File "/usr/lib/python2.7/logging/config.py", line 394, in resolve self.importer(used) File "/home/sabo/projects/iDocs/web/django/api/utils/utils.py", line 23, in <module> from main.models import EnterpriseEntry, Permission File "/home/sabo/projects/iDocs/web/django/main/models.py", line 20, in <module> from moderators.models import HackerLogin, CompanyPayment File "/home/sabo/projects/iDocs/web/django/moderators/models.py", line 4, in <module> from ckeditor.fields import RichTextField File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/fields.py", line 6, in <module> from .widgets import CKEditorWidget File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/widgets.py", line 54, in <module> class CKEditorWidget(forms.Textarea): File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/widgets.py", line 59, in CKEditorWidget class Media: File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/ckeditor/widgets.py", line 68, in Media static('ckeditor/ckeditor/'), File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/js_asset/js.py", line 14, in static if apps.is_installed('django.contrib.staticfiles'): File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/apps/registry.py", line 231, in is_installed self.check_apps_ready() File "/home/sabo/projects/envs/idocs/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I cant resolve this problem. I already installed django-ckeditor, added into installed_apps in settings.py like 'ckeditor', and now when I trying to run project I saw this error, It's happened when … -
How to set a default handler in django fobi
Did anyone managed to set a default handler in django-fobi? What was the approach? I'd like to set the db_store handler as a default for all of the forms. I've tried to set defaults in models but with no success. -
When I put "Logout" button,Page not found error happens
When I put "Logout" button,Page not found error happens. I wrote in views.py like @login_required def logout_view(request): logout(request) return render(request, 'registration/accounts/top.html') in index.html <div class="container"> <ul class="top-menu"> <form name="logout" method="post" action="{% url 'accounts:logout_view' %}"> <button type="submit" class="btn btn-primary btn-lg" style="color:white;background-color: #F62459;border-style: none;">Logout</button> <input name="next" type="hidden"/> </form> </ul> </div> But I put Logout button,Page not found (404) error happens.Traceback is Page not found (404) Request Method: POST Request URL: http://localhost:8000/static/accounts/logout_view My ideal system is when I put logout button, it sends top.html. Directory is What is wrong in my code?How should I fix this? -
form error using cleaned data
I am trying to modify an app that I have found on the net in order to create surveys but I am getting an error that I do not manage to solve form.py: def save(self, commit=True): import pdb; pdb.set_trace() """ Save the response object """ # Recover an existing response from the database if any # There is only one response by logged user. response = self._get_preexisting_response() if response is None: response = super(ResponseForm, self).save(commit=False) response.survey = self.survey response.interview_uuid = self.uuid if self.user.is_authenticated(): response.user = self.user response.save() # response "raw" data as dict (for signal) data = { 'survey_id': response.survey.id, 'interview_uuid': response.interview_uuid, 'responses': [] } # create an answer object for each question and associate it with this # response. for field_name, field_value in self.cleaned_data.items(): if field_name.startswith("question_"): # warning: this way of extracting the id is very fragile and # entirely dependent on the way the question_id is encoded in # the field name in the __init__ method of this form class. q_id = int(field_name.split("_")[1]) question = Question.objects.get(pk=q_id) answer = self._get_preexisting_answer(question) if answer is None: answer = Answer(question=question) if question.type == Question.SELECT_IMAGE: value, img_src = field_value.split(":", 1) # TODO answer.body = field_value data['responses'].append((answer.question.id, answer.body)) LOGGER.debug( "Creating answer for question %d … -
django import export raises error on foreignkey to `User`
Software: Python3.6.2 Django1.11 django-import-export==0.5.1 OSX10.12.6 INSTALLED_APPS: THIRD_PARTY_APPS = [ ..., 'reversion', # django-reversion 'import_export', # django-import-export ] Requirements: 1. Model has reversion 1. Model can be able to do import 1. Each imported role has uploader as created_user, and updated_user (However, just for now I let it read from the Excel file and here it is the problem) Attempts: 1. Since 2 of the requirements will hit hard with strict meta class. Then I apply reichert solution https://github.com/etianen/django-reversion/issues/323 1. Problem: Line number: 1 - get() keywords must be strings None, 696 02, Lane, Ronald Regan, Ratíškovice, n/a, Dolichitus patagonum, admin, admin Traceback (most recent call last): File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/resources.py", line 434, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/resources.py", line 258, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/resources.py", line 252, in get_instance return instance_loader.get_instance(row) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/import_export/instance_loaders.py", line 33, in get_instance return self.get_queryset().get(**params) TypeError: get() keywords must be strings Models: https://gist.github.com/elcolie/98e641d57c5de3394f816a5d9b80ef13 admin.py https://gist.github.com/elcolie/081017adc7b5e2fd7a3a38b0573597c6 References: Dealing with import of foreignKeys in django-import-export django-import-export to export User model Django Import/Export to multiple Models (foreignkey) -
if condition in urls.py - dajngo
I want to check if user not loged(don't have a session) he go to login.html file and if he loged(have a session) he go to profile.html , but i want to check it at urls.py My projects Tree : manage.py url ----setting.py mr_url -----templates ---------url ------------profile.html ------------login -----------------logon.html -----views.py -----models.py -----urls.py My urls.py : from django.conf.urls import url from . import views from django.views.generic import TemplateView urlpatterns =[ url(r'^$', views.profile, name='profile'), ] How i can check set session for user or not in urls.py ???? Note : i can do it in views.py but i don't want! -
django template print either "good morning or afternoon" depending on time of day
Morning, I'm trying to create a template for an email and I'm unsure on how to get the greeting to flip between "Morning, afternoon and evening" depending on time of day that it is selected to be sent. Any ideas current template code {% if hour < 12 %} morning {% elif hour > 12 %} afternoon {% endif %} -
Django models through many to many relations
I am building an open-hard/software home automation environment based on Django, python and Arduino devices. I just wanted a small app to start diving into python but the thing has gone away once I started because this is so amazingly powerful... My main doubt here is on Django... I have a Django model that describes the general things of each of the type of devices available. class DeviceTypeModel(models.Model): Code = models.CharField(help_text='Type of the device', max_length=10,primary_key=True) ... Each of this device-types will have some communication datagrams in which they will send information to the master when queried. class DatagramModel(models.Model): DeviceType = models.ForeignKey(DeviceTypeModel,on_delete=models.CASCADE) AnItems = models.ManyToManyField(AnalogItemModel, through='ItemOrdering',blank=True) DgItems = models.ManyToManyField(DigitalItemModel,through='ItemOrdering',blank=True) In each datagram, several analog and/or digital values can be defined and ordered through an auxiliary model 'ItemOrdering': class ItemOrdering(models.Model): datagram = models.ForeignKey(DatagramModel, on_delete=models.CASCADE) AnItem = models.ForeignKey(AnalogItemModel, on_delete=models.CASCADE,blank=True,null=True) DgItem = models.ForeignKey(DigitalItemModel, on_delete=models.CASCADE,blank=True,null=True) order = models.PositiveSmallIntegerField(help_text='Position in the dataframe 1-based') Each of the items in the datagram are based on a model (shown analog, digital are fairly the same) : class AnalogItemModel(models.Model): HumanTag = models.CharField(max_length=20,unique=True) Units = models.CharField(max_length=10) This model is supposed to keep the basic information about an item. The particular info (the one particular to a particular device) such as the … -
Run string command in pymongo
I have following string command query = "{}{'_id': False}" Now I want to run above command in following code client = MongoClient('mongodb://'+host+':'+port+'/') db_col = database.split(',') database, collection = db_col[0].strip(), db_col[1].strip() collection = client[database][collection] collection = collection.find(query).limit(10) Is there any solution for that -
Function that assign image from related model to parent model ImageField
Is it possible to write a function that assigns an image from another/related model to an models.ImageField? Sorry for the bad explanation, here is an example: models.py class Product(models.Model): cover_image = models.ImageField(default=get_cover_image) class Image(models.Model): product = models.ForeignKey(Product, related_name='images') is_featured = models.BooleanFIeld(default=1) So my intention is to write/define a function above the Product model that assigns the image from Image that is set to is_featured = True. I've been playing around and no matter what I've tried cover_image remains blank or None. Currently the function looks like this: def get_cover_image(instance): cover_image = instance.architecture.is_featured == 1 return cover_image class Product(models.Model): cover_image = models.ImageField(default=get_cover_image) Am I completely of base here? Is what I'm trying to achieve possible? -
Model Relationship Failing, Can't Get Data in Template
I have model Profile and another model called 'Nation', and this model will take Profile and User as ForeignKeys. It's like this, class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type=models.CharField(max_length=10, choices=M_CHOICES) class Nation(models.Model): user= models.ForeignKey(User, related_name='natuser') profile = models.ForeignKey(Profile, related_name='nat_hr') ref_number = models.CharField(max_length=20, default=pm_tag) The logic here is to check for the type of user and show fields 'values' related to the user model. For this, we believe the User belongs to the Nation model, so to get his ref number, In Views, I did @login_required def profile_detail(request, username): user= get_object_or_404(User, username=username) try: the_detail= user.profile except ObjectDoesNotExist: return None in Template, after checking that the user type belongs to the Nation model, I wrote the below code to get the user ref_number but it's failing. {{the_detail.nat_hr.ref_number}} {{the_detail.user.profile.nat_hr.ref_number}} What am I missing when it comes to using related_name to get data that belongs to a model via template? -
django pagination is not working properly
i am trying to do pagination function based-view , it does work but...I m going to give you an example: If i have a total of 100 results and i want to paginate by 50, it will give 2 pages, but both pages have same 100 results. Cause if i want to paginate by 50 it will give me 2 pages. I used the the function based view from this link. i don't want classed view cause if i implement that the rest of the code would not work. I m going to post a part of my code for this. views.py def search_form_table(request, pk): table_name = Crawledtables.objects.get(id=pk) t = create_model(table_name.name) if request.method == 'GET': form = AllTablesForm(request.GET) if form.is_valid(): cd = form.cleaned_data title = cd['title'] url = cd['url'] query = t.objects.filter(title__icontains=title, url__icontains=url) page = request.GET.get('page', 1) paginator = Paginator(query, 50) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'search_table.html', {'tbl_name': table_name, 'users': users, 'form': form, 'details': query}) -
Django encode / decode and Store in psql
I'm trying to store the store the Gujarati string from Android to PostgreSQL using Django API. When I'm calling the same API by web, its working fine because I can see the Gujarati text in the database. but when I'm trying to store the same string from Android, it's coming in question mark format (EX: ???? ??) So I encoded the string in Android, as per this solution: Here Now I'm getting the correct output by using print only, but when I'm storing it into the database, it's storing in the encoded format, see the below example: Gujarati Text: ❛ઝીંદગ After AndroidEncoded:%E2%9D%9B%E0%AA%9D%E0%AB%80%E0%AA%82%E0%AA%A6%E0%AA%97 By using the urllib: >>>urllib.unquote_plus(a.encode('utf-8')).decode('utf-8') Output: u'\u275b\u0a9d\u0ac0\u0a82\u0aa6\u0a97' Now when using print on terminal: >>>print(urllib.unquote_plus(a.encode('utf-8')).decode('utf-8')) Output: ❛ઝીંદગ and when storing the same value in a database like: text = urllib.unquote_plus(a.encode('utf-8')).decode('utf-8') text getting store as %E2%9D%9B%E0%AA%9D%E0%AB%80%E0%AA%82%E0%AA%A6%E0%AA%97 But from browsers, it's storing ❛ઝીંદગ I want to know why it's showing the proper output when I'm using the print and when storing it's not working as expected. Thanks -
Error with Django Celery ,how to fix?
well i have same view same setting for celery in another app, when i launch another one, he is work, absolutely work, but when i launch this, nothing, i installed everthyng like in another one, but nothing, pls help me! if you have some ideas how to fix please let me know) This is full traceback Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\utils\__init__.py", line 423, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 449, in _ensured return fun(*args, **kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\messaging.py", line 177, in _publish channel = self.channel File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\messaging.py", line 194, in _get_channel channel = self._channel = channel() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\utils\__init__.py", line 425, in __call__ value = self.__value__ = self.__contract__() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\messaging.py", line 209, in <lambda> channel = ChannelPromise(lambda: connection.default_channel) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 771, in default_channel self.connection File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 756, in connection self._connection = self._establish_connection() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 711, in _establish_connection conn = self.transport.establish_connection() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\transport\pyamqp.py", line 116, in establish_connection conn = self.Connection(**opts) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\amqp\connection.py", line 165, in __init__ self.transport = self.Transport(host, connect_timeout, ssl) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\amqp\connection.py", line 186, in Transport return create_transport(host, connect_timeout, ssl) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\amqp\transport.py", line 299, in … -
Django - How can I load images created by site using image uploaded by users?
For any image uploaded by the user, I am generating a Thumbnail. The user uploaded image and thumbnail are stored like this. media_cdn (folder) -user_name_1 (folder) -user_name_2 (folder) --post_1_title_slug (folder) ---300x180 (folder) ----300x180_user_uploaded_image_1.png ---user_uploaded_image_1.png --post_2_title_slug (folder) -user_name_3 (folder) Since I am using ImageField in models, I can easily use {{ appname.image.url }} in templates, but this will load the image uploaded. I want to load the thumbnail. I search on stackoverflow and most people are saying to use {{ MEDIA_URL }}, like here I am leaning towards {{ MEDIA_URL }} because, in the future, the website will be generating more images based on the same user uploaded images. I am using this as of now, <img src='{{ MEDIA_URL }}/{{user.username}}/{{ upload.slug }}/300x180/300x180_{{ upload.get_filename }}'> this is giving out this in the page, (from Inspect element) /user_name/file_slug/300x180/300x180_image_name.png {{ MEDIA_URL }} is not giving its correct url. FYI, get_filename is from models.py where I wrote this to get the file name def get_filename(self): return(os.path.basename(self.image.name)) how can I make this work? I am Using Django 1.11.5, and Pillow 4.2.1 -
How to add custom button in django-admin
I have a another submit button in change_form and if this button clickled i want to validate and customize my requested data. admin.py def save_model(self, request, obj, form, change): data = request.GET.copy() if '_saveandclose' in request.POST: data['CloseDetail'] = "Save and Closed Clicked!" #and i need some validation obj.User = request.user obj.save() -
Running a python script after a button is clicked
So I have an html page like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Find the words</title> <h1>Find the Words</h1> </head> <body> <p>Find the largest and the smallest word</p> <textarea rows="25" cols="100"></textarea> <br> <button type="button">Find now!</button> <br><br> <label>Largest Word</label> <input type='largest word'/> <label>Smallest Word</label> <input type='smallest word'/> </body> </html> I want to run a python script which will find the largest and smallest word from a text and post the result back. The script is like this: #!/usr/bin/env python3 def find_small_large_words(given_string): new_list = given_string.split(" ") sorted_list = sorted(new_list, key=len) return 'Smallest: {0} & Largest: {1}'.format(sorted_list[0], sorted_list[-1]) words = "Ten years on from the financial crisis, it’s hard not to have a sense of déjà vu.Financial scandal and wrangles over financial rule-making still dominate " \ "the headlines.The cyberhacking at Equifax compromisedpersonal records for half of the adult population of the United States.At SoFi, a one-time fintech darling" print(find_small_large_words(words)) Ultimately, I want to run the python script on click of the "Find words" button and post them back in the two boxes. How can I do that here? I have read some suggestions about using django framework. Is there any other simple way? If so, how? -
Writing html files with python
I have read about some python frameworks for web development. I understand that django is a really high level and good platform. I want to put static data (results from several runs of a program) on a webpage. Should i use django or there is an easiest alternative because my needs are simple. Prehaps i will need to deal with dynamic data in the future- for that i do need django? Thanks, Or. -
When changing a Custom User model in Django Admin a plain text field is used instead of the special password field?
In the custom user with admin docs, it mentions that if your custom user model extends AbstractBaseUser you need to add it to the admin manually. I have done that in admin.py with: from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ('email', 'first_name', 'last_name', ) However when I go and edit a user I get: Instead of the usual password field: -
Extending admin index.html template
I have downloaded the following templates from admin.contrib: base.html, base_site.html and index.html. I would like to extend index.html, but no matter what I do it does not seem to work. In settings.py, I have declared the name of my app to override the order in which the admin files are render. So, I can edit the actual files and content does change when I run the server. But, I create a file in the directory templates/admin/foo.html. The code with foo.html is: {% extends "admin/index.html" %} {% block something %} <p>Hello</p> {% endblock %} And I have change the file templates/admin/index.html to have {% block something %}{% end block %} When I run the server, the content of foo.html does not display. Do I need to add foo.html to my urls.py and create a function within views.py to render the content? Any help would be greatly appreciated.