Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djoser user_list setting AllowAny not working
I have created login Api using Djoser for authentication. I want to get the list of users using a GET api call (/api/auth/users/ endpoint) but I get an error saying "detail": "Authentication credentials were not provided." I have added djoser settings in setting.py file like this DJOSER={ 'user': ['djoser.permissions.AllowAny'], 'user_list': ['djoser.permissions.AllowAny'], 'SERIALIZERS':{ 'user_create':'restapi_subserv.serializers.UserCreateSerializer', 'user':'restapi_subserv.serializers.UserCreateSerializer', } } But Still, I get the error. Am I missing something? Please let me know if you need any more details. -
Heroku how to update git remotes after project rename
I already renamed my project to PROJECT_NAME on Heroku and should I update project git remotes, This is Heroku guide: $ git remote rm heroku $ heroku git:remote -a PROJECT_NAME But when I run the first command, I'm getting this error: fatal: No such remote: heroku -
ModuleNotFoundError: No module named 'oscar.apps.dashboard.partnersoscar' in Django Oscar
I am setting up Oscar Django and getting the following error ModuleNotFoundError: No module named 'oscar.apps.dashboard.partnersoscar' in Django Oscar. -
How should I do when conf folder doesn't have global_setteings.py
When I launch a Django project in a local server, It doesn't work with the errors below, and then, I checked the directory of conf(/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf) and found that global_settings.py doesn't exist in that directory. in that case, how should I do? do I have to make the global_settings.py my self in there with this code? or will I be able to solve another way? Would you mind telling me how should I solve this problem? Thank you in advance. error code Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 11, in <module> from django.conf import settings File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 17, in <module> from django.conf import global_settings ImportError: cannot import name 'global_settings' from 'django.conf' (/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 21, in <module> main() File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 16, in main ) from exc 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? Python Console import sys; ... ...print(sys.path) ['/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/third_party/thriftpy', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages', '/Users/apple/GoogleDrive/project_django'] -
Is this a correct class-based-django-view?
In my project i have a page that displays a form where the User inputs some irrelevant(for the moment project name) and a host/ip-address. When he hits the scan button he makes a post request. In the current moment i get that ip address and im trying to 'banner-grab' the running services on that ip/host and render the results to the page. In the code below i got that working but as im litteraly using django for the first time i think that my aproach is really bad cause all of my code( for grabbing the banner etc ) is in the POST function in my class-based-view.So question is can i do this in a better way? Maybe write that bannerGrab() function somewere else and, if form is valid just call the function in the POST method... class NewProject(View): # Reusable across functions form_class = ProjectData template_name = 'projectRelated/create_project.html' ports = [20, 21, 22, 23, 80, 3306] def get(self, request): # redundant to use it like this # form = ProjectData() form = self.form_class context = { 'form': form # this is a context variable that i can use in my html page. like this <h3> {{ context.var }} </h3> … -
Three.js modal popup on model click
I'm trying to add onclick event to my model displayed using THREE.js. Here is how I'm loading the model. var ww = 600; wh = 400; function init(){ var three = THREE; renderer = new THREE.WebGLRenderer({canvas : document.getElementById('scene')}); renderer.setSize(ww,wh); renderer.setClearColor( 0xffffff, 1 ); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(50,ww/wh, 0.1, 10000 ); camera.position.set(0,0,500); scene.add(camera); controls = new THREE.OrbitControls (camera, renderer.domElement); controls.minAzimuthAngle = -1; // radians controls.maxAzimuthAngle = 1; // radians controls.minPolarAngle = 1.5; // radians controls.maxPolarAngle = 1.5; // radians //Add a light in the scene const skyColor = 0x00000 // light blue const groundColor = 0xFFFFFF; // brownish orange const intensity = 1; const light = new THREE.HemisphereLight(skyColor, groundColor, intensity); scene.add( light ); //Load the obj file loadOBJ(); } var loadOBJ = function(){ //Manager from ThreeJs to track a loader and its status var manager = new THREE.LoadingManager(); //Loader for Obj from Three.js var loader = new THREE.OBJLoader( manager ); //Launch loading of the obj file, addBananaInScene is the callback when it's ready loader.load( "static/pictures/3D/jaw.obj", addModelInScene); }; var addModelInScene = function(object){ model = object; //Move the banana in the scene model.rotation.x = Math.PI; model.scale.x = 2000; model.scale.y = 2000; model.scale.z = 2000; scene.add(model); render(); }; var render … -
Django User profile model form edit for current user
I have searched a lot on this and all the questions and answers provided are never clear and fit for purpose, maybe I'm going at it the wrong way. I have just recently started Python and Django, so know very little about it. I am creating a website and have done the basic authentication using Django and even added the facebook authentication using social-django. That part all works fine. Now I am moving to profile information and how to update it after you sign up to website. I have the below UserProfile in models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.TextField() last_name = models.TextField() email_address = models.EmailField() phone_number = models.TextField() In forms.py a testing form: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['first_name','last_name','email_address'] Then in views.py I have a function: def myprofile(request): if request.method == 'POST': form = UserProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() user_profile = UserProfile.objects.get(user=request.user) if request.method == 'GET': user_profile = UserProfile.objects.get(user=request.user) form = UserProfileForm(instance=user_profile) return render(request, 'pandp/myprofile.html', {'user_profile' : user_profile, 'form' : form}) And finally myprofile.html: <div class="profile-details"> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> </div> I was struggling from the start to actually only load UserProfile of the logged … -
Django signup neither gives error message nor registering user
I am beginner to python Django. I got stuck at signup form. I have created a form using signupform, but when I am submitting the form its not register the user or not get any error. When i code it first time it works perfectly but when I open next day to move forward in my learning but it's working like last time. model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class AppUser(User): pass form.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, get_user_model from stock.models import AppUser class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput) password = forms.CharField(widget=forms.PasswordInput) class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) password1 = forms.CharField(widget=forms.PasswordInput) password2 = forms.EmailField(widget=forms.PasswordInput) class Meta: model = AppUser fields = ('username', 'password1', 'password2' ) htmlTemplate {% extends 'base.html' %} {% block content %} <div> <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" >Signup</button> </form> </div> {% endblock %} views.py class SignupView(TemplateView): template_name = 'stock/signup.html' def get(self, request): form = SignUpForm() args = {'form':form} return render(request, self.template_name, args) def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): form.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('home') … -
Rise ValidationError in Django's forms
Anyone who can explain me, why my ValidationError in my form doesn't work? I can see "TEXT" in my terminal, but the ValidationError doesn't show. def clean(self): cleaned_data = super(CheckInForm, self).clean() new_room = cleaned_data.get('room') new_name = cleaned_data.get('name') if Student.objects.filter(room=new_room).count() > 3: if not Student.objects.filter(room=new_room, name__icontains=new_name): print('TEXT') raise ValidationError('The room is full') It’s also worth noting that a similar def clean_room(self): function works fine in my code. In this function, raise ValidationError works correctly. def clean_room(self): new_room = self.cleaned_data['room'] if new_room == '': raise ValidationError('This field cannot be empty') return new_room Full length code: class CheckInForm(forms.ModelForm): class Meta: model = Student fields = ['room', 'name', 'faculty', 'place_status', 'form_studies', 'group', 'sex', 'mobile_number', 'fluorography', 'pediculosis', 'contract_number', 'agreement_date', 'registration', 'citizenship', 'date_of_birthday', 'place_of_birthday', 'document_number', 'authority', 'date_of_issue', 'notation' ] widgets = {'room': forms.TextInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'faculty': forms.TextInput(attrs={'class': 'form-control'}), } def clean(self): cleaned_data = super(CheckInForm, self).clean() new_room = cleaned_data.get('room') new_name = cleaned_data.get('name') if Student.objects.filter(room=new_room).count() > 3: if not Student.objects.filter(room=new_room, name__icontains=new_name): print('TEXT') raise ValidationError('The room is full') def clean_room(self): new_room = self.cleaned_data['room'] if new_room == '': raise ValidationError('This field cannot be empty!') return new_room {% extends 'hostel/base_home.html' %} {% block check_in %} <form action="{% url 'check_in_update_url' id=student.id %}" method="post"> {% csrf_token %} {% for field in … -
What is wrong with {% block %}?
Console: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 6: 'blосk'. Did you forget to register or load this tag? Basic.html [<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>{% blосk title %}Главная{% endblock %} - Доска объявлений</title> </head> <body> <header> <hl>Объявления</hl> </header> <nav> <а href="{% url 'index' %}">Главная</а> <а href="{% url 'add' %}">Добавить</а> {% for rubric in rubrics %} <а href="{% url 'by_rubric' rubric.pk %}">{{ rubric.name }}</а> {% endfor %} </nav> <section> {% blосk content %} { % endblock % } </section> </body> </html>][2] index.html {% extends "layout/basic.html" %} {% block content %} {% for bb in bbs %} <div class="b"> <h2>{{ bb.title }}</h2> <p>{{ bb.content }}</p> <p><a href='{% url "by_rubric" bb.rubric.pk %}'>{{bb.rubric.name}}</a></p> <p>{{ bb.published|date:"d.m.Y H:i:s" }}</p> </div> {% endfor %} {% endblock %} I looked at the code, tags and syntax, too - I didn’t find anything. Help, please -
Django 3.0.4, PostGis, Geoserver 2.16.2 - Error when trying to load points from Postgis
I'm trying to learn how to use GeoDjango + Geoserver. I encountered a problem at the very beginning. Geoserver cannot display points created in Django (Postgis) (error: java.sql.SQLException: org.postgresql.util.PSQLException: ERROR: lwgeom_write_to_buffer: X / Z precision cannot be greater than 7 or less than -7) My model is: class MeasureStations(models.Model): ext_id = models.PositiveSmallIntegerField(verbose_name='station external ID') lat_lon = models.PointField(verbose_name='lat loncoordinates', ) elevation = models.DecimalField(verbose_name='elevation', decimal_places=3, max_digits=7) I add points through the Django admin panel. In openlayers: enter image description here records in db: enter image description here logs: org.geoserver.platform.ServiceException: Rendering process failed ... Caused by: java.lang.RuntimeException: java.io.IOException ... Caused by: java.io.IOException ... Caused by: java.sql.SQLException: org.postgresql.util.PSQLException: ERROR: lwgeom_write_to_buffer: X/Z precision cannot be greater than 7 or less than -7 at org.geotools.jdbc.JDBCFeatureReader.runQuery(JDBCFeatureReader.java:263) at org.geotools.jdbc.JDBCFeatureReader.(JDBCFeatureReader.java:143) at org.geotools.jdbc.JDBCFeatureSource.getReaderInternal(JDBCFeatureSource.java:595) ... 134 more Caused by: org.postgresql.util.PSQLException: ERROR: lwgeom_write_to_buffer: X/Z precision cannot be greater than 7 or less than -7 ... -
django_tables2 customization
Is it possible to make tables like this Using Django tables? this is my models.py class StudentsBehaviorGrades(models.Model): Teacher = models.ForeignKey(EmployeeUser, on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE, null=True, blank=True) Students_Enrollment_Records = models.ForeignKey(StudentPeriodSummary, on_delete=models.CASCADE, null=True) Grading_Period = models.ForeignKey(gradingPeriod, on_delete=models.CASCADE,null=True, blank=True) Grading_Behavior = models.ForeignKey(EducationLevelGradingBehavior,on_delete=models.CASCADE, null=True, blank=True) Marking = models.ForeignKey(StudentBehaviorMarking,on_delete=models.CASCADE, null=True) This is my table in Django admin StudentsBehaviorGrades -
How to import JSON file in Mongodb using django?
I am working on a project for wich i am using Django framework to serve as server and Mongodb as a back-end database.I have a JSON file which i want to import in MONGODB using DJANGO, but i don't know how to do that, i am a beginner. A help would be much appreciated.Thank you. My file includes this data: data: { request: [ { type: "City", query: "Karachi, Pakistan" } ], weather: [ { date: "2009-01-01", astronomy: [ { sunrise: "07:17 AM", sunset: "05:54 PM", moonrise: "10:19 AM", moonset: "10:11 PM", moon_phase: "Waxing Crescent", moon_illumination: "31" } ], maxtempC: "0", maxtempF: "32", mintempC: "0", mintempF: "32", avgtempC: "19", avgtempF: "66", totalSnow_cm: "0.0", sunHour: "8.7", uvIndex: "1", hourly: [ { time: "0", tempC: "19", tempF: "66", windspeedMiles: "4", windspeedKmph: "6", winddirDegree: "358", winddir16Point: "N", weatherCode: "113", weatherIconUrl: [ { value: "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png" } ], weatherDesc: [ { value: "Clear" } ], precipMM: "0.0", precipInches: "0.0", humidity: "61", visibility: "10", visibilityMiles: "6", pressure: "1016", pressureInches: "30", cloudcover: "0", HeatIndexC: "26", HeatIndexF: "78", DewPointC: "16", DewPointF: "61", WindChillC: "24", WindChillF: "75", WindGustMiles: "4", WindGustKmph: "7", FeelsLikeC: "24", FeelsLikeF: "75", uvIndex: "1" }, { time: "300", tempC: "18", tempF: "65", windspeedMiles: "5", windspeedKmph: "8", … -
Why do I get this error when putting models.CASCATE?
This is my models.py content: content = models.TextField() seen = models.BooleanField(default=False) user = models.ForeignKey('Users', on_delete=models.CASCADE) def _str_(self): return self.content class Users(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) online = models.BooleanField(default=False) def _str_(self): return self.name pass and I am getting this error when trying to put " models.CASCATE " in on_delete module: File "/workspace/testjson/App/backend/chat/chatApp/models.py", line 8, in Messages user = models.ForeignKey('Users', on_delete=models.CASCATE) AttributeError: module 'django.db.models' has no attribute 'CASCATE'``` Could someone explain me why I am getting this error? Thanks <3 -
list index out of range while retrieving tweets with certain hashtag using TwitterAPI
While trying to retrieve tweets with a particular hashtag, I am getting error stating index out of range in the lines highlighted or under two asterisks. As far as I understand, this is not the because of the error in python code. I am not able to understand the reason for getting this error. Please help me out. views.py code: from django.shortcuts import render from TwitterAPI import TwitterAPI from Post.models import Album import calendar from django.contrib.auth.models import User import requests import http.client,urllib.request,urllib.parse,urllib.error,base64,sys import simplejson as json consumer_key='RNBUUEtazKVJemcMedGHWgMCV' consumer_secret='zILQDS386Dd4WRr8810gD5WAGbfkeVRDT3BYWs7RKChY1U7duM' access_token_key='893345180958564352-UT4mqHeDQyYllebzbsIPItOCyjHs8eP' access_token_secret='Gv2pbj6eeKvKPWjbePfO71la7xOeib2T5lV4SaL86UUdj' api = TwitterAPI(consumer_key,consumer_secret,access_token_key,access_token_secret) me = User.objects.get(username='vedant') def newsfeed(request): hashtag_string = '#Swachh_Bharat' hashtag_string = hashtag_string.lower() if(request.GET.get('mybtn')): hashtag_string = str(request.GET.get('hashtag')) print("HashtagString :: ",hashtag_string) if hashtag_string == '#vedant': url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] url_list_in_database = Album.objects.all().filter(user = me).values('image_url') temp = Album.objects.all().filter(user = me).values('image_url','date','retweet_count','like_count') url_list = {} for entry in temp: dt = str(entry['date'])[0:10] dt = calender.month_name[int(dt[5:7])]+" "+ dt[8:10]+"," + dt[0:4] url_list[str(entry['image_url'])] = (dt, str(entry['retweet_count']),str(entry['like_count'])) return render(request, 'Post/newsfeed.html', {'url_list': url_list}) #get the images of particular hashtag else: url_list = [] retweet_count_list = [] url_retweet_dict = {} url_favourite_dict = {} favourite_count_list = [] r = api.request('search/tweets',{'q':hashtag_string,'filter':'images','count':1000}) url_dict = {} for item in r: line = … -
Django rest framework error object X has no attribute 'get_extra_actions'
I am wanting to add some search functionality to my API and I followed this simple guide but I'm still getting the error type object 'ClientViewSet' has no attribute 'get_extra_actions' My setup Versions Django: 2.2.5 Django Rest Framework: 3.11.0 Python: 3.8.2 urls.py router = routers.DefaultRouter() router.register(r'clients', ClientViewSet) urlpatterns = [ path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] serializers.py class ClientSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Client fields = '__all__' views.py class ClientViewSet(generics.ListAPIView): queryset = Client.objects.all() serializer_class = ClientSerializer filter_backends = [filters.SearchFilter] search_fields = ['phone'] -
{'batch': ['“asdsad” is not a valid value.']} is not a valid value
I am new in python (Django), i try to save the data using django from it throw me error like a ** Please select a valid value ** ** model.py ** class Dataset(models.Model): dataset = models.CharField(max_length=255) def __str__(self): return self.dataset class Batch(models.Model): batch = models.CharField(max_length=255) def __str__(self): return self.batch class Image(models.Model): image = models.CharField(max_length=255) batch = models.ManyToManyField('Batch') dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE) def __str__(self): return self.image ** Form.py ** class ImageForm(ModelForm): class Meta: model = Image fields = ['image','batch','dataset'] ** Views.py ** def image(request): dataset = Dataset.objects.all() if request.method == 'POST': form = ImageForm(request.POST) if form.is_valid(): form.save() return redirect(home) else: return HttpResponse("Form is Not Valid") else: return render(request,'shop/form.html', {'dataset' : dataset}) -
How do I input current date and time in Django?
So I'm a beginner in Django, and recently came up with a question, regarding datetime. So I'm trying to make a blog-like page. And among the input fields, including title and contents, I want a datetime field as well. However, there is an additional feature that I want to create, which is -- if the user clicks a checkbox right next to the datetime input field, the datetime will automatically change into the CURRENT date and time. So the input field is replaced with the current date and time. I have no idea on how to create the feature. I would very much appreciate your help :) -
Will the delete function be triggered if on_delete is set to models.PROTECT?
I am trying to implement a behavior where when I am trying to delete an instance, the instance will not be deleted but django will set an attribute called deleted to True. However, when I am trying to define a foreign key, I have to set on_delete because it is required. I set it to models.PROTECT. My question is: Will django trigger my overridden delete function while setting on_delete to models.PROTECT? Here is an example code: class BaseModel(models.Model): deleted = models.BooleanField(default=False) def delete(self): self.deleted = True self.save() class A(BaseModel): pass class B(BaseModel): a = models.ForeignKey('A', on_delete=models.PROTECT) -
Django Python Seat Selector User Interface
I'm trying to replicate something similar to this. I know a few websites that do this type of seat selection movie theatres, airlines, etc. How can I accomplish something like this? Are there any examples out there for accomplishing this is Django and Python? -
DRF: using partial update common case
I use the partial_updae method to update the instance. I understand the logic of how to change and save a specific field or fields. That's how it's done for vendor_name field serializer.py class VendorManagementUpdateSerializer(serializers.ModelSerializer): contacts = VendorContactSerializer(many=True) parent = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) class Meta: model = Vendors fields = ('vendor_name', 'active', 'country', 'nda', 'parent', 'contacts',) def update(self, instance, validated_data): instance.vendor_name = validated_data.get('vendor_name', instance.vendor_name) instance.save() return instance views.py class VendorProfileUpdateView(generics.RetrieveUpdateAPIView): permission_classes = [permissions.AllowAny, ] serializer_class = VendorManagementUpdateSerializer lookup_field = 'vendorid' def get_queryset(self): vendorid = self.kwargs['vendorid'] return Vendors.objects.filter(vendorid=vendorid) def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) data { "vendor_name": "Tesddt7t2test" } That is, I get the value of the field I need from validate_data and manually replace it with instance in the def update() method. def update(self, instance, validated_data): instance.vendor_name = validated_data.get('vendor_name', instance.vendor_name) instance.save() But if I have, for example, 10 model fields and plus ForeignKey connections with other models, should I describe for all fields the same logic as for vendor_name and catch exceptions if the field was not passed to the request? def update(self, instance, validated_data): instance.vendor_name = validated_data.get('vendor_name', instance.vendor_name) instance.nda = validated_data.get('nda', instance.nda) ..... ..... instance.save() Or is there a way to write such functionality in a more … -
Basic question alert - Can script in Jupyter be called to use in Django/HTML
I have created some python script in a jupyter notebook that displays bushfires on mapbox, using a google sheet as a database - works great and takes an input for the user id to load user specific content. I want to take this online so users can login and interact. Presumed Django would be the best bet for this so created a project in pycharm. Is there a way to simply add the script in from the jupyter notebook. - This is a high level question (as i have a lack of 'systems' understanding being new to code), I just want to understand if I need to start from scratch and create an SQL database for Django, or if i can use what i have done in Jupyter so far. In my head, creating a compartment in HTML in pycharm for this bit of script and then being able to call it would be the (likely unrealistic) dream -
Objects not deleting
I have several ViewSets.They have one serializer and model. For example - ViewSet "Posts" and "Favorites". If I use DELETE request on Post object, he is deleted from "Posts", but in Favorites, I can see them. BUT, every object has a "URL" field. So, if some object from "Posts" will be deleted, then in "Favorites" I will see it and if I go to the link from the "URL" field, then I get "404 not found". Why does it happen? Model: class Post(models.Model): name = models.CharField(verbose_name='name', db_index=True, max_length=64) city = models.CharField(verbose_name='city', db_index=True, max_length=64) created = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(default=next_month, blank=True, editable=False) description = models.CharField(verbose_name='description', db_index=True, max_length=64) isFan = models.BooleanField(null=True) main_image = models.ImageField(upload_to=get_auth_dir_path, null=True, max_length=255) first_image = models.ImageField(upload_to=get_auth_dir_path, null=True, max_length=255) second_image = models.ImageField(upload_to=get_auth_dir_path, null=True, max_length=255) ViewSets: class PostViewSet(LikedMixin, viewsets.ModelViewSet): queryset = Post.objects.is_actual().order_by('-created') serializer_class = PostSerializer authentication_classes = (TokenAuthentication, SessionAuthentication, ) filter_backends = (DjangoFilterBackend, ) filterset_fields = (...) def perform_create(self, serializer): serializer.save(author=self.request.user) class ClosedPostViewSet(LikedMixin, viewsets.ModelViewSet): queryset = Post.objects.is_not_actual().order_by('-end_time') serializer_class = PostSerializer authentication_classes = (TokenAuthentication, SessionAuthentication,) filter_backends = (DjangoFilterBackend,) filterset_fields = (...) def perform_create(self, serializer): serializer.save(author=self.request.user) class SearchViewSet(LikedMixin, viewsets.ModelViewSet): pagination_class = None queryset = Post.objects.is_actual() serializer_class = PostSerializer authentication_classes = (TokenAuthentication, SessionAuthentication, ) filter_backends = (DjangoFilterBackend, ) filterset_fields = (...) def list(self, request, … -
3.5 hours in and still cannot install Django - my fortitude is waning
Hi and thank you for taking time out of your day to read this, and I very much appreciate any assistance. I'm trying to install Django for the first time - on a mac, python 3.7.7. However, the packages seem to be looking for 2.7 which is not the intended v3. I understand the best practice is to install this via a virtual environment. I am currently following this link. When I run mkvirtualenv my_django_environment I get this error: Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 6, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 585, in _build_master return cls._build_from_requirements(__requires__) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 598, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 786, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'zipp>=0.4' distribution was not found and is required by importlib-resources I've tried this mkvirtualenv -p /usr/local/bin/python3 my_django_environment Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 6, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set … -
customize user modification form django admin site
When you create/modify a user from the django admin site you have this interface : My project is quit simple because I have no group and every staff user could have superusers satus. That is why I want not to show the superuser status option, neither groups and user permissions. How to mask this sections of this form and assert that all staff users also superusers are. Any help would be very appreciated. Thanks in advance !