Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
You have 1 unapplied migration(s)
I cannot able to search and migrate the 1 unapplied ...help me out -
Get HTML and CSS from grapes.js newsletter editor in Javascript
How to get output HTML and CSS of grapes.js in Javascript ? I am writing a Django app for newsletter, in which i need a newsletter editor for which i used "grapes.js" newsletter. Everything is fine but i am stuck in part where i need to get the HTML and CSS of the template created with it. I have: <script type="text/javascript"> var editor = grapesjs.init({ container : '#gjs', plugins: ['gjs-preset-newsletter'], pluginsOpts: { 'gjs-preset-newsletter': { modalTitleImport: 'Import template', 'grapesjs-plugin-export': { /* options */ } // ... other options } } }); function returnHtml(){ console.log('test') const mjml = editor.getHtml; preview = editor.getHtml $("#myiframe").contents().find("body").html(mjml) } returnHtml(); This code gives me the html of the template but without the css ! i have tried https://github.com/artf/grapesjs-mjml/issues/2. Can someone please suggest me what i am missing ? Thanks. -
What are the difference between django structure in different project scale
How we implement Django on different scale project: fro single app, Medium size app, large apps and enterprise app? -
Django - 'User' object is not iterable
When i am passing instance1 in context it giving error 'User' object is not iterable. I want to display Name in Template of pk. Example http://localhost:8000/users/15/profile-update/ pk=15 def userProfileUpdate(request, pk): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=User.objects.get(id=pk)) p_form = UserProfileForm(request.POST, request.FILES, instance=UserProfile.objects.get(user_id=pk)) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Profile Updated!!!') return redirect('users') else: instance1 = User.objects.get(id=pk) u_form = UserUpdateForm(instance=User.objects.get(id=pk)) p_form = UserProfileForm(instance=UserProfile.objects.get(user_id=pk)) context ={ 'object': instance1, # This is giving the error 'u_form': u_form, 'p_form': p_form } return render(request, 'users/userprofile.html', context) -
Changing error messages in django-rest-auth
Whenever I make a POST request with an empty username value, I get the following error message: "username": [ "This field may not be blank." ], I'd like to change this error message to my own custom error message. However, in my User model I try to create a blank error message like so: class User(AbstractBaseUser): username = models.CharField(max_length=15, unique=True, error_messages={ 'blank': 'You have to have a username!', 'unique': "Username has already been taken.", }) However, this error message does not show, instead the default error message shows. How can I show my own custom error message? The unique error message shows up fine, it's just the blank one doesn't show up. -
sshtunnel.BaseSSHTunnelForwarder Could not establish session to SSH gateway
I am using django with mysql database to develop apis. Now I got a new requirement to connect mongodb database with django. I have used following solution from sshtunnel import SSHTunnelForwarder import pymongo import pprint MONGO_HOST = "REMOTE_IP_ADDRESS" MONGO_DB = "DATABASE_NAME" MONGO_USER = "LOGIN" MONGO_PASS = "PASSWORD" server = SSHTunnelForwarder( MONGO_HOST, ssh_username=MONGO_USER, ssh_password=MONGO_PASS, remote_bind_address=('127.0.0.1', 27017) ) server.start() client = pymongo.MongoClient('127.0.0.1', server.local_bind_port) # server.local_bind_port is assigned local port db = client[MONGO_DB] And now I am getting following sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway Is it good way to connect mongodb in django poject? -
Push notification in django rest
I am working on a attendance registration system where a user of an office can make a leave request. When any user makes a leave request, it must be notified to admin. How do I implement it ? I had seen django-fcm for push notification. But I am using django rest framework . Can I implement django-fcm with django rest ? If any tutorials link would be more helpful -
Unable to view content in DetailView Django
I am trying to view the content in my blog posts using django DetailView class but when I run the local server and click on the headline link in my blog post, while the url bar changes to read the correct post, the actual page stays the same, and so I can't view individual blog posts. Here is the section of code were the problem lies. #view.py class PostListView(ListView): model = Post template_name = 'post_list.html' class PostDetailView(ListView): model = Post template = 'post_detail.html' #urls.py urlpatterns = [ path('post/<int:pk>', PostDetailView.as_view(), name='post_detail'), path('', PostListView.as_view(), name='post_list'),] #post_list.html {% for post in post_list %} <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a></h2> <p> {{ post.tagline }} </p> -
id(number) path in urls
I am new to django In urls.py, I set path like this. I tried to create a page with urls: localhost:8000/topics/1/ urlpatterns = [ path('topics/(?P<topic_id>\d+)/', views.topic, name='topic'), ] In views.py. Code is this: def topic(request, topic_id): """Show a single topic and all its entries""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('date_added') context = {'topic': topic, "entries": entries} return render(request, 'learning_logs/topic.html', context) I got error 404 when enter localhost:8000/topics/1/. topics/(?P\d+)/ [name='topic'] The current path, topics/1/, didn't match any of these. But the correct urls turns out to be: localhost:8000/topics/(%3FP1%5Cd+)/ Is there something wrong with the path in urls or what's the problem? -
How to limit fields returned in django queryset per field
I have rows of products, that tend to share some information, such as the same images (an image may show multiple products), descriptions, manufacturer, etc. I would like to choose some fields to only show the information once. I can't use distinct for this (I don't think) as the information is not always identicle, such as with the description, but may be only subtly different enough that I don't want to repeat it. At the moment, I am using a for loop to display fields from each result, which ends up with something like this: This is the code I am using in my view: def collection_detail(request, name=None): template = loader.get_template('/webapps/mywebapp/furniture/main_page/templates/main_page/detail.html') products = product.objects.filter(id=name) cart_product_form = CartAddProductForm() context={'products': products, 'cart_product_form': cart_product_form} return HttpResponse(template.render(context)) What would be the appropriate way to do this in a view, ignoring subsequent rows for some fields? -
AttributeError: 'CloudWatchLogHandler' object has no attribute 'shutting_down' while deploying django-rest-api into aws
i have deployed my django-rest-api application into aws using zappa. its working fine but sometimes i'm getting error like AttributeError: 'CloudWatchLogHandler' object has no attribute 'shutting_down'(im using watchtower for logging in aws).please help me out in settings.py for logs : from boto3.session import Session import logging boto3_session = Session(aws_access_key_id=S3_ACCESS_KEY_ID, aws_secret_access_key=S3_SECRET_ACCESS_KEY, region_name=S3_REGION) LOGGING = { 'version': 1, 'disable_existing_loggers': False, # 'root': { # 'level': logging.ERROR, # 'handlers': ['console'], # }, 'formatters': { 'simple': { 'format': u"%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'aws': { # you can add specific format for aws here 'format': u"%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'watchtower': { 'level': 'INFO', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_session': boto3_session, 'log_group': 'test_logs_group', 'stream_name': 'test_stream_name', 'formatter': 'aws', }, }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['watchtower'], 'propagate': False, }, # add your other loggers here... }, } i kept that code in settings.py for logging using watchtower in cloudwatch -
Security: bypassing login with URL entry
I’m looking to create a login system for my Django web application with is connected to a MySQL database with a table for managers that holds their name, email, and password. My login screen has a URL of localhost/login. I want to query the off-server database for the username and password for each manager that was entered when the user puts in the information. If the credentials match, then I want to redirect them to the manager page, which is localhost/manager. If they don’t match, then I want to keep them at that page, localhost/login. My question is what’s stopping the user from inputting the localhost/manager URL path into their browser and bypassing the login, getting access without getting authenticated? Is there a good way to store the user name and password in the database to make them more secure but also accessible and checkable again? -
how to populate data in formset from the model data where there is variable no. of added forms
i have formset where i want to populate the data from database at the time of edit details and i have multiple no. of forms there js script is embeded in template/app/skills.html at bottom. forms.py class skillform(forms.Form): name = forms.CharField( label='Skill', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Your Skill here' }) ) level = forms.ChoiceField(choices=(('Novice','Novice'),('Beginner','Beginner'),('Skillful','Skillful'),('Experienced','Experienced'),('Expert','Expert')),label="level",initial='Skillful',widget=forms.Select(),required=False) skillformset = formset_factory(skillform) models.py class userskills_model(models.Model): userid = models.ForeignKey(user_model, on_delete=models.PROTECT) skills =models.CharField(max_length=264, unique=False, blank=False,null=False) skills_level = models.CharField(max_length=264, unique=False, blank=False, null=False) def __str__(self): return str(self.userid) templates/app/skills.html {% extends 'app/base.html' %} {% load staticfiles%} {% block head %} <link href="{% static "/css/skills.css" %}" rel="stylesheet" type="text/css"/> {% endblock %} {% block content %} <div class="heading_text">SKILLS</div> <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> <div class="col-5"> <label>{{form.name.label}}</label> <div class="input-group"> {{form.name}} </div> </div> <div class="col-5"> <label>{{form.level.label}}</label> <div class="input-group"> {{form.level}} <!-- <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> --> </div> </div> <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> </div> {% endfor %} <div class="row spacer"> <div class="col-3 button1"> <button type="submit" class="btn3">Save and Continue</button> </div> </div> </form> {% endblock %} {% block custom_js %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script type="text/javascript"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + … -
Display thumbnail from image without creating or modifying file, based off of url?
I have a database with rows, with one of the fields being image_url. The images specified by these urls are high resolution and have different aspect ratios. I need to use some of these images to display thumbnails. I am thinking of running them through an image program to automatically create thumbnails, and then add a new image_thumbnail_url field of the like. Alternatively, I have seen some software which leads me to believe it may be possible for django to take these images, resize them in memory and then serve them to the client, without having to create new resize images. Is such a method possible, and if it is possible, is it efficient, or frowned upon? -
How to have a local instance or React hit a local instance of Django
I have a django api (djangorestframekwork, django2.1, python 3.6) that I run locally - http://127.0.0.1:8000/api/cards/b361d7e2-6873-4890-8f87-702d9c89c5ad. This api seems to work well. I can hit it via the web api or use curl/requests to add to or view the database. Now, I want to be able to have my React project hit this api. I can have my react project hit a different api and it returns the data, but when I replace that URI with my own URI it breaks. App.js - there is one line commented out. Switch that out with the other to switch between the public and private api. import React from 'react' import keyforge from '../api/keyforge' import localhost from '../api/localhost' import SearchBar from './SearchBar' class App extends React.Component { onSearchSubmit = async (term) => { const response = await localhost.get("api/cards/" + term) //const response = await keyforge.get("api/decks/" + term) console.log(response) } render () { return (<div className='ui container'> <SearchBar onSubmit={this.onSearchSubmit} /> </div>) } } export default App keyforge.js - this one works! import axios from 'axios' const proxyurl = 'https://cors-anywhere.herokuapp.com/' const url = 'https://www.keyforgegame.com/' export default axios.create({ // baseURL: 'https://www.keyforgegame.com/api/decks/' baseURL: proxyurl + url }) localhost.js - this one does not work import axios from 'axios' … -
Accessing dictionaries given django template's attributes?
So my problem is that I need to iterate over a dictionary given an attribute, which is the value of the for loop. For example, I have a dictionary called my_dictionary which is being iterated by a for loop in a django template, with an attribute called q. What I need is to access to that dictionary by using the q attribute. I tried with {{my_dictionary.q}}, {{my_dictionary.{{q}} }} but none of them did work. What can I do? I guess it should be similar as in Python my_dictionary[q]. Thank you. -
User Profile 'Syntax Erro'r in Django
I am trying to create the user profile in Django. t is a new User model that inherits from AbstractUser. It requires special care and to update some references through the settings.py. Ideally, it should be done at the beginning of the project, since it will dramatically impact the database schema. Extra care while implementing it. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/user/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/user/anaconda3/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/user/anaconda3/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 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/user/Desktop/vmail/vm/models.py", line 21 user = models.OneToOneField(User, on_delete=models, CASCADE) ^ SyntaxError: positional argument follows keyword argument how to solve this syntax error? my models.py # -*- coding: utf-8 -*- … -
What are dependancies and why should I care about them?
I am a beginner to web development, and am currently engaged in creating a Django web application to interface with a MySQL database. Through the time I've spent reading the documentation for Django, it constantly talks about isolating dependancies using virtual environments like virtualenv. I don't really understand what a dependency is and why creating a virtual environment would help 'isolate' them from each other. What is a virtual environment? Is it like another machine running on your machine? Any input for these conceptual questions would be much appreciated. -
WHY connect MySQL database to Django?
I am creating my first ever Django web application, which is essentially a portal for managers to view the current status of a MySQL database. I’m having trouble understanding why I should connect MySQL to Django instead of just writing Python scripts to connect directly to the database using the pymysql library. Plus, if I decide to go forward with connecting Django and MySQL, what would interfacing them look like? I'm currently hosting both the Django web app and the MySQL database on my computer, but will eventually host them on external servers. I'm a webdev beginner and any input would be much appreciated. -
migrate failure (django 1.7) need some
Hi I have a problem in migrate I want to help I looked at all the models I could not figure out the solution Applying accounts.0013_add_primary_interests...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "/Users/mumirahibrahim/Desktop/mo/Fudulbank/accounts/migrations/0013_add_primary_interests.py", line 14, in add_primary_interests exam_content_type = ContentType.objects.get(app_label='exams', model='exam') File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/mumirahibrahim/Library/Python/3.6/lib/python/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. please help me -
Sending SMTP email with Django and Sendgrid on Heroku
I'm trying to send email using SMTP and sendgrid for a Django app. I'm able to send emails on my local server, but on my heroku app I get an "SMTPServerDisconnected" error saying "connection unexpectedly closed. Is there a way to send SMTP email with sendgrid once deployed to Heroku? I can't seem to find any documentation on this. Here are my settings for email in settings.py: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'EMAIL_HOST_USER' EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'email@email.com' SENDGRID_API_KEY='SENDGRID_API_KEY' SENDGRID_PASSWORD='SENDGRID_PASSWORD' SENDGRID_USERNAME='SENDGRID_USERNAME' Please let me know what settings you use to send SMTP email. Thanks. -
403 Forbidden response on a django app deployed using nginx, supervisor and gunicorn
I have been trying to solve this for the past few days. So any help is much appreciated. I have a VPS installed with ubuntu server 18.04 and am trying to deploy a django app using supervisor, gunicorn and nginx. I am a newbie to this platform and so following this tutorials. https://jee-appy.blogspot.com/2017/01/deply-django-with-nginx.html My setup on the server is as the only user 'root'. Django: 2.1.4 nginx: nginx/1.14.0 (Ubuntu) gunicorn: (version 19.9.0) geteat.conf (/etc/nginx/sites-available) upstream geteatapp_server { server unix:/root/djangoproject/geteat_dir/geteat_venv/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 26.208.54.108; client_max_body_size 4G; access_log /root/djangoproject/logs/nginx-access.log; error_log /root/djangoproject/logs/nginx-error.log; location /static/ { root /root/djangoproject/geteat_dir/geteat/; } location /media/ { root /root/djangoproject/geteat_dir/geteat/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # proxy_set_header Host $http_host; proxy_set_header Host $host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://geteatapp_server; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /root/djangoproject/geteat_dir/geteat/static/; } } gunicorn_start.bash (at the project root) #!/bin/bash NAME="geteatapp" # Name of the application DJANGODIR=~/djangoproject/geteat_dir/geteat/ # Django project directory SOCKFILE=~/djangoproject/geteat_dir/geteat_venv/run/gunicorn.sock # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as … -
Auto fill Django form fields with Javascript/Jquery. Like HTML forms
How do I add id's to my Django form input fields so I can auto fill them using jquery. If I had to do it for a regular HTML form I would do it like below HTMl Form: <form method="post" action="{% url 'accounts:edit_location' %}" style="display: none"> {% csrf_token %} <input id="Alpha" type="text" > <input id="Beta" type="text" > <button>Locate Me</button> <!----When user presses this button the Jquery auto fills the Alpha and Beta fields with a value----> <button type="submit" id="submit">Submit</button> </form> But since I am doing it with Django forms, I tried the below approach but it did not work Django Form: class EventForm(forms.ModelForm): price = forms.DecimalField(decimal_places=2, max_digits=5) stock = forms.IntegerField() class Meta: model = Tasting fields = ('price', 'stock', 'date', 'time_from', 'time_to', 'note', 'served_in', 'lat', 'lon') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['lat'].id = "tasting_lat" self.fields['lon'].id = "tasting_lon" Below is a image of the form The Question: I need to move the locate me button above the lat, lon fields I need to add id=something to the input field in my Django Form Can anyone suggest how I can do the above? -
Django - Forms: 'module' object is not callable error
I am trying to update several rows in my table. Same with this question. I modified codes for my project and trying to solve it since a few days but it doesn't work for me. Firstly, i am show all existing rows in html page in a form. And if it is POST request then trying to save into db. I have 2 error here. 1. If i use return render_to_response('module.html',{'modules' : modules}) it is showing data in html page like i want but when click to save button, it give below error: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. If i use return render(request, 'module.html',{'modules' : modules}), it is not even showing data and just give below error : 'module' object is not callable Could you please help me find problem with my code? models.py class ModuleNames(models.Model): ModuleName = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) ModuleSort = models.SmallIntegerField() isActive = models.BooleanField() ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True) slug = models.SlugField(('ModuleName'), max_length=50, blank=True) class Meta: app_label = 'zz' def __unicode__(self): return self.status views.py @cache_page(60 * 15) @csrf_protect def addmodule(request,moduletype): modules='' if request.method == 'POST': data = request.POST.dict() … -
Django PIL unexpected image rotation
I have a Django project with a model with ImageField fields, I use Pillow to manage images, but I find that Images are rotated and are always saved in portrait orientation, in despite of its original orientation. Is there any way to instruct PIL not to change image orientation, but to keep the original one?