Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rerouting request via middleware in django
I have a java server sending out a request where the path contains the hostname. OTOH I've got an ancient django server (1.8) that figures (wrongly) that the hostname is part of the path, and always returns a 404. Assuming that sending properly formed requests from java side is not possible, how would I go about modifying the request URL to something that can be properly redirected to, without actually redirecting? (a 30x is also unacceptable in this case). -
Using parameters in create viewset?
In a specific usecase of my application, I would like to do some logic (varies based on what the user chooses - and thus passed through via the API url) in order to create and return a model. In my application I have a simple test model and question model (each question has a concept: class Question(models.Model): text = models.CharField(max_length=255, null=False) concept = models.CharField(max_length=255, null=False) class Test(models.Model): num_questions = models.IntegerField() questions = models.ManyToManyField(Question) I hoped that user would be able to do a create as such XXX/api/v1/test/create/Math and this would return them a test with questions randomly chosen that pertain to math. in my url I have explicitly called out path('test/create/<str:concept>', CreateTestView.as_view(), name="test-create="), However, when I try and reference this, it does not allow me to pass it in (erroring out with concept is not defined): class CreateTestView(generics.ListAPIView, concept): test = Test() ... add random questions to test queryset = test serializer_class = TestSerializer -
graphite.wsgi' cannot be loaded as Python module
I installed graphite on Ubuntu 18.04 but i have the following issue: I did: - Permissions: chown -R www-data:www-data /usr/share/graphite-web/ chmod +x /usr/share/graphite-web/graphite.wsgi Replacing graphite.wsgi with: import sys # In case of multi-instance graphite, uncomment and set appropriate name # import os # os.environ['GRAPHITE_SETTINGS_MODULE'] = 'graphite.local_settings' sys.path.append('/opt/graphite/webapp') from graphite.wsgi import application Bu still the same issue: [Sun Apr 14 23:14:18.673665 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] mod_wsgi (pid=4639): Target WSGI script '/usr/share/graphite-web/graphite.wsgi' cannot be loaded as Python module. [Sun Apr 14 23:14:18.673693 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] mod_wsgi (pid=4639): Exception occurred processing WSGI script '/usr/share/graphite-web/graphite.wsgi'. [Sun Apr 14 23:14:18.673707 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] Traceback (most recent call last): [Sun Apr 14 23:14:18.673722 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] File "/usr/share/graphite-web/graphite.wsgi", line 14, in <module> [Sun Apr 14 23:14:18.673755 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] application = get_wsgi_application() [Sun Apr 14 23:14:18.673773 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] File "/usr/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Sun Apr 14 23:14:18.673786 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] django.setup(set_prefix=False) [Sun Apr 14 23:14:18.673792 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup [Sun Apr 14 23:14:18.673808 2019] [wsgi:error] [pid 4639] [remote 127.0.0.1:47264] apps.populate(settings.INSTALLED_APPS) [Sun Apr 14 23:14:18.673815 2019] [wsgi:error] … -
How to use Haml and Django 2019
I would like to know how can i use HAML and Django together, without using django-haml, or hamlpy, because they are old and don't work with the current version of Django. How can i use the tags in Django, with haml? I spent 2 days trying to solve this issue, with various methods, but none worked, because of the fact that HAML is Ruby and Django is Python. I am interested in doing everything that django-hamlpy does, but whitout it. 1. Django code (% block code %) <div></div> (% endblock %) 2. HAML code (with Django-hamlpy in case it would work) - block code %div... 3. HAML code (by default) (% block code %) %div... (% endblock %) The only problem with the point 3 is that HAML will give you an error, because you cannot nest inside plain text. Anyone has a solution for this? I really need help on this. My mind is set to explode. Thanks. -
Post reply comment in django-mptt nested comments
In article page I'm using django-mptt for nested comments. Now all comments are saved as without parent. But how to post comment with parent? {% recursetree comments %} <div class="commentary-box"><a href="" class="commentary-box__name">{{ node.user }}</a>{% if node.parent %}<a href="#" class="commentary-box__reply">{{ node.parent.user }}</a>{% endif %} <div class="commentary-box__text">{{ node.message }}</div> <button data-function="commentaryField" data-role="ajax" data-url="{% url 'main:comment_reply' id=node.id %}" type="button" class="commentary-box__button switch">reply</button> {% if not node.is_leaf_node %} <div class="commentaries-list"> {{ children }} </div> {% endif %} </div> {% endrecursetree %} Clicking reply button displays the following form: <form name="commentary" method="POST" action="" enctype="multipart/form-data" class="commentary-box add"> {% csrf_token %} <textarea name="message" data-relation="parent" data-role="addClass" data-target="form.commentary-box.add" required class="switch"></textarea> <input type="submit" value="Submit" class="btn colored"> </form> In this form I don't have access to parent comment instance (node.id). How to deal with it? Maybe it's possible to pass variable from template using url to another template? Or it's bad logic at all. Thanks for your time and help. -
Rewriting URL in an nginx Docker container wrongly uses internal port
I have a Django application that runs in a Docker environment; one container for gunicorn and one for nginx. My application's nginx server listens on port 9081, which is internal to the system (it's not exposed to the outside world). Another nginx container (which routes traffic) sits on port 80 and sends traffic to my site as necessary (based on the hostname a request receives). Here's my application's nginx setup, stripped down to the basics: upstream project { server gun_project:8001; # gunicorn container } server { listen 9081; server_name mytool.myhost.com; set_real_ip_from 172.17.0.0/16; real_ip_header X-Forwarded-For; real_ip_recursive on; location / { proxy_pass http://project; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; } } I want to redirect a URL on this site from one location to another (the URL has permanently changed). I'm doing so via a rewrite in the location block: location / { rewrite "^/oldpath/$" /newpath/ permanent; proxy_pass http://project; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; } When I do this, and I attempt to load the old URL (mytool.myhost.com/oldpath/) in a web browser, I'm redirected to mytool.myhost.com:9081/newpath/ which fails because it doesn't exist (that port isn't exposed externally). Is there something basic I'm missing? I don't want that internal port to be … -
Running python manage.py runserver returns error LookupError: No installed app with label 'admin'
I'm trying to run python manage.py runserver but i'm getting LookupError: No installed app with label 'admin' Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\utils\autoreload.py", line 579, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\utils\autoreload.py", line 564, in start_django reloader.run(django_main_thread) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\utils\autoreload.py", line 272, in run get_resolver().urlconf_module File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\urls\resolvers.py", line 564, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\hitma\Envs\ftest\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 996, in _gcd_import File "", line 979, in _find_and_load File "", line 968, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 667, in exec_module File "", line 222, in _call_with_frames_removed File "C:\myproject\myproject\myproject\urls.py", line 20, in path('admin/', admin.site.urls), File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\utils\functional.py", line 256, in inner self._setup() File "C:\Users\hitma\Envs\ftest\lib\site-packages\django\contrib\admin\sites.py", line 529, in _setup AdminSiteClass … -
Redirect visitor to login required view without filling any password
I am building a chat web app in django.I will open this web app in iframe on my website. I want that visitor on my website doesn't need to do any authentication work.Just enter his/her name, email-id and query-type(Billing , Product and Technical) and once form is submitted by visitor he/she will be redirected to chat-page. But i want users who will be providing customer support from my django app should login to view chat page. How can i achieve this ? P.S: Website and Django webapp are hosted on two different hosts. Cross domain is not an issue because i own both the domains and their ec2 instances. -
How to get access to django database from other python program?
I have django project in which I can display records from raspberry pi device. I had mysql database and i have send records from raspberry there. I can display it via my api, but I want to work on this records.I want to change this to django database but I don't know how I can get access to django database which is on VPS server from raspberry pi device. -
Django Humanize naturaltime templatetag only partly translating
Django version 2.1 I have an app where I show events. I want to show how long ago or how far in the future the event takes place. To do this I am using the naturaltime templatetag from the humanize package. {{ event.date|naturaltime }} # my model in models.py class Event(models.model): # ... other fields date = models.DateTimeField(...) I want the result to be in Dutch, so I changed the language in settings.py: LANGUAGE_CODE = 'nl-nl' Here is the problem: When the time difference between the current time and the datetime set in the model is larger than 24 hours, the translation is only partial. Examples with time in the past: # english one hour ago # dutch, correct een uur geleden # enlish 6 days, 2 hours ago # dutch translation, only partial 6 dagen, 2 uur ago Examples with a time in the future # english 2 hours from now # dutch translation, correct over 2 uur # enlish 1 month from now # dutch translation, only partial 1 maand from now As you can see, the 'ago' and 'from now' parts are not translated when the time difference is larger than 24 hours. I dived into the … -
Validation switcher
I need a little tip. I use the field validator in the django model. But sometimes there is a case when I need to turn off the check. I thought that a simple check box that would turn off checking could be convenient. Can you tell me where it will be better to place a handler for check box. -
Django - Relationships in Models
In Django there are field types called ForeignKey and OneToMany/OneToOne, I was wondering would I use ForeignKey or the relationship type as the field type in this scenario? User to Profile has been identified as ForeignKey but I'm unsure about the others. class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) fullname = models.CharField(max_length=100) dob = models.DateField() address = models.TextField() city = models.CharField(max_length=100) profilephoto = models.ImageField(default='default_profile.jpg', upload_to='reviewApp/static/profile_images') class Product(models.Model): name = models.CharField(max_length=100) brand = models.CharField(max_length=100) cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) category = models.CharField(max_length=100) releasedate = models.DateField() description = models.TextField() productphoto = models.ImageField(default='default_product.jpg', upload_to='reviewApp/static/product_images') class Review(models.Model): product = models.ForeignKey(Product) profile = models.ForeignKey(Profile) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = model.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)]) reviewtext = models.TextField() postdate = models.DateTimeField(auto_now_add=True) lastmodified = models.DateTimeField(auto_now=True) -
If don't see the picture after successful upload django project in heroku server then how can i solve this problems?
I have uploaded my django project in heroku server and everything working properly but when i use in settings file DEBUG=False only this time images are not visible. If i use DEBUG=True then visible images but if i use DEBUG=False then start problem. if you have this problem answer please suggest me how can i solve this problems. Anyone hearing me? This is Settings file import django_heroku import os import environ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') env = environ.Env( DEBUG=(bool, False), ALLOWED_HOSTS=(list), ) envfile_path = os.path.join(BASE_DIR, '.env') environ.Env.read_env(envfile_path) DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = env('ALLOWED_HOSTS') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRTPARTY_APP = [ 'django_filters', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', ] LOCAL_APP = [ 'protfolio.apps.ProtfolioConfig', ] INSTALLED_APPS += THIRTPARTY_APP+LOCAL_APP MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', '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 = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000/' 'http://10.100.68.37:3000/' 'http://127.0.0.1:8000/' ) ROOT_URLCONF = 'backapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backapp.wsgi.application' DATABASES = { 'default': { 'ENGINE':'django.db.backends.postgresql_psycopg2', 'NAME': env('DATABASE_NAME'), 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASSWORD'), 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT') } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, … -
FOREIGN KEY constraint failed error in Django sqlite3
I am working on a script where I created a status model. User can create new status. I have checked the other answers for this but they all seemed code specific. This is models.py: class wall_status(models.Model): status = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="custom_student_status", default=1, on_delete=models.CASCADE) new_status = models.CharField(max_length=2000, default='') This is forms.py: class statusForm(forms.ModelForm): new_status = forms.CharField( widget=forms.Textarea) class Meta: model = wall_status fields = ('new_status', ) This is my views.py: def add_status(request): if request.method == "POST": form = statusForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('wall') else: form = statusForm() btn = 'Add' title = 'Interests' return render(request, 'user/profile_info_update.html', {'form': form, 'btn': btn, 'title': title}) This is template: {% block content %} <h2>Sign up</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">{{ btn }}</button> </form> {% endblock %} Now whats more confusing here is that I was able to add the status successfully 5 times and after that it started giving the error. Any ideas? Thanks -
Display different logic based on Primary Key in a DetailView Page
How can I display two different logics in a DetailView based on two different objects "PK i believe", I am a bit lost here. Let's say I have two modules in a Course DetailView page: "Web development" and "Machine Learning" (which are modules from The Python Course). Now, when the user clicks on "web development" to access it DetailView page, there is a different logic displayed, which is different than accessing Machine Learning DetailView page. The separation of logic is what I fail to create. class Course(models.Model): name = models.CharField(max_length=20) description = models.TextField(max_length=500) class Module(models.Model): name = models.CharField(max_length=20) courses = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='courses', null=True) Below is my code . VIEWS def course_detail(request, pk): module_taken = list(Course.objects.get(id=1).courses.all()) context = {'module_taken': module_taken} return render(request, 'courses/course-detail.html', context) def module_detail(request, module_id): module = get_object_or_404(Module, pk=module_id) context = {'module': module;} return render(request, 'courses/sexual-harassment/module-details.html', context) URL path('<int:pk>/module/', views.course_detail, name='course-detail'), path('module/<int:module_id>', views.module_detail, name='module-detail'), HTML COURSE-DETAIL <div class="text-center mt-5 ml-5"> {% for module in module_taken %} <ul> <li><a href='{% url "courses:module-detail" module.pk %}'>{{ module.name }}</li> </ul> {% endfor %} </div> MODULE-DETAIL {{ module }} Any help would be much appreciate. -
django tests milkman.deliver() - NameError: name 'basestring' is not defined
in django tests.... after use command: milkman.deliver() and run tests i have response with error: "NameError: name 'basestring' is not defined" This error appears only after using the milkman.deliver command. -
axios.post automatically splice url with my params
I want to implement an api with vue and axios in my front-end: methods:{ startSpider:function(event){ alert("spider is ready to run!"); let data = {'searchKey':this.searchKey, 'category':this.category, 'num':this.num}; axios.post("{% url 'main:getCommodityInfo'%}", data, {headers:{'X-CSRFToken': this.getCookie('csrftoken')}}) .then(response=>{ console.log(response.data) }) .catch(error=>{ console.log(error); alert("connection has error") }) }, When I call this function, I expect to get data from the back-end and stay at the inital url. It does receive data but the url quickly changed. After some exploration, I find the browser implement two request! First, POST, and next GET: Using 'searchKey':'switch', 'category':'electronic','num':60 as an example. and My browser url subsequently changes to Why it happens? I have just used POST not GET. The axios post seems to automatically splice inital url with the params. I have tried a lot of ways but failed. Even I have writed a small demo with the similiar structure like this to test, but the demo runs well! What happened? Help me please... -
How to establish a button function to my boolfield
I want to add functionality to my Publish button in HTML. I have made a method under my Post(model) and made a view for that button with a url. I don't know why my button function is not working. My Post Model : class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() created_on = models.DateTimeField(default=timezone.now) published = models.BooleanField(default=False) def publish(self): self.published=True self.save() def __str__(self): return self.title My Views.py : @login_required def publish_button(request,pk): post = get_object_or_404(Post,pk) post.publish() return redirect('blog_detail',pk=post.pk) My urls.py : urlpatterns = [ path('comment/<int:pk>/', comment_post, name='comment_form'), path('publish/',PublicList.as_view(),name='publish'), path('publish/<int:pk>/',publish_button,name='p_button'), path('', index, name='indexpage'), ] -
Question about comparison between model data
I am a beginner at python and django and i want to build a sort of mini-game that consists of pulling data from a database, and i wish to compare two instances of the same model and i wanted to know if i create another app, or a new view? models.py from django.db import models # Tank model created for simulation. class Tank(models.Model): name = models.TextField() barrel_caliber = models.DecimalField(decimal_places=2, max_digits=4) barrel_rate_of_fire = models.IntegerField() turret = models.BooleanField() turret_caliber = models.DecimalField( decimal_places=2, max_digits=4, blank=True) front_armor = models.BooleanField() side_armor = models.BooleanField() views.py from django.shortcuts import render from .models import Tank from django.db import models from django.http import HttpResponse from django.views import View # Create your views here. # The view for the created model Tank def tank_view(request): queryset = Tank.objects.all() context = { 'object': queryset } return render(request, "tankbattle.html", context) urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path, include from pages.views import index_view from tanks.views import tank_view urlpatterns = [ path('admin/', admin.site.urls), path('', index_view, name='homepage'), # URL for the homepage # URL for the tankbattle page path('tankbattle/', include('tanks.urls', namespace='tanks')), -
Get Django post parameter in runing task Celery
I need some help, I am trying to pass post parameter to a asynchronous task. I have to post data to /api and pass that data to the running task. If a user post test=10 I need to update meta={'current': 10. I want an external app to send post data to /api and that 'current': i change. I tried to pass testGlobal by different way without success. Thanks in advance BR urls.py path('api/', views.api, name='api'), views.py @csrf_exempt def api(request): testGlobal = request.POST.get("test", "") return HttpResponse(testGlobal+ ' --> OK') task.py @shared_task def create_random_user_accounts(total_user): for i in range(total_user): time.sleep(1) current_task.update_state(state='PROGRESS', meta={'current': i, 'total': total_user, 'percent': int((float(i) / total_user) * 100)}) return {'current': total_user, 'total': total_user, 'percent': 100} -
user login always return None
I am creating alogin view in which when user is not none go to someurl , then also go to another url , but it always goes to the other url though in cleaned data printed to terminal its already exist views.py def login_page(request): form = LoginForm(request.POST or None) context = { "form": form } next_get_url= request.GET.get('next') next_post_url= request.POST.get('next') redirect_path = next_get_url or next_post_url or None if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) print(user) if user is not None: login(request, user) if is_safe_url(redirect_path, request.get_host()): return(redirect(redirect_path)) else: return (redirect('/')) else: print ("Error") return render(request, "accounts/login.html",context) forms.py: class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) all tries and solutions found did not solve this any help! and thanks in advance -
Apache Webserver retries rest api call again within timeout (Angular - Django)
We have an angular app deployed on apache on 443(SSL) and a Django app which is also deployed on 443 (SSL) with different ServerName and ServerAlias setting. In a particular API call (api call from angular to django), the response time (processing time) is greater than 12 mins. So angular calls the api and after 3-4 minutes of wait time, apache calls the same api again and after 7-8 mins, apache returns ERR_EMPTY_RESPONSE to the client (apache) but on the backend (Django) processing still going on. This scenario is happening only for this particular api. Previously when angular is deployed on node itself (for local development) and only django is deployed on apache on port 8081, then this particular api is working fine. But when we deployed both the application (angular and django) on apache on port 443 (SSL support), then this particular api always keeps failing returning ERR_EMPTY_RESPONSE to the angular. So, my question is why apache retry the api call after 4-5 mins when django doesn't return a response and after 7-8 mins, it simply returns ERR_EMPTY_RESPONSE to the angular app. We have also used TimeOut setting to be 1800 seconds. Below is the required settings used in … -
how to connect MSSQL to Django
I am trying to connect MSSQL to my Django framework to be able to send some queries. However, I am not sure which setting I should implement in my settings.py file. It keeps giving me errors. My Django version is: 1.11.20. Python version is: 3.7.1. I have tried different engines with different drivers but I had no luck get it working. My current attempt is like this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DB_name', 'Host': 'my_host', 'port': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'unicode_results': True, }, } } When I try to apply migrates, I receive this output: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() … -
context must be a dict rather than Context
I have a sample HTML email I use with Django. I use templates to render dynamic content inside my HTML file, where I use the django.template Context object to pass in arguments print(type({'comapny_name': ProjectRequest.company_name})) #prints dict d = Context({'comapny_name': ProjectRequest.company_name}) ... html_message= htmly.render(d) I don't understand how this error occurs since I'm passing in a dictionary as an argument TypeError at /api/contactrequests/ context must be a dict rather than Context. -
Why are the images incorrectly saved when downloaded from a mobile phone using ajax?
Why are the images incorrectly saved when uploaded from a mobile phone using Ajax? I have 2 fields for uploading images. When I click on submit, they go to Django via Ajax. Then they are processed and stored in database. The problem is that my code only works for uploading images from a computer. And when uploading from a mobile phone (iphone), an entry is simply created in the database, there are links to these photos, but when I try to open them - I get an error 403. When I try to manually change these photos from the admin page - I get the same error - 403. models.py from djlime.utils import get_file_path class RequestUser(models.Model): main_photo = models.ImageField(_('main_photo'), upload_to=get_file_path) profile_photo = models.ImageField(_('profile_photo'), upload_to=get_file_path) @property def upload_dir(self): return 'accounts/request_user/images' forms.py class IdentificationForm(forms.ModelForm): class Meta: model = RequestUser fields = ('main_photo', 'profile_photo', ) widget= { 'main_photo': forms.FileInput( attrs={ 'style': 'display: none', } ), 'profile_photo': forms.FileInput( attrs={ 'style': 'display: none', } ) } def __init__(self, *args, **kwargs): super(IdentificationForm, self).__init__(*args, **kwargs) self.fields['main_photo'].widget.attrs = {'class':'file_dnl'} self.fields['profile_photo'].widget.attrs = {'class':'file_dnl'} def clean_image(self): cd_image = self.cleaned_data['main_photo'] return cd_image def clean_image2(self): cd_image = self.cleaned_data['profile_photo'] return cd_image views.py def identification_view(request): if request.method == 'POST': form = IdentificationForm(request.POST, request.FILES) if …