Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Packages not installing on django
I'm trying to install any packages and I am unable to. I use "pip install package". But, after successfully installing. When I try to run the application, I get a the following error. This seems to be a common problem discuss in a lot of groups, but I have not found any solutions. I've been working on this all day. Please help. New to django. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'settings' https://groups.google.com/forum/#!topic/django-users/0tAtr4NBJ_4 http://www.techlighting.info/django-channels-tutorial-1-creating-a-chat-application/ I think that my project is not contecting to the packages correctly. Here is my file relationship. This is where the project is: Documents > Projects > hosproject > catalog, manage.py, hosproject2, venv This is where the packages are Documents > trydjango > lib >python3.7>site.packages>packages -
How to social login from App to consume own backend
I am making a project with this features: A backend with data related to user in flask rest API. A mobile app made in Ionic that should consumes data in that API. The purpose is to login from the app using Social Authentication or email password Authentication to use the backend data according to the user. I was reading about OAuth2 and I understand that sometimes is convenient to use different flows. I was searching a lot in Google but I can find any seemed to my need. What's the appropriate flow for my stack? -
Django Form Imagefield validation for certain width and height
I am trying to validate the image dimension in form level submitted by user before storing it to database. the dimension should be 1080x1920. I dont want to store the width and height size in database. I tried with the Imagefield width and height attribute. But it is not working. class Adv(models.Model): image = models.ImageField(upload_to=r'photos/%Y/%m/', width_field = ?, height_field = ?, help_text='Image size: Width=1080 pixel. Height=1920 pixel', -
best way to use google recaptcha V3 in django
first I should say that I've read this, and It is not what I need. I want to have forms that I made with html/css not django forms. and my method is based on this, that is acctually in php. I wrote a code and it works fine, but I believe there should be a better way to do it. the summery of code is that I submit my form , post the data and google recaptcha token to my function , and then do some process on it , then to redirect to the relative page base on results of proccesses,I return the url and status to the jquery again , and redirect to that page using jqury. here is my codes: login.html: <script src="https://www.google.com/recaptcha/api.js?render=here is recaptcha public key"></script> <!-- login form and etc --> <script> $('#loginForm').submit(function() { // stop what loginform is going to do event.preventDefault(); var username = $('#username').val(); var password = $("#password").val(); grecaptcha.ready(function () { grecaptcha.execute("here is recaptcha public key", {action: "{% url 'basic_app:login_page' %}"}).then(function (token_id) {$('#loginForm').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token_id + '">'); $.post("{% url 'basic_app:login' %}", // url {username: username,password: password, token_id: token_id,csrfmiddlewaretoken: '{{ csrf_token }}'}, function( result ){ console.log(result); if(result.status == 0) { … -
Migrate command not transforming not creating table in database. Django
I created a model and migrated the changes to database and inserted some values in it. But at one point I accidentally deleted that table from database using pgAdmin 4 not from django I was trying to empty the table but accidentally deleted it. The model is still in django and I decided to migrate changes again so that that I could my table back in database. After running migrate it says that no migrations to apply but when I look in the database the table is not there. I tried creating different models in the same app and tried migrating them they migrated but the model with the name same as model that I deleted is not migrating to the database. I have deleted all the migrations and it still not taking it. I think it is still somewhere in the django system from where it should be deleted or something. Any help how can I get that same name model migrated to the database. -
django load image map
I am trying to build a django web application whose one feature is to allow users to click several buttons with a name of the region and returns the image map of corresponding region. This page is already loaded on top of base.html. I am having trouble figuring out how this can be done. Should I do it through static, or template or through ajax and view? -
Django html forms: obtain data using get request and pass on to the another view
I am using two views in django: one for showing a form and get data and then use the data as an argument to the second view. But I could not quite figure this out as how to do it. So far my views look like class View1(View): def get(self, request): return render(request, 'example/view1.html') class View2(View): def get(self, request, arg1): token = processData(arg1) context = { 'word': token, } return render(request, 'example/view2.html', context) Now in the template view1.html I have the following code <form action="{% url 'example:view2 expected_argument %}" method="get"> {% csrf_token %} <input id="key" type="text" name="key"> <input type="submit" value="Submit"> </form> what would be the 'expected_argument' in the template so that I can get the input form value from the view1.html template, and then pass it on to the View2. -
Dynamic fields for django model using `__init_subclass__`
How do I copy over a models fields dynamically to subclasses (with variations...) using __init_subclass__ I've tried this: @classmethod def __init_subclass__(cls, *args, **kwargs): ... for field, field_name in vars(base_model).items(): if isinstance(DeferredAttribute): field.contribute_to_class(cls, new_name, changed_field) ... But, DeferredAttribute doesn't have the contribute_to_class method. Moreover, I can't use the EVA pattern etc. It specifically has to be this method if possible. Using vars because since this is __init_subclass__ then the model._meta.get_fields() doesn't actually exist yet... -
Django routing POST deletion request to viewProduct?
When I try to delete a product on my django app, I get a 404 error stating: Page not found (404) Request Method: POST Request URL: http://localhost:8000/product/1/delete/ Raised by: products.views.viewProduct No Product matches the given query. I'm confused as to why Django is routing the deletion request to viewProduct, since my urls.py clearly states that it should route to deleteProduct. urls.py: from django.urls import path from . import views from django.views.generic import TemplateView urlpatterns = [ path('new/', views.NewProduct, name='NewProduct'), path('product/<int:pk>/<str:slug>/', views.viewProduct, name='viewProduct'), path('product/<int:pk>/delete/', views.deleteProduct, name='deleteProduct'), ] Views: from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from .models import Product from django.utils import timezone from slugify import slugify def viewProduct(request, pk, slug): product = get_object_or_404(Product, pk = pk, slug = slug) return render(request, 'viewProduct.html', {'product' : product}) def deleteProduct(request, pk): if request.method == 'GET': product = Product.objects.filter(pk = pk) return redirect('viewProduct', pk = pk, slug = product.slug) if request.method == 'POST': product = get_object_or_404(Product, pk = pk) if product.productAuthor == request.user: product.delete() return redirect('viewAll') Deletion form: {% if request.user == product.productAuthor %} <form action="/product/{{ product.pk }}/delete/" method="post"> {% csrf_token %} <input type="submit" name="pk" class="btn btn-link text-danger" value="delete product"> </form> {% endif %} If it helps you, I just recently … -
Use stripe token to charge credit card with stripe element
I'm really stuck in this subject and maybe someone can help me out. I can always generate a token with stripe successfully but somehow my charge function doesn't wan't to work. I'm using the stripe element from their official documentation. How can I find out where I have to search for the mistake because I don't get any error from the code. In the stripe dashboard I can see the generated tokens, that's why I think until this point there is everything right but I guess my mistake is in the view function. More precise I think the view function doesn't get the generated token from the javascript. Many thanks for your help in advance! stripe_form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> {% load static %} <link rel="stylesheet" href="{% static 'css/stripe.css' %}"> <title>Document</title> </head> <body> <div id="collapseStripe" class="wrapper"> <script src="https://js.stripe.com/v3/"></script> <form action="" method="post" id="payment-form"> {% csrf_token %} <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div id="card-element" class="StripeElement StripeElement--empty"> <div class="__PrivateStripeElement" style="margin: 0px !important; padding: 0px !important; border: none !important; display: block !important; background: transparent !important; position: relative !important; opacity: 1 !important;"><iframe frameborder="0" allowtransparency="true" scrolling="no" name="__privateStripeFrame4" allowpaymentrequest="true" src="https://js.stripe.com/v3/elements-inner-card-bfbabea0af3ed365b5fe9ce78692fd3c.html#style[base][color]=%2332325d&amp;style[base][fontFamily]=%22Helvetica+Neue%22%2C+Helvetica%2C+sans-serif&amp;style[base][fontSmoothing]=antialiased&amp;style[base][fontSize]=16px&amp;style[base][::placeholder][color]=%23aab7c4&amp;style[invalid][color]=%23fa755a&amp;style[invalid][iconColor]=%23fa755a&amp;componentName=card&amp;wait=false&amp;rtl=false&amp;keyMode=test&amp;origin=https%3A%2F%2Fstripe.com&amp;referrer=https%3A%2F%2Fstripe.com%2Fdocs%2Fstripe-js%2Felements%2Fquickstart&amp;controllerId=__privateStripeController1" title="Secure payment input … -
Django Tutorial - Writing your first Django app, part 2, I'm trying to migrate but it shows "No migrations to apply."
I just started learning Django through the tutorial from Djangoproject. I'm trying to migrate but it shows "No migrations to apply" in terminal where it supposed to show "Applying polls.0001_initial... OK." And don't know where I made mistakes, could you please help? Thank you. [Terminal] Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: No migrations to apply. [mysite/polls/models.py] from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) [migrations/0001_initial.py] from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Choice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choice_text', models.CharField(max_length=200)), ('votes', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='Question', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question_text', models.CharField(max_length=200)), ('pub_date', models.DateTimeField(verbose_name='date published')), ], ), migrations.AddField( model_name='choice', name='question', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'), ), ] https://docs.djangoproject.com/en/2.1/intro/tutorial02/ I'm using python 3.7.2 with anaconda. -
Django get ForeignKey field values from serializer in template
I'm trying to create a page form where the form is actually a DRF serializer (although I don't think this actually makes much difference). I need to be able to access field values from the far end of the ForeignKey field before the object has been created. *** Models.py *** class Tag(models.Model): name = models.CharField(max_length=20) colour = models.CharField(max_length=20) class Entry(models.Model): title = models.CharField(max_length=100) date = models.DateField() tags = models.ForeignKey(Tag) *** Serializer.py *** class EntrySerializer(serializers.ModelSerializer): class Meta: model = models.Entry fields = '__all__' *** views.py *** from rest_framework.views import APIView class Submit(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'submit.html' def get(self, request, format=None): context = {} context['serializer'] = serializers.EntrySerializer(context={'request': request}) return render(request, self.template_name, context) def post(self, request, format=None): ... The following works fine for accessing 2 of the object fields: *** submit.html *** {% for tag in serializer.tag.iter_options %} {{ tag.value }}-{{ tag.display_text }} {% endfor %} However, I would like to do also be able to access the colour field: *** submit.html *** {% for tag in serializer.tag.iter_options %} {{ tag.value }}-{{ tag.colour }} {% endfor %} TIA! -
creating django model that has a list of lists within
I am trying to do a property for all users in my django app that contains a list of lists. Basically they can create lists and then input data to those lists! After all this I will show the selected list in a graph. I already have a model for the inner lists. class List(models.Model): name = models.CharField(max_length=200) data = models.IntegerField() My problem is I cant find a way to make multiple of these lists into an list for each user. -
Create file structure on the server based on parameters sent from the web application using django
I'm developing a web application with the django framework, but I'm new to the framework and I do not know how to organize things. Specifically, I need to receive some parameters from the user and save them in the database, but the important thing is that based on these parameters I need to create a directory structure on the server and some scripts. I do not know since part of the application I must communicate with the OS to create this structure of files and scripts. I would think that from the views.py file but I'm not sure. I appreciate your help in advance!! By the way, I'm working with Centos7 -
Django: using a settings folder; ImportError: cannot import name 'QUEUE_NAME'
I am following this install for this project: https://github.com/IntelligentTrading/data Dependency installation has been difficult, although I've gotten up to migration: (I am in a virtualenv) python manage.py migrate INFO:settings:Deployment environment detected: LOCAL INFO:settings:Importing vendor_services_settings INFO:settings:LOCAL environment detected. Importing local_settings.py Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/cerulean/.virtualenvs/ITF/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/cerulean/.virtualenvs/ITF/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/cerulean/.virtualenvs/ITF/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/cerulean/.virtualenvs/ITF/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/cerulean/.virtualenvs/ITF/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/cerulean/.virtualenvs/ITF/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/cerulean/Code/data-sources/apps/indicator/models/__init__.py", line 5, in <module> from apps.indicator.models.events_elementary import EventsElementary File "/home/cerulean/Code/data-sources/apps/indicator/models/events_elementary.py", line 17, in <module> from apps.signal.models.signal import Signal File "/home/cerulean/Code/data-sources/apps/signal/models/__init__.py", line 1, in <module> from apps.signal.models.signal import Signal File "/home/cerulean/Code/data-sources/apps/signal/models/signal.py", line 15, in <module> from settings import QUEUE_NAME, AWS_OPTIONS, BETA_QUEUE_NAME, TEST_QUEUE_NAME, PERIODS_LIST ImportError: cannot import name 'QUEUE_NAME' It's almost as if the code from the /settings/vendor_services_settings.py doesn't want … -
How to Increment Next Record in Django / Templates
In index.html - I am able to read the first item of my table / model in Django just fine with my code below. However, after the user clicks the next button - I want it to retrieve the next item of my table / model. (how / where do I build this counter?) here is views.py def index(request): flash_dict = {'flashcards': Card.objects.get(pk=1)} return render(request, 'flash/index.html', context=flash_dict) here is index.html <div class = "jumbotron"> {% if flashcards %} <p class = 'question'>{{ flashcards }}</p> <p class = 'answer'>{{ flashcards.flash_answer }}</p> <button type="button" class="btn btn-primary" onclick = "flip()">Flip</button> <button type="button" class="btn btn-primary">Next</button> {% else %} <p>NO ACCESS RECORDS FOUND!</p> {% endif %} </div> -
Django filter timestamp__range
I want to apply a range filter on a timestamp field, based on query parameters start and end. My view looks like this: from rest_framework.generics import ListAPIView from rest_framework.generics import RetrieveAPIView from .models import HourlyTick from .serializer import HourlyTickSerializer # Create your views here. class HourlyTickList(ListAPIView): def get(self, request): start = request.GET.get('start', None) end = request.GET.get('end', None) return HourlyTick.objects.filter(timestamp__range(start, end)) class HourlyTickDetail(RetrieveAPIView): queryset = HourlyTick.objects.all() serializer_class = HourlyTickSerializer Model: from django.db import models # Create your models here. class HourlyTick(models.Model): id = models.IntegerField(primary_key=True) timestamp = models.DateTimeField(blank=True, null=True) symbol = models.TextField(blank=True, null=True) open = models.IntegerField(blank=True, null=True) high = models.IntegerField(blank=True, null=True) low = models.IntegerField(blank=True, null=True) close = models.IntegerField(blank=True, null=True) trades = models.IntegerField(blank=True, null=True) volume = models.IntegerField(blank=True, null=True) vwap = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'xbtusd_hourly' urls.py: from django.urls import path, re_path from . import views urlpatterns = [ re_path('hourlyticks', views.HourlyTickList.as_view()) ] The error I receive is: name 'timestamp__range' is not defined What is the problem here? -
Python django packages not installing
When I run an "pip install" it works and the package installs. Here is an example for the import-export package: Installing collected packages: xlrd, pyyaml, xlwt, unicodecsv, jdcal, et-xmlfile, openpyxl, defusedxml, odfpy, tablib, diff-match-patch, django-import-export Successfully installed defusedxml-0.5.0 diff-match-patch-20181111 django-import-export-1.2.0 et-xmlfile-1.0.1 jdcal-1.4 odfpy-1.4.0 openpyxl-2.6.0 pyyaml-3.13 tablib-0.12.1 unicodecsv-0.14.1 xlrd-1.2.0 xlwt-1.3.0 but when I try to run the app with the package, I get this error: File "~/projects/hosproject/venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'import-export' I have added 'import-export' to my apps. This error occurs when I run "python3 manage.py collectstatic". -
Setting up a Subprocess In my Views.py -- Django
I have a variable symbol that I am trying to pass into a python script called earnings.py in a script folder inside the app. The output will be a matplotlib graph. Is subprocess the best way to do this? If so, how would I do this? The documentation for subprocesses is confusing. -
Issue with Heoku Postgres "could not access file “$libdir/postgis-2.1"
I have a project that works with GeoDjango, Postgis and its deploy it in Heroku. Some info of what I'm using: Python 2.7.15 Django 1.11.20 Heroku-18 (Stack) Postgres 9.4.20 Postgis 2.1.8 In the last months the sistem trow me an error when i want to load de geografic info "ERROR: could not access file "$libdir/postgis-2.1": No such file or directory" when I execute a geocode query. I have looked for the web and stackoverflow for the solutions and a I found some that was really near of my problem but I tried their solutions and doesn't work for me. I tried the "ALTER EXTENSION postgis UPDATE" solution but trow me this error: ERROR: cannot create temporary table within security-restricted operation I tried the "backup your DB, Drop the local database and restaurations" but when I run the comand pg:backups:capture trow me this: An error occurred and the backup did not finish. Then I run the pg:backups:info And trow me this: 2019-03-02 23:08:31 +0000 pg_dump: [archiver (db)] query failed: ERROR: could not access file "$libdir/postgis-2.1": No such file or directory ... (some database code) 2019-03-02 23:08:31 +0000 waiting for pg_dump to complete 2019-03-02 23:08:31 +0000 pg_dump finished with errors Then I … -
Django Prefetch related_name not visible when using multiple lookup
When i use the django Prefetch object (https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-objects) on multiple fields like this: model_a.objects.prefetch_related(Prefetch(model_b__model_c), to_attr='data') where model_a has a m2m relation to model_b and model_c has a foreign key of model_b. I don't seem to get the 'data' field on the elements of the returned QuerySet. Am I looking in the wrong place maybe? -
Proper OAuth Storage for User model
I have an application that gathers OAuth tokens for Twitch and Twitter. My current user model is below: User Model: class CustomUser(models.Model): first_name = models.CharField() last_name = models.CharField() twitch_name = models.CharField() twitter_name = models.CharField() join_date = models.DateTimeField(auto_now=True) I'm wondering if it is more efficient to store the OAuth tokens on the CustomUser as a field, or create individual models like below. OAuth Models Example: class TwitterToken(models.Model): token = models.CharField() secret = models.CharField() user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL) class TwitchToken(models.Model): token = models.CharField() secret = models.CharField() user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL) Please give me an explanation of why one would be chosen over the other. -
How to find the file corresponding to a specific python module?
When a python3 program uses a module "m", what line can I write to make it print the location of the file containing the sourcecode for "m"? In my specific exemple, I am learning Django by reading the source of an app (django-wiki), which contains the following line: urlpatterns += url(r'', include('wiki.urls')) I want to modify the file containing wiki.urls (I cloned django so I assume I have the file somewhere). I thought I found it (src/wiki/urls.py), but then I realized that this file mostly contains compatibility functions, and my changes had no effect. Therefore I am trying to see where exactly python goes to find "wiki.urls". I used find and grep to look for parts of the urls which should be defined in wiki.urls (for example, "signup"), but this only returns this "compatibility" file. -
How do I display a different HTML attribute value in a Django template based on whether a mobile device is used?
I'm using Django and Python 3.7. I want to change the href in a template depending on whether a certain condition is satisfied (the user is viewing the page on a mobile device). If the user is using a regular device, the URL would be {{ articlestat.article.path }} Otherwise the path would be the above, except wiht the "www." replaced by "mobile.". What's the right way to do this? I have the below {% if request.user_agent.is_mobile %} <td align="center"><a href="{{ articlestat.article.path }}" target="_blank">Read Article</a></td> {% else %} <td align="center"><a href="{{ articlestat.article.mobile_path }}" target="_blank">Read Article</a></td> {% endif %} but it seems a little lengthy and I'm thinking there's a more concise way in Django to write all of the above. -
Django display radio button choice
i want to display vaule_fields of my User model as selectable choice radiobuttons, any idea how to do this? class Send_Payment_Form (forms.ModelForm): class Meta: model = User fields = ['acc_usd_balance', 'acc_eur_balance', 'acc_rub_balance'] CHOICES = (('acc_usd_balance', 'USD',), ('acc_eur_balance', 'EUR',), ('acc_rub_balance', 'RUB',)) choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) template.html .... <table> {{ form.as_p }} {{ field.help_text }} <br> </table> .... currently they are displayed as input fields?!