Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override the javascript default editable bootstap values
I am stuck at overriding the default editable bootstrap values in Django framework javascript html page In my webpage, it coded as below $.fn.editable.defaults.url = "{% url 'page1' model.PATH %}"; Now my requirement is, When I click on a button, it check the views.py(page1, which is default URL) and pass the context through 'return HttpResponse' to html page that "True" or "False" based the value, if fasle, it should go page2, it never goes to page2 url,its entered to the function conflict_warn() but not inside and eventually it failed with the "Uncaught TypeError:e.getAttribute is not a function", I tried number of way, but all are vain. $(this).editable({ value: "", display: false, success:function(response, newValue){ if (response.hasOwnProperty("State"))){ conflict_warn(response, newValue)//if State value True,should go to other func } else{ window.location.href = "{% url 'path1' 'path2'%}" + response; } }, error:function(response, newValue){$(this).editable("destroy");} }); $(this).editable("submit"); function conflict_warn(response, newValue){ $(this).editable({ value:"" display: false success: function(response.newvalue){ window.location.href = "{% url 'path1' 'path2'%}" + response; } }); $(this).editable("setValue","{% url:'page1' model.PATH %}"); $(this).editable("submit"); } -
'User' Object has no attribute 'method'
I am just playing around with the Django login and logout phase. I have a login page, if the user gets it with 'GET', he gets the form, if he submits the form, it gets submitted to the same view.login function. The problem is that when i try to use ' if request.method=='POST'. I get an error that 'User has not attribute method', i don't understand, why does the 'User' object gets passed instead of the request object? Here's the code of views.py: from django.shortcuts import render from django.http import HttpResponse, Http404, HttpResponseRedirect from .models import Flight,Passenger from django.urls import reverse from django.contrib.auth import authenticate,login, logout from django.contrib.auth.models import User def index(request): if not request.user.is_authenticated: return render(request,"login.html") context={ "flights":Flight.objects.all() } return render(request,"index.html",context) def flight(request,flight_id): flight= Flight.objects.get(pk=flight_id) passengers = flight.passengers.all() non_passengers = Passenger.objects.exclude(flight=flight).all() context={ "flight":flight, "passengers":passengers, "non_passengers":non_passengers } return render(request,"flight.html",context) def book(request,flight_id): passenger_id = int(request.POST["passenger"]) flight = Flight.objects.get(pk=flight_id) passenger = Passenger.objects.get(pk=passenger_id) passenger.flight.add(flight) return HttpResponseRedirect(reverse("flight",args=(flight_id,))) def login(request): print("\n In LOGIN \n") if request.method=='POST': print("\n In POST Request \n") username = request.POST["name"] password = request.POST["password"] user = authenticate(request,username=username,password=password) if user is not None: login(user) return HttpResponseRedirect(reverse("index")) else: return render(request,"login.html") Here's the login page: <html> <head> <meta charset="utf-8"> </head> <body> <form action="{% url 'login' … -
My function Register catches more mistakes, in Django framework
I possess a problem, than i not resolve since 48 hours. I explain to you : In my function Register, I use FormRegistration of Django and ProfilForm who is my personal form, but it's impossible at displaying the differently errors (username identique, if "password1" is not equal at "password2"..), i don't know where is problem. This is my register function in views.py : def register(request): if request.method == 'POST': form = UserCreate(request.POST) form2 = ProfilForm(request.POST) if form.is_valid() and form2.is_valid(): user = form.save() form2 = form2.save(commit=False) form2.user = user form2.skill = form2.cleaned_data.get('skill') form2.board = form2.cleaned_data.get('board') form2.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/accueil') else: form = UserCreate() form2 = ProfilForm() return render(request, 'registration/register.html', {'form2': form2}, {'form': form}) This is my template register.html for displaying errors : https://paste.ee/p/lAh3q Thank you very much to the one who solves my problem -
Deploying Django + Angular to EB without using django templates in production
I've been reading a million answers in this subject but I can't find a solution that works. I have a Django DRF backend that is used for all the API calls and a separate Angular(5) front-end project. The Django backend is deployed to Elastic Beanstalk and is working properly. All I want to do is to deploy the angular frontend without needing to add template tags to the htmls. Better yet I don't want to change anything in the built dist Angular folder. I see there are several approaches - As far as I can understand the best one would be to serve the index.html through a regular Django url and then expose all the dist folder (the static files). I achieved the first part using: urlpatterns += [ url(r'^$', TemplateView.as_view(template_name='index.html')), url(r'^(?P<path>.*)/$', TemplateView.as_view(template_name='index.html')), ] and defining the dist folder as a template folder in settings.py: ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'client/dist') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ANGULAR_APP_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.i18n', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Currently, I define an s3 bucket to hold all static files and 'collectstatic' works and puts all the static files in the right location, including the files in … -
Updating a value in serialzier after accessing .data in Django Rest Framework
I have a serializer for my Post class which has a image and a link attribute. media is an FileField and link is a URLField which is a url to somewhere else I share my post (in another website.) I want to: Submit my post data (text, and the image) Accessing the url of submitted file to use in sharing it in another place. Updating the link value after I found it. This is what I tried: post = PostCreateSerializer(data=request.data, context={'request': request}) post.is_valid(raise_excpetions=True) post.save() media_url = post.data.get('media') link = find_link_value() post.link = link post.save() This raises an exception. says: You cannot call `.save()` after accessing `serializer.data`.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. The problem is when I use post.validated_data.get('media') instead of .data, it doesn't give me the url. It gives me an InMemoryUploadedFile object, that of course, doesn't have any path and url. I thought I could use name attribute of InMemoryUploadedFile object to create the url (the file is actually saved in disk and I wonder why this is InMemory!) but when the name is duplicate, the real name of file in disk and url differs from it's original name (for … -
'my_app' module not found error Django - Executing a script which uses my_app models
Currently i have a problem. I'm trying to execute an script that uses my application models. But i get this error when i try to execute it : Traceback (most recent call last): File "my_web_app/Scripts/CreateDBTAFs.py", line 2, in <module> standalone.run('taf_analytics.settings') File "/my_app/venv/lib/python3.6/site-packages/standalone.py", line 27, in run django.setup() File "/taf_analytics/venv/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/my_app/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/my_app/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/my_app/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/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 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'my_app' my_app -venv (My virtual environment) -manage.py -my_web_app -Scripts -CreateDBTAFs.py (This is the script i'm trying to execute) And here, my script imports : import sys sys.path.insert(0, '/my_app/') import os, sys PWD = os.getenv('PWD') os.chdir(PWD) sys.path.insert(0, os.getenv('PWD')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "local_settings.py") import django django.setup() #import standalone #standalone.run('my_app.settings') from my_web_app.models import MyModel from django.contrib.auth.models import User from nltk import word_tokenize … -
AttributeError IN IMAGEUPLOAD IN DJANGO_REST_FRAMEWORK?
iam trying to upload image in rest_framework .i cant fix this error because im new rest_framework,Can anyone please solve this error . My all models.py,serializers.py,views.py and urls.py are shown below: models.py def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension) class UploadedImage(models.Model): image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename) name = models.CharField(max_length=120) serializers.py class QuestionSerializer(serializers.ModelSerializer): image = serializers.ImageField() name = serializers.CharField(max_length=120) class Meta: model = UploadedImage fields = ('image','name') views.py class UploadedImagesViewSet(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = QuestionSerializer def create(self,request): serializer1 = self.get_serializer(data={**request.data,**request.FILES}) serializer1.is_valid() data = serializer1.data print(data) img,iss = UploadedImage.objects.get_or_create(name=data['name'],defaults={'image':data['image']}) return Response("UploadedImage") urls.py from django.urls import path,include from rest_framework import routers from app1 import views router = routers.DefaultRouter() router.register(r'',views.UploadedImagesViewSet) urlpatterns = [ path('',include(router.urls)), ] traceback: Exception Value: 'list' object has no attribute Environment: Request Method: POST Request URL: http://127.0.0.1:8000/upload/ Django Version: 2.0.7 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app1', 'practice'] Installed Middleware: ['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'] Traceback: File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in get_or_create 487. return self.get(**lookup), False File "/home/dinesh/.local/lib/python3.6/site-packages/django/db/models/query.py" in get 403. self.model._meta.object_name During handling of the above exception (UploadedImage matching query does not exist.), another exception occurred: File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/dinesh/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, … -
Django Admin, All the contents of my table are not being displayed & Inline Issue
Attached below is the models.py I used for my project, I've attached the photos of the issue as well. Issue 1 For some reason, all the contents of the tables are not being displayed. In the first table, first content goes missing. In the Second table, First and the second contents go missing Issue 2 The Inline function doesn't work. I tried going through the documentation and several youtube videos to find out how to handle the situation but it didn't help much. Issue 3 For the bug table, When I select the project name, How do I ensure that only the people I added to that project table are allowed to be selected? Issue 4 Is there a way to extract the email ID from the Users page and and when I choose the name of the user in the Project page, the email Id will be automatically filled it? Same way, In the issues page, when I choose the user, the email Id will be auto entered. MODELS.py from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models from django.core.mail import EmailMessage from django.contrib import admin # Create your models here. … -
I want to add search box for latitude,longitude in google maps API
If I want to add search box where i can search by typing latitude,longitude in google maps api what are the changes I need to make in this coding below? Please let me know. Thank you $(document).ready(function() { init(); }); function init() { var mapDiv = document.getElementById('map-canvas'); $('#map_position')[0].value = '23.777176,90.399452'; $('#map_distance')[0].value = '10.000'; var map = new google.maps.Map(mapDiv, { center: new google.maps.LatLng(23.777176, 90.399452), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }); var distanceWidget = new DistanceWidget(map); google.maps.event.addListener(distanceWidget, 'distance_changed', function () { displayInfo(distanceWidget); }); google.maps.event.addListener(distanceWidget, 'position_changed', function () { displayInfo(distanceWidget); }); } function DistanceWidget(map) { this.set('map', map); this.set('position', map.getCenter()); var marker = new google.maps.Marker({ position: map.getCenter(), icon: { path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW, scale: 4 }, draggable: true, title: 'SET me anywhere!', map: map }); marker.bindTo('map', this); marker.bindTo('position', this); var radiusWidget = new RadiusWidget(); radiusWidget.bindTo('map', this); radiusWidget.bindTo('center', this, 'position'); this.bindTo('distance', radiusWidget); this.bindTo('bounds', radiusWidget); } DistanceWidget.prototype = new google.maps.MVCObject(); function RadiusWidget() { var circle = new google.maps.Circle({ strokeWeight: 4 }); this.set('distance', 10); this.bindTo('bounds', circle); circle.bindTo('center', this); circle.bindTo('map', this); circle.bindTo('radius', this); this.addSizer_(); } RadiusWidget.prototype = new google.maps.MVCObject(); RadiusWidget.prototype.distance_changed = function () { this.set('radius', this.get('distance') * 1000); }; RadiusWidget.prototype.addSizer_ = function () { var sizer = new google.maps.Marker({ draggable: true, icon: { url:"https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle_blue.png", size: new google.maps.Size(10, 10), anchor: new google.maps.Point(4, … -
ValueError at /profile/:The 'image' attribute has no file associated with it
When a user registers for my app.I receive this error when he reaches the profile page 'ValueError at /profile/:The 'image' attribute has no file associated with it.' This is my profile model: class Profile(models.Model): Full_Name = models.CharField(max_length=32,blank=True) Name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) E_mail = models.EmailField(max_length=70,blank=True) Qualification = models.CharField(max_length=32,blank=True) Permanant_Address = models.TextField(blank=True) image = models.ImageField(upload_to='user_images', null=True, blank=True) def __str__(self): return str(self.Name) def get_absolute_url(self): return reverse("userprofile:profiledetail") @property def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image_url This is my form: class profileform(forms.ModelForm)" class Meta: model = Profile fields = ('Full_Name','Name', 'E_mail','Qualification','Permanant_Address','image') This is my view: from django.shortcuts import render from django.views.generic import DetailView,UpdateView from django.contrib.auth.mixins import LoginRequiredMixin from userprofile.models import Profile from userprofile.forms import profileform # Create your views here. class profiledetailview(LoginRequiredMixin,DetailView): context_object_name = 'profile_details' model = Profile template_name = 'userprofile/profile.html' def get_object(self): return self.request.user.profile class profileupdateview(LoginRequiredMixin,UpdateView): model = Profile form_class = profileform template_name = 'userprofile/profile_form.html' def get_object(self): return self.request.user.profile And in my template I have done something like this: <img class="profile-user-img img-responsive img-circle" src="{{ profile_details.image.url|default_if_none:'#' }}/" alt="User profile picture"> I'm been reading the documentation for Built-in template tags and filters I think a solution here is to use and I think I can't seem to use template tag properly. How can I configure … -
Error in "from . import views" in urls.py while making migrations
urls.py from django.conf.urls import url,include from django.contrib import admin import createArrangement from . import views urlpatterns = [ url(r'^$', views.index,name='index'), url(r'file2/$', views.index2, name='index2') ] I also tried writing from .views import index,index2 with url(r'^$', index,name='index') Also tried writing the "from Appname" instead of "from .", but nothing worked. Error i got is Traceback (most recent call last): File "C:\Users\DELL\Desktop\seatAllocatorWeb\seatAllocatorWeb\urls.py", line 22, in <module> url(r'^createArrangement/', include('createArrangement.urls')) File "C:\Python34\lib\site-packages\django\conf\urls\__init__.py", line 52, in include urlconf_module = import_module(urlconf_module) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed C:\Users\DELL\Desktop\seatAllocatorWeb\createArrangement\urls.py", line 4, in <module> from . import views -
How to know session is getting saved on database or cache?
I tried to go through documentation,its very technical and im getting confused that im using database or cache to save sessions! im using request.session and 'django.contrib.sessions.middleware.SessionMiddleware' in middleware and in 'django.contrib.sessions' in installed apps. If i am saving session datas in DB then how to do it in cache way? -
PostgreSQL connection failed in Django
im using PostgreSQL database in my code. im want upgrade my PostgresSQl so install new version postgres then reset the postgresSQL service after that postgres start currectly and i can access my db in admin panel of django but when i try access db object in my code i face this error Exception in thread Thread-5: Traceback (most recent call last): File "opt/%/api/.env/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. -
Django urls.py passing wrong GET value
I have a url in my app path('owner/season/<season_name>', LV.owner_season, name='league-owner-season') where I want to load a page based on the season that is passed. The url in my browser is "mywebsite.com/owner/season/fall2018". My views file looks like def owner_season(request, season_name): data = check_if_owner(request) print(str(request)) if not data['valid_owner']: redirect('home') print(season_name) #other code doing classic django stuff What gets printed is: <WSGIRequest: GET '/owner/season/favicon.ico'> favicon.ico What would be causing the value of the GET value to change from urls to views? From what I have read the value should be fall2018 but I have no idea where favicon.ico is coming from. -
How to retrieve models data having nested relationship using serializers in Django Rest Framework?
i am explaining in detail about a problem that i am facing and seek help from this community. I followed this Django Rest Framework documentation but couldn't get the desired result for multi-level nesting Consider the relationship of models as explained : A user can have multiple Workspaces A workspace can have multiple Projects A Project can have multiple ProjectLists ProjectList can have multiple Tasks Tasks can have multiple updates User | Workspaces (ForeignKey="User") |____Projects (ForeignKey="Workspaces") |____TodoList (ForeignKey="Projects") |____Tasks (ForeignKey="TodoList") |____Updates (ForeignKey="Tasks") So what i want is to get all the data that a User has in a nested json format like this: [ { "workspace_id": "99a961ec-b89e-11e8-96f8-529269fb1459", "workspace_owner": "1", "workspace_title": "Indie Dev Works", "projects": [ { "project_id":"db09cfa0-b89e-11e8-96f8-529269fb1459", "todo_list":[ { "list_id": "9dc64e4c-b89f-11e8-96f8-529269fb1459", "list_name":"Project list -1", "tasks":[ "task_name":"Create HTML docs", "updates":[ { "id":"d5eb660e-b89f-11e8-96f8-529269fb1459", "text":"Creating using PUG" }, { ..... ..... ..... ..... }, ] ] } ] }, { "project_id":".........", .... .... .... .. .. . }, ] } ] So when my User logs in by entering email, i am trying to get all the Workspaces instance and then pass it to the serializers in my views as mentioned below: views.py class InitializeHome(viewsets.ViewSet): def list(self,request): user_email = request.user.email user_instance = utils.getUserInstance(user_email) … -
__month and __year creating query with Between clause from wrong year, with timezone activated
I have a model with createdon datetime field. My env is timezone sensitive. NOw I want to get total/aggregated value by date of current month and year. (ie.g. each date of today's month year totalled) k=model.objects.extra({'created_on':"date(createdon)"}).filter(createdon__month=date.today().month,createdon__year=date.today().year).values('created_on').annotate(total_created=Count('id')).order_by('created_on') I have records but it returns empty result set. And the query that was actually executed looks like this: SELECT (date(createdon)) AS 'created_on', COUNT(app_model.id) AS total_created FROM app_model WHERE app_model.createdon BETWEEN 2017-12-31 22:00:00 AND 2018-12-31 21:59:59 AND EXTRACT(MONTH FROM CONVERT_TZ('app_model.createdon','UTC', Europe/Istanbul)=9 GROUP BY date(createdon)) Timezone is really vital to the app so it won't be turned off. But is there away to fix te query so I get the members who are actually registered in Sep, 2018? -
How to connect postgis to django in docker
Hi I would like to know how to connect POSTGIS to django using Docker. I am having an error could not open extension control file "/usr/share/postgresql/10/extension/postgis.control": No such file or directory output root@localhost:~/try-geodjango# docker-compose run web python manage.py migrate Starting try-geodjango_db_1 ... done /usr/local/lib/python3.5/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) psycopg2.OperationalError: could not open extension control file "/usr/share/postgresql/10/extension/postgis.control": No such file or directory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 81, in handle connection.prepare_database() File "/usr/local/lib/python3.5/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 25, in prepare_database cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") File "/usr/local/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, … -
Django; ValueError: I/O operation on closed file. when trying to use ManifestFilesMixin
I'm trying to use ManifestFilesMixin so the cache for static files can be boosted. But ValueError: I/O operation on closed file. This error happened when I did python manage.py collectstatic here is my storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings from django.contrib.staticfiles.storage import ManifestFilesMixin class StaticStorage(ManifestFilesMixin, S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION file_overwrite = False How can I fix this error? -
Django SQLite application Error after some time sleep
I have a strange problem with Django. I have developed an application with Django, that is a database of papers. i used SQLite. the db has 8 field including title, authors and ... and has about 60000 records. Every thing is OK, but the problem is when i don't search in db through Django interface like a night, in the morning when i search something in db through Django, i get Error page is not working, while after some refreshing page and passing some mins it works greatly!!! i.e with every search results is shown quickly. Any idea. -
Authentication credentials were not provided with Django Rest Framework JWT
I am having trouble implementing token authentication with JWT in the Django rest framework with a Typscript frontend. I'm getting: {detail: "Authentication credentials were not provided."} with my API call view Typescript, which is: readonly BASE_URL = 'http://127.0.0.1:8000/' api_url = this.BASE_URL + 'items/' auth_url = this.BASE_URL + "api-token-auth/" getItemsService(token) { const headers = new HttpHeaders() headers.append('Content-Type', 'application/json') headers.append('Authentication', 'JWT ' + token.token) return this.http.get(this.api_url, {headers: headers}) } Logging in works fine. It's when I try to load the items that I have issues. Here's my Django code: views.py from rest_framework import generics from .models import Item from .serializers import ItemSerializer class ItemList(generics.ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer class ItemDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer items/urls.py from django.urls import path from .views import ItemList, ItemDetail urlpatterns = [ path('', ItemList.as_view()), path('<int:pk>/', ItemDetail.as_view()), ] project/urls.py from django.contrib import admin from django.urls import include, path from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ path('items/', include('groceries.urls')), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api-token-auth/', obtain_jwt_token), ] settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } I'm thought the issue would have to be with Django, but I am able to get what I expect with curl -H "Authorization: JWT <token>" http://localhost:8000/items/ If … -
use django-filter with object url_params
I have successfully implemented django-filter on my Django-rest-framework server. I have the following filter_class filters.py class EmploymentFilter(filters.FilterSet): class Meta: model = EmploymentCheck fields = ['instructions',] views.py class EmploymentCheckViewSet(viewsets.ModelViewSet): pagination_class = ContentRangeHeaderPagination serializer_class = EmploymentCheckSerializer queryset = EmploymentCheck.objects.all() filter_class = EmploymentFilter the filter works when i send a get request as /employmentcheck/?instructions=2 However, I have implemented a front end with react-admin. My front-end, sends a request with the url_params as objects /employmentcheck/?filter={"instruction_id":"2"}&range=[0,24]&sort=["id","DESC"]/ Notice how the URL specifies a filter object, in which, it defines the parameters to filter against. My question is, how and where can I filter my model without changing the URL pattern from my client? Any other advise that spans the scope of my question is equally welcomed Models.py class EmploymentCheck(models.Model): instructions = models.ForeignKey(Instruction, on_delete=models.CASCADE, null=True) -
Difference between Django serializers
I am now learning django and I just heard about drf. I was wondering what was the difference between the django.core serializers and the rest_framework serializers. Also, is drf doing anything useful else than serializers ? Yes, I know drf is for apis -
Django deploying on MySQL gives #1071 error “Specified key was too long”
Please dont mark it as dupliacte .I have been searching for three days on community I am using alibaba cloud services for hosting and I got this error django.db.utils.operationalerror: (1071, 'specified key was too long; max key length is 767 bytes') when i run python3 manage.py migrate my problem is similar as mentioned here Django deploying on MySQL gives #1071 error "Specified key was too long" my model.py file is ` from django.db import models class SendRequest(models.Model): rid=models.AutoField(primary_key=True) uname=models.CharField(max_length=256) problemcode=models.CharField(max_length=256) languageused=models.CharField(max_length=50) question=models.TextField() description=models.TextField() codesnapshot=models.TextField() status=models.BooleanField(default=False) date = models.DateTimeField(default=datetime.now,null=False) class ReceiveRequest(models.Model): rrid=models.ForeignKey(SendRequest,on_delete=models.CASCADE) uname=models.CharField(max_length=256) class Meta:`enter code here` unique_together = (("rrid", "uname"),)` When i use SendRequest Model i didnt get any error but when i add ReceiveRequest table i got the above error **my settings.py is ** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME' : 'dbdiv', 'USER' : '********', 'PASSWORD':'********', 'HOST' : 'rm-6gjg9lt559w00uv6yeo.mysql.ap-south-1.rds.aliyuncs.com', 'PORT' : '3306', 'OPTIONS': { 'init_command':'SET character_set_connection=utf8,collation_connection=utf8_unicode_ci', }, } } I tried all possible ways by dropping and adding database again and i created database with CREATE DATABASE dbdiv CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; Please help me . my problem is similar to Django deploying on MySQL gives #1071 error "Specified key was too long" mention answer -
form is not shown despite being nested to company model
The use case of the app I am trying to develop is about registering the company who are interested for franchise. I have taken this concept from franchisebazar for learning purpose. There i saw company info, brand info and business model for registering the company. That is why I created the following model. I want the create and update view now so from the frontend i can hit the api request to create and update. I designed the following serializer and APIView. However, when i try to test in the browser, if the coded way is working or not, i could not see the form for brand and business model despite they are nested in company. Thus, I want to know if i have to extend it more by creating a view for brand and business model separately or i did something wrong in my code. class Company(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=150, blank=False, null=False) phone_number = models.CharField(max_length=15, blank=False, null=False) class Brand(models.Model): company = models.ForeignKey(Company, related_name='company_brand', on_delete=models.CASCADE) name = models.CharField(max_length=150, blank=False, null=False) website = models.URLField() description = models.TextField(blank=False) class BusinessModel(models.Model): company = models.ForeignKey(Company, related_name='company_business_model', on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, related_name='industry', on_delete=models.SET_NULL) segments = models.ForeignKey(Segment, on_delete=models.SET_NULL, null=True) total_investment … -
Correct way of using Django update_or_create
this is my model class services(models.Model): Invoice_number = models.CharField(max_length=100) name = models.CharField(max_length=100) contact = models.IntegerField() email = models.EmailField() service = models.CharField(max_length=30) This is the query I am trying to update or create an instance in the above model services.objects.update_or_create(Invoice_number = self.a, name=self.b, contact=self.c, email =self.d, service =self.d ) So if an Invoice_number exists the instance should get updated if not then create a new instance.