Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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/") -
Checking duplicate email when editing user profile in Django
I am trying to check the duplicate email while I am logged in as a user and editing my own profile. But when the email entered is the email of current logged in user and I do not want to update my current email then also I am getting a duplicate email error message. accounts/forms.py class UserProfileForm(forms.ModelForm): class Meta: model = models.Profile fields = ("organisation", "phone_number") first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)")) organisation = forms.CharField(max_length=30) email = forms.EmailField() def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.initial['first_name'] = self.instance.user.first_name self.initial['last_name'] = self.instance.user.last_name self.initial['email'] = self.instance.user.email helper = FormHelper() helper.layout = Layout( Div( Field("first_name", wrapper_class="col-sm-6"), Field("last_name", wrapper_class="col-sm-6"), css_class = "row" ), Div( Field("organisation", wrapper_class="col-sm-6"), Field("email", wrapper_class="col-sm-6"), css_class = "row" ), Div( Field("phone_number", wrapper_class="col-sm-6"), css_class = "row" ), ) def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): raise forms.ValidationError(u'Please use a different email address.') return email def save(self, commit=True, *args, **kwargs): self.instance.user.first_name = self.cleaned_data['first_name'] self.instance.user.last_name = self.cleaned_data['last_name'] self.instance.user.email = self.cleaned_data['email'] self.instance.user.save() return super(UserProfileForm, self).save(commit, *args, **kwargs) How can I check if the entered email is a new email and if it is new email then check duplicate function else ignore email field … -
Deploying Django projects with conda
Environment management in Python projects is critical and is commonly done with venv or virtualenv. However, I am interested in deploying a Django project with conda. The basic setup looks like the one here. Django is served using gunicorn which is controlled with supervisor. That conda does not use folders as environments basically means that there is no isolated directory where the Django project could live (hope I got this right). This post has a nice description of how to deploy a Python project with conda in general. For using this with supervisor I was thinking if activating a specific conda environment with installed dependencies in supervisor would suffice to create the needed results. I assume this supervisor config might look something like this: [program:djangoapp] command = .activate django-env; python gunicorn djangoapp.wsgi:application -b 127.0.0.1:8000 directory = /path/to/djangoapp ... The supervisor docs say that supervisor will search the supervisord’s environment $PATH for the executable, if it's provided without an absolute path. Does this mean that the absolute path of the conda environment needs to be used here? Long story short: Is anyone using conda for this and is it even usable the way I like to do it and if yes: … -
Getting error while including javascript files using Django and Python
I am getting some error while including javascript files in templates using Django. I am explaining my error below. Error: TemplateSyntaxError at / Invalid block tag on line 6: 'static'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.2 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 6: 'static'. Did you forget to register or load this tag? Exception Location: C:\Python34\lib\site-packages\django\template\base.py in invalid_block_tag, line 571 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 I am explaining my code below. settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] PROJECT_DIR = os.path.dirname(__file__) """ Internationalization """ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True """ Static files (CSS, JavaScript, Images) """ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') urls.py: """Neuclear plant URL Configuration""" from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('plant.urls')), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) base.html: <html lang="en"> <head> <meta charset="utf-8"> { % load static %} <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> </head> In the above template file i am getting the error. Here I need to include the js file in … -
Key (email)=() already exists error: python-social-auth
My app uses both email registration and Facebook or Google+ registration using python-social-auth (0.2.11). When some new users register using Facebook, they are taken to an error page. After that, I see the following error: Internal Server Error: /complete/facebook/ Traceback (most recent call last): File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/newrelic/hooks/framework_django.py", line 527, in wrapper return wrapped(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 51, in wrapper return func(request, backend, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/apps/django_app/views.py", line 28, in complete redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/actions.py", line 43, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 41, in complete return self.auth_complete(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/utils.py", line 229, in wrapper return func(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/facebook.py", line 87, in auth_complete return self.do_auth(access_token, response, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/facebook.py", line 119, in do_auth return self.strategy.authenticate(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/strategies/django_strategy.py", line 96, in authenticate return authenticate(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 74, in authenticate user = backend.authenticate(**credentials) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 82, in authenticate return self.pipeline(pipeline, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 85, in pipeline out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py", line 112, in run_pipeline result … -
How can I display a view based on a database value
I want to use one view (URL) for 2 conditions. In my application, "owners" create daily plans for routes they manage, and update the plans/results throughout the day. class DailyRoute(models.Model): owner = models.ForeignKey(Owner) route = models.ForeignKey(Route) driver = models.ForeignKey(Driver) stops = models.PositiveSmallIntegerField(default=0, ... on_duty_hours = models.TimeField(default=datetime.time... date = models.Datefield(... finalized = models.Boolean(... Essentially, there are 3 database conditions, 2 of which I'm trying to use for a view: No database row for the date/route. This means that the owner hasn't created a plan for the day. (e.g. if DailyRoute.objects.filter(stage = 0).count() == 0:...) A database row for the date/route with finalized = False. This means that a plan has been created for the day for the date/route pair and can be edited. (e.g. DailyRoute.objects.filter(stage = 0).count() >0 ) A database row for the date/route with finalized = True. This means that a plan/updates for the day are complete and no further edits are allowed. (e.g. if DailyRoute.objects.filter(stage = 1).count() > 0:...) As a daily activity, I want the user to go to a URL (e.g. /account/daily) and be presented with one of these views: a) If no owner routes (point 1 above), provide an "Add" button to add a row …