Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to activate Django view with a button on a page
I am trying to render an individual button on a page that activates a view method which sets a field in one of my models to false. How could I go about doing this? -
python virtualenv Creating Django Project in desired directory on windows
I have successfully created my Virtualenv in D:\ after installing python and virtualenv module I want to create django project outside "(virtualenv)>>\ scripts" folder. is it possible? if yes, how? because i am getting following error while doing so: CommandError: "D:\ \ " is not a valid project name. Please make sure the name is a valid identifier. it tired to put the name in double quote also. -
Django endpoint to accept xml Feed
I am looking to make an endpoint which would expect an Outbound message from Say SalesForce. The end point would consume the data (most likey update DB with the data). I was hoping to have some questions answered/clarified. 1) would django rest framework be the way to go? 2) since i dont have much control, I believe the auth-key/token etc would come in as a query string param. Does rest framework allow authentication this way? Thanks for you time and help. Regards Tanmay -
When is null=True ever not needed in Django?
It seems excluding null=True on any model field only causes problems - i.e especially when trying to delete fields. So what purpose does excluding null=True actually have? -
Is there anyway to create Django python model class from JSON SCHEMA
I want to create Django python model class dynamically from JSON SCHEMA. Is there any open source tool? -
Django Models: Aggregate over not directly related models
I have following models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) some_field = models.CharField(max_length=100) class UserRating(models.Model): subject_user = models.ForeignKey(User, related_name='rated_user', on_delete=models.CASCADE) rating_user = models.ForeignKey(User, related_name='rating_user', on_delete=models.CASCADE) rating = models.IntegerField() class Meta: unique_together = ("subject_user", "rating_user") I am trying to get a queryset of all UserProfiles with annotated average value of rating in UserRating model. I've tried doing the following: queryset = UserProfile.objects.all() for profile in queryset: user = profile.user ratingset = UserRating.objects.filter(subject_user = user).values_list('rating') if len(ratingset) == 0: profile.rating = 0 else: profile.rating = sum(ratingset) / float(len(ratingset)) However this throws the following error: TypeError: unsupported operand type(s) for +: 'int' and 'tuple' I thought about calculating the sum by iterating over ratingset, but my approach seems like an overkill. Is there any simpler way to achieve this? -
Error retrieving value textarea's value from form in Django
I am new to Django. I am trying to create a simple form that has text area in it. I can't seem to retrieve the value from textarea Here's my form: <form method="POST" class="ui form" action=""> {% csrf_token %} <div class="field"> <label>Title</label> <input type="text" name="title"/> <label> Content</label> <textarea rows="8" name="content" ></textarea> </div> <button type="submit" class="ui primary button">Create</button> </form> Here's my how I handle the form def createArticle(request): if(request.method == 'POST'): form = ArticleForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] body = form.cleaned_data['content'] username = request.session['email'] user = User.objects.get(username=username) I am getting this error KeyError at /create/article/ 'content' at this line body = form.cleaned_data['content'] Here's the content from my post request csrfmiddlewaretoken'CgCwDF1d03KGIxsmM2Z4hhStBRIxw9hlh1ACtYXpBWXLLvYJq2tfdO7lqds7EVxI' title'dsadasdasdsadsadasdsadasdsadsad' content'<p>sadasdsadasdasdasdsadasdasdsadsadsadasdsadsadsadsadsadsadsadasdasd</p>\r\n' I am guessing the <p> tag in content is what causing the error but I have no idea idea how to get rid of that. -
Does Django have an equivalent of Rails's “rails db:seed”?
One thing I like about Rails projects is that you can create test content and place them in seeds.rb and seed them into the database by running rake db:seed instead of having to feed them one by one directly. Is there something similar for Python/Django? -
Django Inlines in admin for multiple foreign keys
I have 3 models: Document, MetaData, MetaDataValue, and a "connector table" DocumentMetaDataValue. I want to add a document and all the associated metadata values on one admin page. # MetaData class MetaData(models.Model): metadata_id = models.AutoField(primary_key = True) name = models.CharField('metadata name', max_length=200, unique=True) description = models.TextField('description') # MetaData Value class MetaDataValue(models.Model): metadata_id = models.ForeignKey(MetaData, on_delete=models.CASCADE,) value = models.CharField('value', max_length=200, unique=True) # Document class Document(models.Model): document_id = models.AutoField(primary_key=True) metadata = models.ManyToManyField('MetaData', through='DocumentMetaDataValue', through_fields=('document', 'metadata')) metadatavalue = models.ManyToManyField('MetaDataValue', through='DocumentMetaDataValue', through_fields=('document', 'metadataValue')) class DocumentMetaDataValue(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE) metadata = models.ForeignKey(MetaData, on_delete=models.CASCADE) metadataValue = models.ForeignKey(MetaDataValue, on_delete=models.CASCADE) I want the inline to show the metadata name opposite a drop down with the associated metadata values. One should be able to pick more than one metadata value for a particular metadata name. For example, the Document may be a picture of three people. For the metadata Person, I want to select 3 names from the long drop down list of names for the metadata values associated with Person. Other metadata names may have only one possible selection from the drop down list. I get the basics of inline forms in simple instances, but this application, I don't see how to do it, or how to … -
Django celery beat task not working
celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TwitterApiProxy.settings') app = Celery('TwitterApiProxy') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, hello_test.s('hello'), name='add every 10') @app.task def hello_test(arg): print(arg) settings.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Los_Angeles' I want to print "hello" every 10 seconds. So on running celery -A TwitterApiProxy beat in my terminal, I see as below: LocalTime -> 2018-04-06 23:27:09 Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%WARNING . maxinterval -> 5.00 minutes (300s) it did not print anything related to the task that I scheduled. Where did I go wrong? -
How to link Different Users to Database?
So basically i'm new to django and i'm making a University project which is a E-learning site where users login to Study in different levels, every level has some Modules that u can study and then take a test after finishing each one, i want every user's mark to be saved (Module's test mark, a general level mark) so i can unlock the next level's button. ps: The modules Are editable (add,delete,add a questions to the module's test...) by the admin i'm a bit confused how to setup my Database Model and link it to the default Users model any help would be appreciated. -
Django Reuse form cleaning
I have a form cleaning method in my forms: def clean_field1(self): field1 = self.cleaned_data['field1'] field1 = ','.join(field1) return field1 If I have 8 fields out of my 20 fields that will perform this exact cleaning method. How can I reuse this cleaning method without need to repeat the same code 8 times. -
Pass local JSON to Vue.js in Django Wagtail CMS
I have a python program that outputs and updates a json file. I would like to pass that json file to Vue.js. What is the convention for doing this? (I am using CDNs) Django Fixture, ajax/getJson, vue-router fetch, something else? -
Overriding Crispy Forms template fails
I am trying to override default templates for tabs in Crispy Forms 1.7.0. As a first step, I tried to copy the relevant template (templates/bootstrap3/layout/tab-link.html) from crispy forms templates into my app template directory (myapp/templates/crispy_overrides/tab-link.html) but it stopped rendering the tabs properly when I tried to use the template in my dirs in layouts. Below is the relevant part from my form layout object and the template. Everything works fine if I comment out the template=... lines. Am I doing it wrong? TabHolder( Tab('D.DDD°', 'latitude', 'longitude', template='crispy_overrides/tab-link.html', ), Tab( 'DD°, DD.DD\'', 'lat_dmm_d', 'lat_dmm_m', 'lon_dmm_d', 'lon_dmm_m', template='crispy_overrides/tab-link.html', ), Tab( 'DD°, DD\', SS.SS\'\'', 'lat_dms_d', 'lat_dms_m', 'lat_dms_s', 'lon_dms_d', 'lon_dms_m', 'lon_dms_s', template='crispy_overrides/tab-link.html', ), Tab('UTM', 'utm_zone', 'utmx', 'utmy', template='crispy_overrides/tab-link.html' ), ), tab-link.html <li class="tab-pane{% if 'active' in link.css_class %} active{% endif %}"><a href="#{{ link.css_id }}" data-toggle="tab">{{ link.name|capfirst }}{% if tab.errors %}!{% endif %}</a></li> -
Preserve `Referer` header in Django redirect
Here's my problem: I have a Django view behind authentication, https://my.site.com/go-to-store. Upon clicking a link to that url/view, if the user's not logged in they get sent to a CAS service, https://cas.my.domain.com/ then, upon successful authentication, get sent back to https://my.site.com/go-to-store. When the user successfully authenticates, I want to redirect the user to https://some.company.com/store, with the Referer set to https://my.site.com/go-to-store. https://some.company.com/store requires this, otherwise the user sees "Store Unavailable". Some other SO questions claim that on all browsers, 301 and 302 redirects should preserve the Referer, but I'm not seeing it. If I make a link from my page to https://some.company.com/store, everything works perfectly. What do I need to do to have a redirect with the Referer preserved. My code's simple: @login_required def store_redirect(*args): return redirect(settings.STORE_URL) -
django url tag not being called
I have a template structure similar to this: #X_List.html <div class="row"> {% include './X_List_Table.html' %} </div> <div id="confirm" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="testmodal" aria-hidden="true"> <div class="modal-dialog modal-sm" role="document"> <div class="modal-content"></div> </div> </div> #X_List_Table.html <table> <thead> <tr> <th>Desc</th> <th>Activate</th> </tr> </thead> <tbody> {% for item in x_list %} <tr> <td>{{ item.id }}</td> <td><a data-toggle="modal" href="{% url 'x:x_quantity' item.id %}" data-target="#confirm">Click me</a></td> </tr> {% endfor %} </tbody> </table> My view is defined as: #views.py def x_quantity(request, id): return render(request, 'modal.html', {'quantity': X.objects.filter(pk=id).count()} and the modal.html: <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h3>Attention</h3> </div> <div class="modal-body"> <p>The number of elements is {{ quantity }}</p> </div> <div class="modal-footer"></div> The problem is: Supposing that I have 2 elements in the table, their urls would be: 'x/x_quantity/1' 'x/x_quantity/2' Consider that for these elements: One returns a QuerySet with atleast 1 element One returns an empty QuerySet When I click on the link, it should run the view, get the quantity based on the id of the element, return it as a context variable to the modal so it can be displayed. The problem is: When I click on a link, the view is being called with the id of the element, which can be … -
Update Query if data of 2 columns is equal to a particular string
For example assume my table contains user query data. I generate a hashed string by doing the following: queries = Query.objects.values('id', 'name') # creating a bytes string using the ID, NAME columns and a string "yes" (this string could be anything, I've considered yes as an example) data = (str(query['id']) + str(query['name']) + "yes").encode() link_hash = hashlib.pbkdf2_hmac('sha256', data, b"satisfaction", 100000) link_hash_string = binascii.hexlify(link_hash).decode() Assume I've sent this hashstring via email embedded in a link which is checked when the use visits that link. My current method of checking if the hash (got from the GET parameter in the link) matches with some data in the table is like this: queries = Query.objects.values('id', 'name') # I've set replyHash as a string here as an example, it is generated by the code written above, but the hash will be got from the GET parameter in the link replyHash = "269e1b3de97b10cd28126209860391938a829ef23b2f674f79c1436fd1ea38e4" #Currently iterating through all the queries and checking each of the query for query in queries: data = (str(query['id']) + str(query['name']) + "yes").encode() link_hash = hashlib.pbkdf2_hmac('sha256', data, b"satisfaction", 100000) link_hash_string = binascii.hexlify(link_hash).decode() if replyHash == link_hash_string: print("It exists, valid hash") query['name'] = "BooBoo" query.save() break The problem with this approach is that … -
django project polls stuck at using your own package step
I'm new to Python and Django so forgive me if this question seems silly. I'm following the django tutorial and I'm stuck at the step when you use your own package The app mysite works and there was no error. I've setup all the required files according to the tutorial. I've run python3 setup.py sdist (inside django-polls folder) There's the file django-polls-0.1.tar.gz in django-polls/dist/ $ cd .. $ pip3 install --user django-polls/dist/django-polls-0.1.tar.gz Processing ./django-polls/dist/django-polls-0.1.tar.gz Requirement already satisfied (use --upgrade to upgrade): django-polls==0.1 from file:///home/viet/webdev/django-polls/dist/django-polls-0.1.tar.gz in /home/viet/.local/lib/python3.6/site-packages Building wheels for collected packages: django-polls Running setup.py bdist_wheel for django-polls ... done Stored in directory: /home/viet/.cache/pip/wheels/ff/ec/8b/85c031efa2ba719d6bd909d20f61ca6b106c79345a1e875f08 Successfully built django-polls Then the tutorial says: With luck, your Django project should now work correctly again. Run the server again to confirm this. How? There's no manage.py file in /django-polls or in /home/viet/.cache/pip/wheels/ff/ec/8b/85c031efa2ba719d6bd909d20f61ca6b106c79345a1e875f08 So I tried this: $ pip3 uninstall django-polls Uninstalling django-polls-0.1: ... Proceed (y/n)? y Successfully uninstalled django-polls-0.1 $ pip3 install --user django-polls/dist/django-polls-0.1.tar.gz Processing ./django-polls/dist/django-polls-0.1.tar.gz Building wheels for collected packages: django-polls Running setup.py bdist_wheel for django-polls ... done Stored in directory: /home/viet/.cache/pip/wheels/ff/ec/8b/85c031efa2ba719d6bd909d20f61ca6b106c79345a1e875f08 Successfully built django-polls Installing collected packages: django-polls Successfully installed django-polls-0.1 I'm lost at this point. -
In Django, how to get a query of all objects with a one-to-one relationship with another model?
I'm looking to refactor some code which has a special kind of user, LucyGuide, with a one-to-one relationship to Django's User model: from django.db import models from django.contrib.auth.models import User class LucyGuide(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @classmethod def lucy_guide_user_ids(cls): return [guide.user_id for guide in cls.objects.all()] In certain use cases, we need all Users which have a corresponding LucyGuide, which is obtained like so: User.objects.filter(id__in=LucyGuide.lucy_guide_user_ids()) This seems rather verbose to me and it seems like there should be a more concise way. Any ideas how to refactor this? -
Adding filter search box for each table columns in django templates
I am using django to display my database query data in a table with multiple columns. Would like to add filtering boxes for each columns in templates so people can filter the data from different fields. My current table looks like similar to this: After adding filtering box for each column, it should look like this: How would I achieve this in django templates? I currently have code in templates like this: -
to_representation in django restframework does not work with custom serializers.SerializerMethodField
I was bit confused about having custom structure with custom field, attached my reference implementation. If you see do_representation you output was not as expected, anyone know why is it so? class ImageSerializer(serializers.ModelSerializer): image_thumb = serializers.ImageField() class Meta: model = Image fields = ('thumb',) class ProductSerializer(serializers.ModelSerializer): def product_url(self,obj): request = self.context['request'] return request.build_absolute_uri(reverse('product', args=(obj.slug,))) url = serializers.SerializerMethodField('product_url') images = ImageSerializer(many=True) class Meta: model = Product fields = ('url', 'images', 'id') def to_representation(self,product): raise Exception(product.url) # Not working raise Exception(product.images) # Not working raise Exception(product.id) # Working -
View values of a file uploaded on django-rest-framework
I am trying to upload multiple files to from an angular frontend, I want to be able to view or access the values of each file before performing any extra manipulations on them. How do I view the contents of each file? @list_route(methods=['PUT']) def uploads(self, request): print(request.data['files']) for file_item in request.data.getlist('files'): print(file_item) return Response(0) this is the result I get when i print the contents. [object File],[object File] this is the array of files that was sent from the client. File(8614) lastModified : 1522947934000 name: "passport.jpeg" size: 8614 type: "image/jpeg" File(8610) lastModified : 1522947934800 name: "passport2.jpeg" size: 8610 type: "image/jpeg" -
"lookup_field" with "drf-nested-routers" : inconsistent variable naming convention
I am using lookup_field = "id" in all my nested viewsets, such that "child" viewsets get variables that match documentation of my api. However, primary_key (pk) for all viewsets do not match documentation... Is this the right way to do this, or should I rename lookup_field to match value in documentation? If doing so, how to I avoid "redundent" field variable naming in the children nested viewsets ? EG: I have 4 endpoint, documented as follows: GET api.com/company/ GET api.com/company/{company_id}/ GET api.com/company/{company_id}/project/ GET api.com/company/{company_id}/project/{project_id}/ Here's a "mockup" of urls.py: from django.conf.urls import url from rest_framework_nested import routers from company.views import CompanyViewSet from project.views import ProjectViewSet router = routers.SimpleRouter() router.register(r'company', CompanyViewSet, 'company') router.register(r'project', ProjectViewSet, 'project') projectrouter = routers.NestedSimpleRouter(router, r'company', lookup='company') projectrouter.register(r'project', ProjectViewSet, 'project') urlpatterns = [] urlpatterns += router.urls urlpatterns += projectrouter.urls Part of my requirements.txt includes: drf-nested-routers Here's are "mockups" of my 2 viewsets: class CompanyViewSet(): lookup_field = "id" def list(self, request): ... return Response(companies) def retrieve(self, request, id=None): ... return Response(company) & class ProjectViewSet(): lookup_field = "id" def list(self, company_id=None, request): ... return Response(projects) def retrieve(self, request, company_id=None, id=None): ... return Response(project) In the above 2 "viewsets", we have the following "field parameters" : id company_id id These "field … -
Django https ssl configuration error related to mod_wsgi
I deployed my Django project to AWS Linux AMI thought Elastic Beanstalk. Currently, it works well with http, but on https, it shows an error like the below. [:error] [pid 3090] [client 24.43.39.130:64135] Embedded mode of mod_wsgi disabled by runtime configuration: /opt/python/current/app/connectshops/wsgi.py -
Django & Vue.js: GET / HTTP/1.1" 200 220 Not Found
I am new to Django and Vue.js, and trying to combine those tow frameworks, So I followed a video tutoriel and copy every thing he does, except for the names of project, app, and variables, and had to copy only the webpack.config.js. So in the video, he made homepage.games as his main page, bach I choosed to make webapp/game as my main page. and when ever I tipe http://127.0.0.1:8000/ in the browser, the data I extracted from my database are not showen and the PowerShell shows this error [06/Apr/2018 15:25:26] "GET / HTTP/1.1" 200 220 Not Found: /homepage/games I don't rmember copying or writing homepage in any of my project files. and I really don't know whitch code I should post in here so you could answer me. So please if anyone have any idea or wants me to post any code,please let me know in a comment. PS: here is the link of the video I followed https://www.youtube.com/watch?v=rxLZg4PqC8M