Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
not working update method in rest API framework
I want to be able to edit registered User profile by using UpdateModelMixin class. The forms to edit is existed but when we want to PUT the new information , the new one is not applied and the pervious info is displayed. views.py: c lass ProfessorDetailAPIView(DestroyModelMixin, UpdateModelMixin, RetrieveAPIView): queryset = Professor.objects.all() serializer_class = ProfessorDetailSerializers def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) serializers.py: class ProfessorDetailSerializers(serializers.ModelSerializer): user = CustomUserSerializer() professor_no = SerializerMethodField() class Meta: model = Student fields = ( 'user', 'professor_no', ) def get_professor_no(self, obj): return str(obj.professor_no) There is not any changes applied on information -
how to use forms in APIView to send post request in django
i'm making an OTP app using class based views. the bottom is the class for generating and sending OTP to a phone number. the template works good and when i press the submit button in my html form it sends a post request and it returns response: 'phone number is not given in post req' so the template and API works! but the {{form}} in the html template doesn't work so i can't send the OTP to the number submitted in the form. so what am i doing wrong? forms.py exists in my project with 1 field class ValidatePhoneSendOTP(APIView,TemplateView): template_name = 'accs/reg.html' def post(self, request, *args, **kwargs): form = PhoneRegForm(request.POST) phone_number = request.data.get('phone') if phone_number: phone = str(phone_number) user = User.objects.filter(phone_number__iexact = phone) if user.exists(): return Response({ 'status': False, 'detail': 'user exists' }) . . . . . . . . else: return Response({ 'status' : False, 'detail' : 'phone number is not given in post req' }) i tried to pass FormView in the class after the APIView,TemplateView but i couldn't get that to work. -
Can't import django even though it says requi
I had some django projects in a directory and they were spinning up fine with runserver. The projects were all very similar, so I created a subdirectory and moved the django projects inside this subdirectory. Now when I try runserver I get the following error. virtualenv is activated and pip says django is already installed, but for some reason it can't import django. Why am I getting this error now? jpanknin:spinup2/ (master) $ source virtualenv/bin/activate [22:56:28] (virtualenv) jpanknin:spinup2/ (master) $ pip install "django<1.12" [22:56:37] Requirement already satisfied: django<1.12 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (1.11.22) Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from django<1.12) (2018.5) (virtualenv) jpanknin:spinup2/ (master) $ python manage.py runserver [22:56:53] Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Nginx upstream prematurely closed connection, but files still being written
I have a Django and Nginx server running in docker containers. Here is the docker compose file. This is the Dockerfile for the django app: FROM python:3.7 RUN mkdir -p /opt/services/djangoapp/src WORKDIR /opt/services/djangoapp/src RUN pip install gunicorn COPY . /opt/services/djangoapp/src RUN pip install -r facefind/requirements.txt EXPOSE 8000 CMD ["gunicorn", "--chdir", "facefind", "--bind", ":8000", "FaceFind.wsgi:application"] When uploading files, I get errors like this: 2019/07/07 02:07:25 [error] 6#6: *4 upstream prematurely closed connection while reading response header from upstream, client: [ip], server: localhost, request: "POST /addface/4 HTTP/1.1", upstream: "http://[ip]:8000/addface/4", host: "example.com", referrer: "https://example.com/addface/4" [ip] - - [07/Jul/2019:02:07:25 +0000] "POST /addface/4 HTTP/1.1" 502 174 "https://example.com/addface/4" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0" "99.252.117.58" 2019/07/07 02:08:01 [warn] 6#6: *7 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000003, client: [ip], server: localhost, request: "POST /addface/4 HTTP/1.1", host: "example.com", referrer: "example.com" [ip] - - [07/Jul/2019:02:08:01 +0000] "GET /media/flower.jpeg HTTP/1.1" 200 20775 "-" "OxfordCloudService/1.0" "40.85.225.30" 2019/07/07 02:08:01 [error] 6#6: *7 upstream prematurely closed connection while reading response header from upstream, client: [ip], server: localhost, request: "POST /addface/4 HTTP/1.1", upstream: "http://[ip]:8000/addface/4", host: "example.com", referrer: "https://example.com/addface/4" [ip] - - [07/Jul/2019:02:08:01 +0000] "POST /addface/4 HTTP/1.1" 502 174 "https://example.com/addface/4" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0" … -
Cant create user with django-knox
I am having issues creating a user serializer.py from rest_framework import serializers from django.contrib.auth.models import User from .models import Invoice class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = Userfields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], None, validated_data['password']) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" This is the error message I am getting. tuple' object has no attribute '_meta' -
How can I count the number of SQL queries needed to render a Django admin page?
Part of my django admin site that uses a lot of Inlines is running slowly and based on this question I think that it might have to do with the number of SQL queries it generates. I'd like to count the number of SQL queries so I can test some changes. I know how to do this on a custom-written view but I can't figure out how to do it for a standard admin view. Here's how I would test my own view. The view is called weight_plot and the app is called runner. from django.test.client import RequestFactory from django.conf import settings settings.DEBUG = True from django.db import connection import runner.views myview = runner.views.weight_plot request = factory.get('/weights') response = myview(request) n_queries = len(connection.queries) This works, and now I'd like to see how many queries are needed to load the page at https://example.com/admin/runner/MODEL_NAME/add/. But I can't figure out what view to use for this instead of myview above. -
How to store media file uploaded from Django Admin panel on the AWS S3?
Thanks for taking the time to read my question! I hope I was clear enough, in case I wasn't please let me know, I will try to provide more content. I successfully configured the settings.py to store all the static on the S3 after running the "manage.py collectstatic" command. I have tried to follow different guides on how to achieve the same thing for the media files. All of them focus on uploading files from a website form, which isn't my case. What I ideally want is to have my S3 bucket have 2 folders 'static' and 'media'. Where media folder will have subfolder based on which of my Django models I have update with an image. So one file might look something like this on AWS S3: "media/myprojects/personal_website.jpg" and then of course display that image on the website. So let me show you what I have now. models.py (For the my_projects App) from django.db import models class Project(models.Model): title = models.CharField(max_length=200) cover = models.ImageField(upload_to='project-images/') def __str__(self): return self.title settigns.py ... AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' … -
OSError when opening .heic image with PIL
My django app allows users to upload images to their account. I'm using jquery file upload to process asynchronously. In my upload view, I'm using PIL to do some basic image manipulations (resize, rotate if necessary). Relevant portion of view for image upload below: def group_photo_upload_desktop(request): if request.method == 'POST': try: group_id = request.POST.get('group_id') uploaded_image = request.FILES.get("image", default=None) image = Image.open(uploaded_image) image = autorotate_image(image) image = resize_image(image) Occasionally, I have started to see the code fail when PIL attempts to open the image. The failing image is always .heic format and as of now, is only occurring with one user (only have 7 users so not large sample set) who is uploading the image from an iPhone (not sure of exact version). What is really confusing me is that the vast majority of .heic images upload just fine for the user and will often upload successfully after several hour delay. A traceback of a recent error is below. File "/home/EscapeKit/socialwaiver/core/views_group_detail_desktop.py", line 308, in group_photo_upload_desktop image = Image.open(uploaded_image) File "/home/EscapeKit/.virtualenvs/venv/lib/python3.5/site-packages/PIL/Image.py", line 2622, in open % (filename if filename else fp)) OSError: cannot identify image file <TemporaryUploadedFile: 20190706_154803.heic (application/octet-stream)> And request.FILES <MultiValueDict: {'image': [<TemporaryUploadedFile: 20190706_154803.heic (application/octet-stream)>]}> I've had the user send me … -
How could a field in another table in a datatable of angular by means of a foreign key?
I have data table in angular and one of the fields or column of that table is a foreign key, I mean an ID (computer_id), but I want to show in place of that ID a field of another table, that is, I have in the table records (table that I am showing) a team id as a foreign key and I want to show the name of that team, which is a column of the table of equipment (table of which I have its id as a foreign key in the table of records). I have no idea how to do it in angular, if you gave me an idea they would help me a lot. PD: to bring me the data from the database, I am consuming the api through http queries and using django rest framework, my doubt would be if I have to bring me by query http get the two tables but then as I do relation for the table records. As a database manager I am using MYSQL -
Modifing fields form order of CustomUser model
I created a customUser model so that the default User is overwritten. This is my customUser model: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser from crispy_forms.helper import FormHelper class CustomUserCreationForm(UserCreationForm): helper = FormHelper() class Meta(UserCreationForm): model = CustomUser fields = ('first_name', 'username', 'email', 'last_name', 'organization', 'location', 'postcode', 'phone', 'agree_conditions') class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm): model = CustomUser fields = ('username', 'email', 'first_name', 'last_name','organization', 'location', 'postcode', 'phone', 'agree_conditions') Everything works perfectly however I am not able to change the order of the "User default" fields. I know how to re-order the form fields, I can simply change the order in the fields = (a, b, c). For example if I want "c" to appear before "a" and "b" in the form, I can do: fields = (c, a, b). HOWVER I want to move up the password and password confirmation but I do not know how to do so because I do know know their name in the User default model. Ideally I want this: fields = ('username', 'email', 'PASSWORD_WHICH_I_DONT_KNOW_THE_NAME', 'CONFIRMPASSWORD_WHICH_I_DONT_KNOW_THE_NAME' 'first_name', 'last_name','organization', 'location', 'postcode', 'phone', 'agree_conditions') -
Adding extra-fields signup User without using {{ form.as_p }} but bootstrap
I am new to Django, I am trying to add extrafields when the user signup. The fields I am adding are: 'first_name', 'last_name', 'organization', 'location', 'postcode', 'phone' to the already existing 'username' and 'password'. My base app is called: mysite This is what I am doing: 1) Create an app users (It is my understanding this app is a special app inside Django and contains some default values) python manage.py startapp users 2) Add 'users.apps.UsersConfig' in my mysite/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', ] 3) Telling Django in mysite/settings.py NOT to look at the deafault User but to my new User model. AUTH_USER_MODEL = 'users.CustomUser' 4) Add in users/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): first_name = models.CharField(max_length=100, default='') last_name = models.CharField(max_length=100, default='') organization = models.CharField(max_length=100, default='') location = models.CharField(max_length=100, default='') postcode = models.CharField(max_length=100, default='') phone = models.CharField(max_length=100, default='') def __str__(self): return self.email 5) Create touch users/forms.py With inside: (Here I am not sure why we need there 2 classes and what their functionality is) from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): … -
How can I grab articles with the same tag, so within a template I can display those articles?
I'm new to Django, so thanks for any help. I have an Article model, and I would like to display related/similar articles by assigning tags to each article. I've tried making a function/filter in my views.py that inherits from self (that particular article) and filters out the articles with the same tag, but with no success. from django.db import models class Article(models.Model): title = models.CharField(max_length=200, blank=True) thumbnail = models.ImageField(max_length=200, blank=True) tag = models.CharField(max_length=200, blank=True) from .models import Article class ArticleView(DetailView): template_name = "article/article.html" model = Article def related_articles(self): tagged = Article.objects.filter(tag=self.tag) return tagged {% if articles.objects.all %} {% for article in article.objects.all|related_articles %} <div> <img src="{{ article.thumbnail.url }}"> <span>{{ article.title }}</span> </div> {% endfor %} {% endif %} So, whenever I try to use this filter I get no results. -
When a scroll event occurs using animate I want to position scroll up a bit
When a scroll event occurs using animate I want to position scroll up a bit The current scrolltop code looks like this: $ (". go_btn"). click (function () { const number = $ (". go_input"). val (); if (number == 1) { $ ('html, body'). animate ({ 'scrollTop': $ ("# index_first"). offset (). bottom }); } $ ('html, body'). animate ({ 'scrollTop': $ ("# index _" + number) .offset (). top }); }} But the problem is like the picture. It is moved, but the upper part is covered by the navigation bar. I want to prevent row data from being obscured by the navigation bar I want the scrolling up a bit. Is there any good way? -
404 error after implementing django-rest-knox
I want to implement auth using django-rest-knox. I don't know where the issue. I am new to django also. urls.py urlpatterns = [ path("", include(router.urls)), path("^auth/register/$", RegistrationAPI.as_view()) ] I can a 404 message when I go the localhost:8000/api/auth/register. I got the same error when I use curl -
Filter data over count of two ManyToMany-relations
What's the way to filter data over the count of two ManyToMany-relations ? class Pic(models.Model): size_kb = models.IntegerField(default=0,blank=True) md5 = models.CharField(max_length=128,blank=True) class Film(models.Model): content = models.CharField(max_length=4096, null=True, blank=True) duration = models.SmallIntegerField(null=True, blank=True) class Video(models.Model): md5 = models.CharField(max_length=32,blank=True) rating = models.FloatField(null=True,blank=True) year = models.SmallIntegerField(null=True,blank=True) class Person(models.Model): pics = models.ManyToManyField(Pic,related_name='persons') videos = models.ManyToManyField(Video,related_name='persons') films = models.ManyToManyField(Film, related_name='persons') Searching for Persons with 10 - 20 Pics: Person.objects.all().annotate(seek_col=Count('Pic')).filter(seek_col__range=(10,20)) Result is ok ... Searching for Persons with 10 - 20 Films: Person.objects.all().annotate(seek_col=Count('Film')).filter(seek_col__range=(10,20)) Result is ok ... Searching for Persons with 10 - 20 Films AND 10 - 20 Pics: I try the follow statements: Person.objects.all().annotate(fcol=Count('films')).filter(fcol__range=(10,20)).annotate(pcol=Count('pics').filter(pcol__range=(10,20)) Person.objects.all().annotate(fcol=Count('films')).filter( pcol=Count('pics')).filter(fcol__range=(10,20), pcol__range=(10,20)) Result is nonsens ... not really nonsens: I expect follow results ( only pics and films columns ): | pics | films | | 20 | 20 | | 10 | 20 | | 14 | 15 | | 10 | 12 | | 16 | 13 | | 12 | 17 | but I get these results (depends on range): | pics | films | | 20 | 1 | | 1 | 20 | | 4 | 5 | | 10 | 2 | | 6 | 3 | | 2 | 7 | I … -
How to load file contents to ace editor
I set up a django website allowing users upload .txt files, and I want to add editing function by integrating ACE editor (or any other editor suggestions?). I have a list of my uploaded files, and I want an edit button to redirect to editor page with loading the file content in the editor page. I am wondering how to load file content to ace editor? I found some code about uploading file and displaying them in editor directly.(https://jsfiddle.net/xlaptop2001/y70gL3kv) However, what I want is to redirect to a new editor page with loading the file that already uploaded by clicking on 'edit' button. {% extends 'base.html' %} {% block content %} <h1>Mechanism {{ object.id }} details</h1> <style> ul.b { list-style-type: square; line-height:200%; } </style> <ul class="b"> <li> {% if object.ck_mechanism_file %} <a href="{{ object.ck_mechanism_file.url }}">{{ object.ck_mechanism_file }}</a> <a href="/ace/"> <button type="button" class="btn btn-primary btn-sm">Edit</button> </a> <a href="delete_mechanism"> <button type="button" class="btn btn-danger btn-sm">Delete</button> </a> {% else %} <span class="text-muted">No Mechanism File Attached</span> {% endif %} </li> <li> {% if object.ck_thermo_file %} <a href="{{ object.ck_thermo_file.url }}">{{ object.ck_thermo_file }}</a> <a href="/ace/"> <button type="button" class="btn btn-primary btn-sm">Edit</button> </a> <a href="delete_thermo"> <button type="button" class="btn btn-danger btn-sm">Delete</button> </a> {% else %} <span class="text-muted">No Thermo File Attached</span> … -
ProxyError while using "requests.post()" in Python/Django
I try to call a java-based web-service in python code, using requests.post() as follows: endpoint = 'http://**.**.**.**:8080/MyApp/services/Services/login' def index(request): post = request.POST if request.POST.get('login_button'): qd = QueryDict(mutable=True) qd.update( inputPhoneNumber=request.POST.get('phone_num'), inputPassword=request.POST.get('password') ) messages.info(request, '{}?{}'.format(endpoint, qd.urlencode())) response = requests.post('{}?{}'.format(endpoint, qd.urlencode())) result = response.json() messages.info(request, result) return render(request, 'login/index.html') However, proxy blocks my request. I suspect that this happens because the web-service uses http protocol. After 30 hours of searcing, I could not find anything to solve this problem. I've tried changing http to https but that caused another error. For the record, I can access web-service's url by manuel on browser, but I cant, on django. The stack trace is: ProxyError at /login/ Request Method: POST Request URL: http://localhost:8000/login/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['login', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Traceback: File "C:\Program Files\Python37\lib\site-packages\urllib3\connection.py" in _new_conn 160. (self._dns_host, self.port), self.timeout, **extra_kw) File "C:\Program Files\Python37\lib\site-packages\urllib3\util\connection.py" in create_connection 80. raise err File "C:\Program Files\Python37\lib\site-packages\urllib3\util\connection.py" in create_connection 70. sock.connect(sa) During handling of the above exception ([WinError 10060] Bağlanılan uygun olarak belli bir süre içinde yanıt vermediğinden veya kurulan bağlantı bağlanılan ana bilgisayar yanıt vermediğinden bir bağlantı kurulamadı), another exception occurred: File "C:\Program Files\Python37\lib\site-packages\urllib3\connectionpool.py" in … -
Django Model Type
My goal is to have a model structure like the below: Course Section Subsection For each course there can be multiple sections. And each section can have multiple subsections. class Course(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class Section(models.Model): course = models.OneToOneField( Course, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) def __str__(self): return self.title class SubSection(models.Model): title = models.CharField(max_length=200) course = models.OneToOneField( Course, on_delete=models.CASCADE, ) def __str__(self): return self.title However, when i test this via the admin, I can create a course, but not a section? # cat course/admin.py from django.contrib import admin from .models import Course admin.site.register(Course) Any ideas on where im going wrong? -
Maximum call stack size exceeded error on JQuery Autocomplete Lookup
I have the following code: var person_names = JSON.parse(document.getElementById('person_names').textContent); $('#autocomplete_person_names').val(''); var selected_person = null; $('#autocomplete_person_names').autocomplete({ lookup: person_names, showNoSuggestionNotice:true, maxHeight:200, onSelect: function (suggestion) { selected_person = suggestion.value; } }); For some reason I get the uncaught type error Maximum call stack size exceeded in my console. When I check line by line, I found out the error is because of the following line: lookup: person_names, As far as I have found out by searches until now, the Maximum call stack size exceeded is because of recursive functions. But I cannot understand what kind of recursive behavior the lookup brings here. What could be the problem here? Another thing: the variable person_names gives an array and works fine. And I am using this inside an html template inside a Django project. The full error in console looks like this: Uncaught RangeError: Maximum call stack size exceeded at Function.map (jquery-3.3.1.js:462) at b.verifySuggestionsFormat (jquery.autocomplete.min.js:8) at b.setOptions (jquery.autocomplete.min.js:8) at new b (jquery.autocomplete.min.js:8) at HTMLInputElement.<anonymous> (jquery.autocomplete.min.js:8) at Function.each (jquery-3.3.1.js:354) at jQuery.fn.init.each (jquery-3.3.1.js:189) at jQuery.fn.init.a.fn.devbridgeAutocomplete (jquery.autocomplete.min.js:8) at HTMLDocument.<anonymous> ((index):3734) at c (jquery.min.js:4) -
Syntax Error after adding knox to urls.py
I am new to Django and django-rest-framework. I am building an API and I want to implement auth using Django-rest-Knox. I have added Knox to the installed apps in the settings.py. In the urls.py of the project, I added the path to Knox. It seems there is a syntax error. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("api/", include('core.urls')) path("api/auth/", include('knox.urls')), ] This is the error message : path("api/auth/", include('knox.urls')), ^ SyntaxError: invalid syntax -
Django - Retrieve Different Post Types Based On TimeStamp
I am working on a little Django project. The user can create two types of Posts: Image & Video . Here, the different classes I have created (for the sake of brevity, I excluded some fields): class VideoPost: videoData = ... class ImagePost: imageData = ... So, when I combined the project with an Android app to display the posts on the screen, then I faced the problem how to retrieve the different posts once. I could not come up with a solution. Let's say, the user has created video and image post objects with the following order: VideoPost1 -> ImagePost1 -> ImagePost2 -> VideoPost2 How can I retrieve them in that order ? So, how to get a that mix of video and image posts based on creation time ? At the moment, I can only make separate queries like: # the view responsible for listing VideoPost instances .... return VideoPost.objects.all() # the view responsible for listing ImagePost instances .... return ImagePost.objects.all() I do not want to sort the instances on the frontend (Android app). So, is there a way to sort and query the different instances on the backend (Django) -
How do I allow model serializer to set model's foreign key field to null?
I want to be able to set the borrower field (a foreign key) in my Asset model to be NULL but I can't seem to get it to work. I'm trying to send a PATCH request with JSON data that has the key borrower equal to value of NULL but the borrower field won't get updated to NULL for the model instance. Perhaps there is an issue with the serializer that is preventing the foreign key field from being able to be set to NULL? I have already tried passing in allow_null=True to BorrowSerializer class but that hasn't worked. I've searched high and low on StackOverflow for posts with similar problems and solutions but nothing I've tried has worked. Here is my models.py: from django.conf import settings from django.db import models from django.utils import timezone from datetime import date from django.contrib.auth.models import User from django.urls import reverse import uuid class Category(models.Model): """Model representing an Asset category""" name = models.CharField(max_length=128) def __str__(self): return self.name class Borrower(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=128) associated_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return f'{self.first_name} {self.last_name}' class Asset(models.Model): """Model representing an Asset""" # Unique identifier for an instance of an asset (a barcode of sorts) … -
How to allow normal user to access port 80 and 443 on compute engine ubuntu18.04 intance?
I'm trying to host django wesite on gcp compute engine ubuntu 18.04 instance. when i'm running django development server as normal user on port 80, it show error "Error: You don't have permission to access that port." But when i run same as root user, it run successfully. I guess normal user don't have permission to access port 80 or port 443. Is there any way i can provide port access to normal user? -
Django database and migration error, ValueError: Related model 'Users.user' cannot be resolved
I am facing a very very strange situation with my Django (in general). I'm using Django 2.2 and Python 3.6.7. Every single time I create a new project, using: django-admin startproject myproject and trying to migrate it, I got this error : Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying admin.0004_auto_20190630_1438... OK Applying admin.0005_auto_20190630_1441...Traceback (most recent call last): File "C:\Dev\Django\myproject\manage.py", line 21, in <module> main() File "C:\Dev\Django\myproject\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Dev\Django\Env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Dev\Django\Env\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Dev\Django\Env\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Dev\Django\Env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 137, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File … -
How to assign object permission with override save() in model class?
I want model chapter to have two status. One is public, the other is only for permitted group. Therefore, I think I need object permission to put into practice. I also hope I can assign permission whenever I create or edit the object class Chapter(models.Model): chapter = models.PositiveSmallIntegerField() title = models.CharField(max_length=200, blank=True) content = models.TextField() book = models.ForeignKey('book', on_delete=models.CASCADE, null=True) AVAILABLE_STATUS = ( ('p', 'public'), ('l', 'login user only') ) status = models.CharField( max_length = 1, choices = AVAILABLE_STATUS, default = 'p', help_text='Chapter availability', ) class Meta: ordering = ['chapter'] unique_together = (("book", "chapter"),) permissions = (('author', "Can Create ,Edit , Delete"), ('view_private_chapter',"Can View Private Chapter") ) def save(self, *args, **kwargs): if self.status=='l': group = Group.objects.get_or_create(name='private_chap_viewer') assign_perm('view_private_chapter', group, self) super().save(*args,**kwargs) But I get Error:not all arguments converted during string formatting when i try to change chapter status in admin