Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django vs Kivy comparison
I just found out about kivy and I also started developing with Django recently. I'd please like to extensively compare Kivy with Django. What are the major differences? Which one is relevant now, and will be relevant in the next five years? What are their advantages and disadvantages? What kind of apps can I build with Kivy? What's the best or most recommended JavaScript framework to mix with either of the two? -
I have a REST api on Django. Which UI technology should I use - Nodejs or Angular?
I have a couple of REST apis built using django rest framework. I want to build a UI using those APIs. I am not sure which UI technologies should I be using - Nodejs or Angularjs ? I plan to have few animations in UI to give a good feel while using the UI. What will be the pros and cons? Please suggest. -
AssertionError at /graphql/ Query fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping
I am new to django and graphql, I am trying use graphql in django using the the instructions given in this site. https://docs.graphene-python.org/projects/django/en/latest/installation/ I followed the instructions carefully but when I enter the url http://127.0.0.1:8000/graphql/ I am getting the error following error. AssertionError at /graphql/ Query fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping. I just have a single app called demo. The code in the models.py of demo app is as follows... from django.db import models # Create your models here. class UserProfile(models.Model): userId = models.IntegerField(primary_key=True) userName = models.CharField(max_length=15) password = models.CharField(max_length=15) address = models.CharField(max_length=30) phoneNumber = models.IntegerField() class Meta: db_table = 'UserProfile' Here are the relevant parts of the settings.py file in the project folder. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'corsheaders', 'demo', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True GRAPHENE = { 'SCHEMA': 'abc.schema.schema' } abc is the name of the main project folder which contains manage.py. Please help,thanks in advance. -
Avoid duplication in Django when having to format a message both in a template and as a response from an ajax call
I have a chat board where people can post messages that can include attachments and some other additional things. When I retrieve all messages I loop over them and display each message in this way (simplified): <p>Message posted by: <strong>{{ details.name }}</strong></p> <p>{{ details.message }}</p> <ul> {% foreach attachment in attachments %} <li>{{ attachment }}</li> </ul> {% endforeach %} So far, so good. Now, my difficulty is that I use AJAX to allow people to post new message. Upon adding a new message, I struggle to find the best way to show this message to the user. The problem is that the new message needs to be formatted in a particular way (the above is a simplification; there are various conditions and additional formats). I can think of three ways: I use javascript to parse the message. That means I basically have the same code twice, in two different languages (once in Django's template language for all existing message, and then again in js for newly added messages) I craft the exact same HTML code in the view, so when I return a response through AJAX it already includes properly formatted code. However, this will also be a duplication of … -
How to Redirect to a POST url and pass data in django
I'm trying to integrate payfort payment gateway using the redirection method. it requires redirecting to a POST url and submitting some data. the data contains confidential values like access code and merchant code, so i don't want to expose them in HTML. Is it possible to redirect to a POST URL from a django view and submit the data? or should I use ajax to perform the signature calculations and submit the form using jquery. I'm kind of lost. any help is appreciated. -
How to sort by nested objects integer field
I'm trying to get elasticsearch docs sorted by price. I have this docs: class OfferDocument(InnerDoc): partner_price = Float() class ProductDocument(DocType): view_count = Integer() offers = Nested(OfferDocument) So, I have 55000 products in elasticsearch and I have to get them sorted by its offers price. So what I did: s = ProductDocument.search().query(some_query).sort({'offers.partner_price':{'order':'asc', 'mode': 'min'}}) When I do: s = ProductDocument.search().query(some_query).sort({'view_count':{'order':'desc'}}) It sorts correct. But It sorts incorrectly with nested object offer and its field partner_price. What's my problem? -
Django admin - Hidden field - Cannot assign must be an instance
I have a CustomUser model with ForeignKey to another model. In my Signup form, I'm using a hidden field that is populated with a value depending on a search result from the user (the user is searching for a company and after clicking on the result the hidden input value represents that company's ID). When I'm saving the User object I can easily get the ID, make a query and add the company object to the field. The problem is with my Admin. The Admin is using the same form and the company field is rendered as hidden with the ID value. When I try to change some User info and try to save it I get this error: Cannot assign "'3'": "CustomUser.kompanija" must be a "Kompanija" instance. I thought that the Admin is using the same save method from my custom UserAccountAdapter...? Is it possible to override the hidden input just for the Admin to show: forms.ModelChoiceField(queryset=Kompanija.objects.all(), empty_label="Kompanija") with initial value from the saved user object? My models.py: class Kompanija(models.Model): naziv = models.CharField(max_length=50) adresa = models.CharField(max_length=50, blank=True) def __str__(self): return self.naziv class CustomUser(AbstractUser): ime = models.CharField(max_length=30, default='') prezime = models.CharField(max_length=30, default='') kompanija = models.ForeignKey(Kompanija, on_delete=models.CASCADE, null=True, blank=True) is_premium = … -
Django change the field value after changing the value from another field
Im trying to add the value from another field/ColorField to another field. I currently made it work using the code below. The problem is once yun change the color in the admin changeview page the color_label does not get updated you need to save the actual data so the color_label will be updated. Any suggestions on how to make this work? Any signals that will be triggered after a form field has been changed? Model class Colors(models.Model): color = RGBColorField(null=True,blank=True) Admin class ColorsAdminForm(forms.ModelForm): color_label = forms.CharField() def __init__(self, *args, **kwargs): super(ColorsAdminForm, self).__init__(*args, **kwargs) self.fields['color'].label = 'Actual Color' self.fields['color'].disabled = True self.fields['color_label'].initial = self.initial['color'] -
How to set Python module like uwsgi in AWS beanstalk
Some applications I am deploying are using __init__.py instead of wsgi.py or application.py (app/wsgi/__init__.py) and setting a WSGI module like uwsgi would be great (module = app.wsgi:application in uwsgi.in) myapp/wsgi/__init__.py == myapp.wsgi:application .ebextensions/django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: saleor/uwsgi/__init__.py (!!! DOES NOT WORK !!!) uwsgi.ini: [uwsgi] die-on-term = true http-socket = :$(PORT) log-format = UWSGI uwsgi "%(method) %(uri) %(proto)" %(status) %(size) %(msecs)ms [PID:%(pid):Worker-%(wid)] [RSS:%(rssM)MB] master = true max-requests = 100 memory-report = true module = saleor.wsgi:application processes = 4 static-map = /static=/app/static mimefile = /etc/mime.types New account at AWS forums so can't post a question there yet. SO to the rescue! -
django.core.exceptions.ImproperlyConfigured: WSGI application 'invoice_project.wsgi.application' could not be loaded; Error importing module
I suddenly opened my Django project and when I tried to launch it with py manage.py runserver it gave me this error. django.core.exceptions.ImproperlyConfigured: WSGI application 'invoice_project.wsgi.application' could not be loaded; Error importing module. This is my traceback. I checked the settings.py and the wsgi.py file and they both (I think) are configured properly, therefore I do not know where to start looking for the error Traceback (most recent call last): File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Enrico\Desktop\prova\django_invoice\invoice_project\invoice_project\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\site-packages\django\core\handlers\wsgi.py", line 135, in __init__ self.load_middleware() File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\site-packages\django\core\handlers\base.py", line 35, in load_middleware middleware = import_string(middleware_path) File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Enrico\.virtualenvs\invoice_project-JDtH6-bZ\lib\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 … -
django template language is not the same as jinja2
i'm new in Django. i'm really curious to Django template language. i have used jinja2 before Django template language. Some people say says that jinja2 and Django template language are the same. But i stuck on if statement on Django template language. usually when we are comparing some value to "True" we are usually not using "==" : {% if somevalue %} ..... {% endif %} instead of.... {% if somevalue == true %} ..... {% endif %} i can't do the first method... why ??? -
How to pass python variable to javascript in django template for Dygraph
I want to send a pandas dataframe output that is in Django Views.py, to the template in order to graph in a Dygraph. The Dygraph will display if I leave the array definition in the template with the Dygraph script. If I copy that same array definition to views.py and render it to the template the graph won't display. The example array from Dygraphs (http://dygraphs.com/data.html#array). And it works correctly. output.html: <div id="graphdiv"></div> <script> new Dygraph( document.getElementById("graphdiv"), [ [1,10,100], [2,20,80], [3,50,60], [4,70,80] ] , ); </script> Below is my intent with the array defined in views.py, but this won't render the graph. Views.py: def output(request): DAT = [ [1,10,100], [2,20,80], [3,50,60], [4,70,80] ] #DAT = json.dumps(DAT) This doesn't seem to help either. data = { 'DAT': DAT, } return render(request, 'cylon/output.html', data) ------------------------------------------------------ Output.html: <div id="graphdiv"></div> <script> new Dygraph( document.getElementById("graphdiv"), "{{DAT}}" , ); </script> -
Django rate-limit not run
I want to limit the number of login is 2, so I use Django rate-limit, but I can log in with 3rd account in mobile. Any suggestions what I am doing wrong? views.py @ratelimit(key='user_or_ip', rate='1/m', method=['GET', 'POST']) def login(req): was_limited = getattr(req, 'limited', False) if was_limited: mess = "Try again" return HttpResponse(mess) if req.method == 'POST': login_form = LoginForm(req.POST) if login_form.is_valid(): email = login_form.cleaned_data['email'] password = login_form.cleaned_data['password'] user = authenticate(username=email, password=password) if user is not None: auth_login(req, user) if user.is_staff != 0: return HttpResponseRedirect('/admin') return HttpResponseRedirect('/') else: return render(req, 'app/templates/pages/login.html', {"result": "Account is incorrect", 'form': login_form}) elif req.user.is_authenticated: if req.user.is_staff != 0: return HttpResponseRedirect('/admin') return HttpResponseRedirect('/') else: form = LoginForm() return render(req, 'app/templates/pages/login.html', {'form': form}) settings.py # RATELIMIT SETTINGS #RATELIMIT_CACHE_PREFIX = 'rl:' RATELIMIT_ENABLE = True RATELIMIT_USE_CACHE = 'default' #RATELIMIT_VIEW = None MIDDLEWARE = [ ... 'ratelimit.middleware.RatelimitMiddleware' ] -
Change paragraph on homepage from django admin panel
I want to be able to edit paragraphs on my homepage from the django admin panel. I tried making a "Homepage" class in models.py and calling it like so. models.py class Homepage(models.Model): homepage_image = models.ImageField(blank=True) image_text = models.CharField(max_length=200, blank=True) header_title = models.CharField(max_length=200, blank=True) header_text = models.TextField(blank=True) class Meta: verbose_name_plural = "Homepage" def __str__(self): return "Homepage" views.py from .models import Homepage # Create your views here. def homepage_view(request): context = { "title": "Grey Bear Industries | Home", "homepage": Homepage.objects.all() } return render(request, "main/index.html", context) index.html <p class="lead"> {{ homepage.header_text }} </p> This may not be the ideal way to do this as in django admin I only want to have one "Homepage" that I can edit and swap out pictures from rather than having the add button. -
how to show short version of post in the main page of template in django
I'm writing a blog app and I want to show short versions of posts on the main page, after title then would have just 4 line of detail of each post then have another post, but problem is post of detail all shows in the main page. def tours(request): featured = Tour.objects.filter(featured=True) context = { "object_list": featured, } return render(request, 'tours.[html][1]', context) def sidebar(request): return render(request, 'sidebar.html', {}) -
cannot import name 'detail_route' from 'rest_framework.decorators'
I'm trying to run longclaw but when I python manage.py migrate i get an error . $python manage.py makemigrations catalog home Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/urls/resolvers.py", line 398, in check for pattern in self.url_patterns: File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/x/Documents/Longclaw/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "/home/x/Documents/Longclaw/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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen … -
Django 2.2 staticfiles don't work in production (DEBUG False)
I'm making a new django app where a user can upload images and then they can be displayed on a page. I've read the django docs 10000 times through and I still don't understand why my images aren't loading. All my images are going to where they're supposed to be and in the admin in my models django has the right path that leads to the image but it just won't load properly. my setup in settings.py: STATIC_URL = '/static/' STATIC_ROOT = 'static' # live cdn such as AWS S3 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') MEDIA_URL = '/img/' my directories: |- src |- myproject |- settings.py, views.py, urls.py etc |- myapp |- views.py urls.py models.py forms.py etc |- static (this folder is empty and appeared after running collectstatic |- templates |- db.sqlite3 |- manage.py |- static (this folder is OUTSIDE src) |- admin |- django admin stuff |- media |- img |- myimage.png in models.py of myapp the imagefield upload_to = 'img/' if i am in debug mode and i add the reccomended code to make it work: if settings.DEBUG: from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) everything works. this … -
Django Model Query to Group Results By Month/Year and Display Each Month's Results in Separate DIV Elements
I want to create a model (name is Event) query in my view that groups events by month/year (launch_date field), then I want to display (using a for loop) the group of each month's events in it's own DIV element. For example, all September 2019 events would be in a single DIV element, all October 2019 events would be in a single DIV element next to September, and so on. The model is really simple: class Event(models.Model): name = models.CharField(max_length=300, blank=True) overview = models.TextField(max_length=1200,blank=True) launch_date = models.DateField(blank=True, default=datetime.now) Any help on this would be appreciated. -
Pycharm debugger not working with docker for mac
When starting my debugger docker seems to run fine with no errors but I do not get a connection to my localhost server. Docker logs are fine as well. This issue only occurs when starting the debugger. I am using docker for mac. -
django auth form jump to login page
i would like to protect some web pages to use only auth users to have access and if user is not auth then jump him to login page.but I have some errors because auth users jump to dead link . here the code entry page : @login_required(login_url="login/") def add_entry(request): if request.method == "POST": form = entryForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.save() else: form = entryForm() return render(request, 'add_entry.html', {'form': form}) urls.py url(r'^add-entry/$', views.add_entry, name='add_entry'), url(r'^login/$', views.login, {'template_name': 'auth/login.html', 'authentication_form': LoginForm}), dead link : 127.0.0.1:8000/add-entry/login/?next=/add-entry/ any idea ?thanks -
Define Django model with flaggit
I'm trying to use this django app https://github.com/mkalioby/ModelTracker I believe I have installed the dependency via pip in my environment. Then in models.py I have import flaggit print(flaggit) class Thread(flaggit.models.Flag): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True ) but I get error AttributeError: module 'flaggit' has no attribute 'models'. Can someone provide a minimal example of how to use this django app? I'm using django rest framework btw. -
How to create Django objects so as to avoid duplicate key errors after restoring your database?
In Django, when you create an object, either with a Django helper function like 'create_user' or with an object's 'create' method, Django automatically creates an auto-incrementing primary key for that new object: user = User.objects.create_user(username='foo', password='bar') # id = 1 user.save() account = Account.objects.create(user=user) # id = 1 account.save() But in the real world, if your server crashes and you have to rebuild your database server and then reload all your data, the first time you try to create a new object, you're going to get this type of error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "new-object_pkey" Whenever you create a new model instance, Django seems to assume you're starting with a clean, new database and it assigns the new object an id of 1 even though, if you had to restore the database, you already have an object in the restored table with an id of 1. What is the "Django way" to avoid this situation with both Django's helper functions as well as the object "create" method? I would think that this would be a common problem for any production Django website and that Django would recognize this and handle it automatically. But I don't see such … -
I am trying to inser dictionary in database from django how to do this task at onclick event
I need code example to insert data from data dictionary in data base from django please help. I am stuck in this -
Django Admin formfield_for_foreignkey generic owner filter
I want to use formfield_for_foreignkey method to filter owned objects in selection list. There are many so i wanted to use a generic way. Also show all if super user. This is what i found in the documentation. class OwnerFilteredAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "company": kwargs["queryset"] = Company.objects.all() if request.user.is_superuser is not True: kwargs["queryset"] = kwargs["queryset"].filter(client=request.user.userprofile.client) return super().formfield_for_manytomany(db_field, request, **kwargs) return super().formfield_for_manytomany(db_field, request, **kwargs) class FooAdmin(OwnerFilteredAdmin): # configs In this case, only work for Company model. ¿Any ideas? -
ListView without queryset
I am trying to increase performance in a view that has to render a list of events. Currently, I populate a database table on the fly and with a generic list view I show it. However, since it has to do a dababase bulk insert it takes few seconds. I wonder if there is a way -since I have the information in a list in memory- to use the ListView not having to create the database table and the respective queryset. I mean to render the LisView directly from the list structure that I have in memory. Is it possible ? I would appreciate if anyone can give me a hand with this since I have not found any information in google regarding this issue. Best regards.