Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django specific user content/data
first post on stackoverflow. Ive been reading/watching everything I can, but im still very new to this. Any help would be greatly appreciated Im trying to display specific content/data based on a logged in user. I want to display only their info. This is what ive tried but i cant get it to work. In views.py class DemoView(TemplateView): template_name = 'demographics/demographics.html' def get(self, request): demos = Demographics.objects.filter(user=request.user) context = { 'demos': demos, } return render(request, self.template_name, context) models.py class Demographics(models.Model): first_name = models.CharField(max_length=50, null=True) middle_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) user = models.ForeignKey(User, null=True) I feel like im close. what im a missing?? -
get foreign key from model
Hello I want to get fk from model model.py class Produit(models.Model): ref=models.CharField(max_length=100, default='',primary_key=True) marq=models.CharField(max_length=100, default='') nomp=models.CharField(max_length=100, default='') qte = models.IntegerField(default=0) codecateg=models.ForeignKey(categorie, on_delete=models.CASCADE) class categorie(models.Model): codecateg=models.CharField(max_length=100, default='' , primary_key=True) nomcat=models.CharField(max_length=30, default='' ) views.py def edit_prod(request , id = None): ins = get_object_or_404(Produit,ref=id) datedit = {'ins': ins} return render(request, 'produit/modal_prode.html',datedit ) when i want to get ins.codecateg i get categorie object -
Google Material Design vs Material Design Lite
As a background I am working on a Django project where I want to use Google's Material Design. But I'm running into a lot of trouble to install the environment with npm. I would like to know what are the pros and cons of using each one. I was reading that Google's Material design has dependencies and MDL doesn't. Am I right?! I am wondering what is the best choice would be to use material design lite to this project. It is important to me the maintenance of the site as easy as possible. Thanks for your suggestions -
Use Angular to Display Dynamic Content Generated by Django View
Does anyone have a coding example to demonstrate this? I followed instructions found at https://blog.khophi.co/beginner-troubles-with-django-and-angular/ but they only work if the content is static. Any help would be appreciated. Thanks. -
GraphQLView does not work properly unless request.body is previously accessed
I have the following setup: urlpatterns = [ # ... url(r'^graphiql-token', csrf_exempt(GraphQLTokenView.as_view())), # ... ] class GraphQLTokenView(APIView): permission_classes = (IsAuthenticated, IsSuperuser) authentication_classes = (TokenAuthentication,) @staticmethod def post(request, *args, **kwargs): request.body # Breaks when removed return GraphQLView.as_view(schema=schema)(request, *args, **kwargs) It is mandatory that this view is protected by TokenAuthentication and the permission classes specified above. There's an unusual error where if the seemingly no effect statement request.body, first line of GraphQLTokenView.post is removed, the GraphQL Endpoint becomes disfunctional. For instance, if the same query is sent to both with and without the statement, the one without request.body would reply with this: { "errors": [ { "message": "POST body sent invalid JSON." } ] } Even despite the fact that the same JSON has been sent. The one with request.body would handle the query just fine and return what is expected. What could be causing this unusual error, and how do I fix it? -
Capitalize "i" to "İ" in python
I want to capitalize first letter of "ismail" when i write "ismail".title() it shows: Ismail. I want to seem like "İsmail". Is there any function for this? -
Custom view and url for DRF
I'd like to know how to add a custom view and url using DRF. I currently have a UserDetail(APIView) class that can display a user object using a url like /users/123/ but I'd like to also have the ability to view a users history with a url like /users/123/history/ which would likely call on a new method within the UserDetail class. Is there a way to do this? I've tried looking through DRFs documentation and it looks like they can achieve this through ViewSets and custom Routers, but I get errors when using ViewSets likes needing to define a queryset. -
Retrieve password using rest framework JWT
Is it possible to use Django JWT rest framework to create a password recovery link? An example would be to recover password by email and create an access token for it. Or do I need to use the features of Django admin to do this? Thank you very much. -
Using /// inside a URL in a NGINX/Django project
I have a Django project running with NGINX and I would like to route the following URL to a view: example.com///what.three.words (with the 3 slashes) and it should be a different view than example.com/what.three.words The following works with the Django test server: url(r'^//(?P<w3w_address>[\w.]+)/?$', W3WView.as_view(), name='w3w') but not in production with NGINX and Gunicorn. The question is why, is NGINX somehow messing with it? NGINX config: upstream project_prod { server unix:/webapps/project/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name domain.com www.domain.com amp.domain.com; keepalive_timeout 5; client_max_body_size 4G; access_log /webapps/project/logs/nginx-access.log; error_log /webapps/project/logs/nginx-error.log; location /.well-known/ { alias /webapps/project/.well-known/; } location /static/ { alias /webapps/project/static/; } location /media/ { alias /webapps/project/media/; } location / { add_header 'Access-Control-Allow-Origin' *; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://project_prod; } listen 443 ssl; # SSL stuff here... if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot # PAGE SPEED pagespeed RewriteLevel CoreFilters; pagespeed EnableFilters extend_cache; pagespeed EnableFilters responsive_images; location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" { add_header "" ""; } location ~ "^/ngx_pagespeed_static/" { } location ~ "^/ngx_pagespeed_beacon" { } } -
Can I get span element to ignore columns?
I am creating a web app in which the user drags boxes containing words/phrases into an area. When the user mouses over the boxes, a tool-tip is displayed with the definition of the word. When the user drags boxes into the areas, I would like them to fall into two columns. However when using columns, the tooltip breaks when going over the edge of the area. Is there any way to fix this? How tooltips are at the moment How I would like them to be CSS: #div1 { float: left; width: 328px; height: 400px; margin-left: 4px; padding: 10px; border: 1px solid black; border-radius: 6px; background-color: white; -webkit-columns: 2; -moz-columns: 2; columns: 2; -moz-column-fill: auto; column-fill: auto; } .box{ height: 54px; width: 160px; text-align: center; background-color: white; color: purple; border: 1px solid black; border-radius: 4px; margin-bottom: 2px; position: relative; text-align: center; } .tooltiptext { visibility: hidden; width: 160px; background-color: purple; color: #fff; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 100%; left: 50%; margin-left: -80px; } .box:hover .tooltiptext { visibility: visible; } HTML: <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> {% for c in cards1 %} <div id="drag{{c.id}}-{{c.carddata.position}}" class="box" draggable="true" ondragstart="drag(event)" > <span class="tooltiptext">{{c.carddata.description}}</span> <div id="text{{c.id}}-{{c.carddata.position}}" class="text"><br>{{c.carddata.name}}</div> </div> {% … -
Django-taggit with Django-treebeard or suitable Taxonomy app
Environment: Python 2.7.10 Django 1.11.3 Problem I need a Taxonomy system instead of just tags. For example: Art > Digital Illustration Programming > Websites > Code Fights Programming > Websites > Hackerrank Programming > Websites > Code Fights > Arcade > Level One Programming > Code Challenges Looking around I found this post in StackOverflow which led me to this blog post. Which led me to the following code: Models class Taxonomy (TagBase, MP_Node): node_order_by = ['name'] class TaggedPost (ItemBase): content_object = models.ForeignKey('Post') tag = models.ForeignKey('Taxonomy', related_name='tags') class Post(ItemBase): tags = TaggableManager(through=TaggedPost, blank=True) Admin admin.site.register(Taxonomy, TreeAdmin) Problem is when I go to admin to add the Taxonomies I get the following fields: Name Slug Path Depth Numchild The last two are not meant to be input by hand, so says the documentation of tree beard. Do not change the values of path, depth or numchild directly: use one of the included methods instead. Consider these values read-only. I went ahead and tried to input them myself, for the curiosity/stupidity, and the tree broke. So I had to use this hack to fix it: f = Taxonomy.objects.all() from django.db.models import QuerySet QuerySet.delete(f) Kudos to user “jrief” for the hack. Another problem … -
What do I add to my requirements.txt in Django directory in order to push it to Heroku?
I am new to programming/web development and I want to push a Django directory to heroku. But every time I enter "git push heroku master" into my command line I get the same error: "Could not find a version that satisfies the requirement bonjour-py==0.3 (from -r /tmp/build_602f#############86ff270e/requirements.txt (line 3)) (from versions: )" I activated the virtual environment, but to no avail. Now I assume that the problem might be that my requirements.txt file does not contain anything (as I thought there would not be a reason for that, anyway). Still, I wonder what "bonjour-py==0.3" is and how that could be fixed. Thank you very much for your help! -
Django: how can i get a model that store a list(like in python or anyway) of a sizes of a shoes
excuse my English I'm beginner in django and i want to achieve this in my model and form: the scenario is like purchasing shoes on amazon: 1. the shoes has list of size a user can select form 2. the user select and add it to the cart 3. user place an order which is saved in a model with the respective size included now imagine a shoe seller when selling can enter a list of sizes like this in python size = [1, 2, 3, 4] which is also saved on a shoe-model how can implement this in django and how to save a list of size entered but a seller to a model and how can i display this list so the user can select only one of the value of this list? please help -
Prevent duplicate voting when there's more than one possible selection?
I'm trying to set up a voting system in using Django that limits a registered user to voting only once on a single vote (despite there being multiple options available agree/strongly agree/disagree). So far, I've been able to set up a system where they can't make the same exact vote (so they can't vote "agree" twice), but they can change their vote and it still goes through (so they can vote "agree" and then vote again as "disagree"). I want them to be limited to one vote per topic, and I can't quite figure out how to tweak my code to accomplish this. Here is my view: def vote(request, prediction_id): prediction = get_object_or_404(Prediction, pk=prediction_id) selected_choice = prediction.choice_set.get(pk=request.POST['choice']) if Voter.objects.filter(prediction=prediction, choice=selected_choice, user_id=request.user.id).exists(): return render(request, 'predictions/detail.html', { 'prediction': prediction, 'error_message': "Sorry, but you have already voted." }) else: selected_choice.votes += 1 selected_choice.save() Voter.objects.create(prediction=prediction, choice=selected_choice, user_id=request.user.id) return HttpResponseRedirect(reverse('predictions:results', args=(prediction.id,))) and here are my models: class Prediction(models.Model): prediction_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') # ... def __str__(self): return self.prediction_text class Choice(models.Model): prediction = models.ForeignKey(Prediction, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Voter(models.Model): user = models.ForeignKey(User) choice = models.ForeignKey(Choice) prediction = models.ForeignKey(Prediction) -
DJANGO Queryset with datetime: Need to get all future dated entries
How would I get all the entries in the model Appointment with a future date using datetime? The attribute in question is date. Appointment.object.filter(date = ???? ) -
populate a modal table with Ajax
Okay so I've been working on this issue for over a week now and still have not been able to find a working solution and I more than a little stumped. The problem I'm having is I'm trying to use ajax to load data into a table in a modal on a click event. I've tried several different implementations but I am very new to Ajax and javascript. Here is what I have. I am passing two dictionaries from my controller to my template as context: views.py def queries_search(request): ... context = { "title":"Search", 'data': list(od.iteritems())[:10], 'methods': od_methods.iteritems(), } return render(request, 'results.html', context) from there I am taking the first dict and passing the results to a table using the iterative template tags {% if data %} <section class="results-section"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div id='loader' class="center-block"> <p>Searching<img src='{% static "img/ellipsis.svg" %}'></p> <img class="center-block" src='{% static "img/gears.svg" %}'> </div> <div id='results_donwload'> <a href="{% static 'mycsvfile.csv' %}" > Downlaod Search Results </a> <img style="width: 12%;" src='{% static "img/download-icon.png" %}'> </div> <table class="table table-bordered table-striped table-hover table-responsive" id="results-table" > <thead> <tr> <th style="width: 4%">#</th> <th>Study Reference</th> <th>Study Methods</th> <th>Study Data</th> <th>Study Tools</th> <tr> </thead> <tbody> {% if data %} {% for … -
How to have a template link leave the django app
I'm attempting to have a hyperlink leave the Django application I am building. What I found through another Stackoverflow page was: <a href="google.com">Google</a> doesn't work, but <a href="https://google.com">Google</a> does break the link from the site. My issue with the above is the certain link I am attempting to get to doesn't work when linked with https:// in front of it. Is there a different way to set a hyperlink to link outside of my application without requiring the https://? -
How to access and use exceptions the way status codes could be used? (Python, Django)
I would like to raise an exception in a function, and then check somewhere else (in the Django view and my unit tests) if it was raised. The following code uses status codes, and it works. But I can't figure out how to do the same thing with exceptions - which, everyone seems to agree, are the right way to do this kind of thing. It is important to me to use custom error messages. Not to print them, but to detect and use them in the code (mainly to forward them to the end user with Django messages). I have no idea how I would check in add_foo_view if an exception was raised in utils.add_foo. In the unit test I have tried things like assertWarnsRegex(Warning, 'blah went wrong'), but that did not bother to check if the message is actually the same. views.py: from django.contrib import messages from .utils import add_foo def add_foo_view(request): if request.method == 'POST': status = add_foo(request.POST['bar']) if not status == 'Bar was added.': messages.error(request, status) return render(request, 'index.html') else: return render(request, 'add_foo.html') utils.py: def add_foo(bar): if not spamifyable(bar): return 'Bar can not be spamified.' try: eggs = Egg.objects.get(baz=bar) except: return 'Bar has no eggs.' do_things(bar) … -
Django tests loading fixtures auth.group
When I run django tests I get the error: IntegrityError: Problem installing fixture ... ContentType matching query does not exist.: (auth.group:pk=2) field_value was '[u'add_corsmodel', u'corsheaders', u'corsmodel']' I get the fixtures by doing python manage.py dumpdata --natural-foreign --exclude=contenttypes --exclude=auth.Permission How can I solve this? should I exclude some other table? -
Python Django UnicodeDecodeError
Am new to Django trying to learn, just installed python 2.7.13 and Django 1.11.4. Have created a project called myproject and tried to start with below command it throws below error. can some one help?? python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f13229f10c8> Traceback (most recent call last): File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run self.check_migrations() File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/opt/IBM/Python2.6/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 6: ordinal not in range(128) Din't configured anything else. Just tried to start development server but it fails. Thank, Vinoth -
Python/Django Error: String expected
While processing some forms.py data, I'm constantly getting String Expected error for some reason. Also the function load_privatekey() is loaded from external ssl.py module. forms.py def clean_cert_passphrase(self): cdata = self.cleaned_data passphrase = cdata.get('cert_passphrase') privatekey = cdata.get('cert_privatekey') if not privatekey: return passphrase try: privatekey = load_privatekey( privatekey, passphrase ) except Exception as e: raise forms.ValidationError(_("Error: {}\nType: {}".format(e, type(passphrase)))) ssl.py: def load_privatekey(buf, passphrase=None): return crypto.load_privatekey( crypto.FILETYPE_PEM, buf, passphrase=lambda x: str(passphrase) if passphrase else '' ) The exception output: Error: String expected Type: <class 'str'> Does anyone seem to understand the problem and might have a solution? I'd appreciate. -
Raspberry pi3 and django
I am working on a project in which I am supposed to take the sensor values using raspberry pi 3 store it in cloud or in raspberry pi 3 and I should be able to access that data and display it on a django based server( we are asked to use pythonanywhere.com which is a django app ) . The data should be taken from sensors after some interval of time. -
Store data from class instance to request.session
I'm trying to share some data between Django views. I have a view where I instanciated the class "Mwfrs Buildings". The class have several attributes, properties and cached_property. For example: from django.utils.functional import cached_property class MwfrsBuildings: def __init__(self, form_cleaned_data): for key, value in form_cleaned_data.items(): setattr(self, key, value) @property def foo(self): pass @cached_property def bar(self): pass I need to get the data from the attributes and the properties. I have the following view: def buildings(request): if request.POST and request.is_ajax(): s_form = BuildingForm(request.POST) if s_form.is_valid(): method = MwfrsBuildings(s_form.cleaned_data) html = render_to_string('wind/results/buildings/buildings_results.html', {'method': method}) request.session['building_method'] = method.__dict__ return JsonResponse({"result": html}) else: return JsonResponse({'building_errors': s_form.errors}, status=400) Because I can't store the instantiated class, I store the data using the __dict__ method. This works fine for the class attributes and the cached_property, but doesn't work for properties. How can I store the class properties in request.session? It is posible to pass the instanciated class to request.session ? -
Connect the prod's database on the dev's database
In a Django project, we are having the same application in dev and in prod. The application runs in prod since three months now. I imported the database from this application with scp user@remote_host:remote_file local_file, and I would like to connected to my own application in dev. The backup file is called backup-credit24h-prod-2017-08-29.sql. How could I do it? -
Redirect extends url instead of changing it
Let's say that on mysite.com/my_view/ I can log into my system. In development everything was fine. In production I end with mysite.com/my_view/mysite.com/adminin my url bar in browser. :( My "log in" code looks like: def my_view(request): domain="mysite.com" return redirect("http://"+domain+"/admin/")