Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access django main page by its name not ip
is there a way to configure a Django server in that way so I can open my local webpage by typing 'weatherstation.local' and not by the IP:port? -
Django - select [column] AS
I have the following code: MyModel.objects.values('foo','flu','fu').filter(part_of=pk) which gives me the following dictionary: {'foo': a, 'flu': b, 'fu': c} This dictionary is serialized into a JSON response like so: JsonResponse(data, safe=False) Is there a way I could rename the key of 'flu' into something while preserving the value? So far I tried: values[0]['new_flu'] = values[0].pop('flu') Which I think is the usual Python way of renaming a dictionary key however this seems to have no effect and the JSON returned still contains 'flu' instead of new_flu. I feel like this could be simply solved by ALIAS eg. SELECT foo, flu AS new_flu, fu from ..... What would be the Django alternative of this command? Or is there some other solution? -
Post Foreign Key As Id but show Foreign Key Details in GET method
I am working in a drf & react app . Where i need to show details of a foreign key field but when in POST method i need post only ID.But its not norking for nested serilizer. Giving an error from frontend named "Expected Dictonary but got int". output: { "id": 1, "Hospital": { "id": 1, "User_Info": "bnsb@gmail.com", "Manager_Name": "Jalal Uddin", "Address": "Dhaka" }, "FullName": "s", "Age": "s", Models.py: class Hospital(models.Model): User_Info = models.ForeignKey(User , on_delete=models.CASCADE) Manager_Name = models.CharField(max_length= 40 , blank=True, null=True) Address = models.CharField(max_length=40 , blank=True, null=True) class Patient(models.Model): Hospital = models.ForeignKey(Hospital , on_delete= models.CASCADE , default = 1) FullName = models.CharField(max_length = 50 , blank = False , null = False , default = "") Age = models.CharField(max_length=12 , blank=True, null=True) def __str__(self): return str(self.User_Info.Hospital_Name) Serilizers.py: class HospitalDetailsForPatientSerializer(serializers.ModelSerializer): User_Info = CustomUserSerializer(read_only= True) class Meta: model = Hospital fields = "__all__" extra_kwargs = {"Address":{'read_only': True} ,"Manager_Name":{'read_only' : True}} I got the expected output, Now I need to POST the only ID of Hospital Model when I save the patient but it's not working. -
Why can't Django detect a static file outside of my project folder in local?
In a Django template tag, I am returning a file path that is outside of my project folder. I am placing this in my template. My files look like this: myproject (contains project, app, manage.py, etc) myfolder | +----styles.css In my template tag, this is what I am returning: from myproject.settings import BASE_DIR from pathlib import Path ... def get_outside_file(): HOME_DIR = Path(BASE_DIR).parent return os.path.join(HOME_DIR, 'myfolder/styles.css') Unfortunately, in my template, I get this error: "GET /Users/myusername/myfolder/styles.css HTTP/1.1" 404 I clearly have the file in that folder, but Django can't seem to detect it. How can I fix this issue? Thanks for any help. BTW, I am on Mac OsX, if that helps. -
Customizing Username error that shows for duplicate
Ok let me go straight to the point, When a user try to signup with a username that has already been taken it shows an error like A user with that username already exists. How can I customize that message ? I tried adding error message in my Form Class like below but does not work error_messages = { 'username':_('Nametaken') } This is the whole of the form class UserRegistrationForm(forms.ModelForm): password1 = forms.CharField(label='', widget=forms.PasswordInput(attrs={ 'placeholder': 'Password'}) ) password2 = forms.CharField(label='', widget=forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password'}) ) class Meta: model = User fields = ('username', 'email') widgets = { 'username': forms.TextInput(attrs = {'cols': 1, 'rows': 8, 'placeholder':'username'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email'}), } labels = { 'username': _(''), 'email': _(''), } help_texts ={ 'username': None } error_messages = { 'username':_('Nametaken') } def clean_password2(self): cd = self.cleaned_data if cd['password1'] != cd['password2']: raise forms.ValidationError("passwords don't match") return cd['password1'] -
getting an error of an integer is required (got type DeferredAttribute)
i need to group data based on hour extracted from a 13 digit unix timestamp.those timestamps are stored in a model(Hello) field called startTime with IntegerField timehour = InteractionWith.objects.values( #hour=ExtractHour('startTime') hour=datetime.datetime.fromtimestamp((Hello.startTime)).strftime('%H') ).annotate( times=Count('pk') ).order_by('hour') -
Django rest multiple nested Related
I have 3 table Province, Commune and District that link to each other. Province hasMany District District hasMany Commune When vist my api url api/v1/province/ i got data like this [ { "id": 1, "name_eng": "Banteay Meanchey", "name_kh": "បន្ទាយមានជ័យ", "district": [ { "id": 1, "name_eng": "Mongkol Borei", "name_kh": "មង្គលបុរី", "province": 1 }, { "id": 3, "name_eng": "Malay", "name_kh": "មា៉ឡៃ", "province": 1 } ] }, ] I want to make it nested multiple like this [ { "id": 1, "name_eng": "Banteay Meanchey", "name_kh": "បន្ទាយមានជ័យ", "district": [ { "id": 1, "name_eng": "Mongkol Borei", "name_kh": "មង្គលបុរី", "province": 1 "commune": [ "id": 1, "name_eng": "Mongkol Borei", "name_kh": "មង្គលបុរី", ] }, ] }, Is it Possible to do so??? My Model class Province(models.Model): name_eng = models.CharField(max_length=50) name_kh = models.CharField(max_length=50) class District(models.Model): province = models.ForeignKey( Province, on_delete=models.CASCADE, related_name="district") name_eng = models.CharField(max_length=50) name_kh = models.CharField(max_length=50) class Commune(models.Model): district = models.ForeignKey( District, on_delete=models.CASCADE, related_name="commune") name_eng = models.CharField(max_length=50) name_kh = models.CharField(max_length=50) My Serializer class ProvinceSerializer(serializers.ModelSerializer): # commune = serializers.SerializerMethodField() class Meta: model = Province fields = ['id', 'name_eng', 'name_kh', 'district'] depth = 1 class DistrictSerializer(serializers.ModelSerializer): class Meta: model = District fields = ['id', 'name_eng', 'name_kh', 'commune'] # fields = '__all__' depth = 1 class CommuneSerializer(serializers.ModelSerializer): class Meta: model = … -
Django/Gunicorn/Nginx: myproject-gunicorn: ERROR (not running) / myproject-gunicorn: ERROR (spaw running)
I have deployed my Django project on ubuntu server with Nginx/Gunicorn/Supervisor I was working until this afternoon I have made some corrections 'on the fly' and restart services using sudo supervisorctl restart intensetbm-gunicorn It was also working until my last modifications but I don't know if it is related when I run this command, I got errors: myproject-gunicorn: ERROR (not running) myproject-gunicorn: ERROR (spawn error) How can I get more informations about these errors? -
Django How to rename file upload by can change path?
I want to change filename before upload. I create folder for store image which seperate by catagories of image. So, I have to set folder path for upload. This is my code for rename file and set path. def path_and_rename(instance, filename,path): upload_to = path ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(upload_to, filename) I upload by this code. image=models.ImageField(upload_to=path_and_rename("path_image1")) when I run it show error like this. image=models.ImageField(upload_to=path_and_rename("path_image1")) TypeError: path_and_rename() missing 2 required positional arguments: 'filename' and 'path' I don't know how to set parameter and filename. How to fix it? -
cities_light fails to populate the database
I'm not getting an error when I do python manage.py cities_light but it's not populating the database. I want to include countries so I removed the CITIES_LIGHT_INCLUDE_COUNTRIES setting, then I repeat python manage.py cities_light but I still dont get any city. So I added back the CITIES_LIGHT_INCLUDE_COUNTRIESsetting. When I try to populate my database with python manage.py cities_light --force-import-all and python manage.py cities_light --force-all, I get these errors: WARNING 2020-07-07 14:49:46,343 cities_light 4654 140274572259456 Saving Manono, Democratic Republic of the Congo failed: IntegrityError('null value in column "region_id" violates not-null constraint\nDETAIL: Failing row contains (9099, Manono, Manono, manono, 9179907, , Manono, Democratic Republic of the Congo, 9179907, 40, null).\n') WARNING 2020-07-07 14:50:13,388 cities_light 4654 140274572259456 Saving Gldanskiy Rayon, Georgia failed: IntegrityError('null value in column "region_id" violates not-null constraint\nDETAIL: Failing row contains (13587, Gldanskiy Rayon, Gldanskiy Rayon, gldanskiy-rayon, 614519, , Gldanskiy Rayon, Georgia, 614519, 79, null).\n') WARNING 2020-07-07 14:50:15,785 cities_light 4654 140274572259456 Saving Djibloho, Equatorial Guinea failed: IntegrityError('null value in column "region_id" violates not-null constraint\nDETAIL: Failing row contains (13970, Djibloho, Djibloho, djibloho, 12168385, , Djibloho, Equatorial Guinea, 12168385, 88, null).\n') Traceback (most recent call last): File "manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line … -
django DEFAULT_VERSION is breaking swagger
When I add a DEFAULT_VERSION for api versioning in my django settings: REST_FRAMEWORK = { .... "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", "DEFAULT_VERSION": "v1", } My swagger is breaking. Probably because the url's are not the same anymore. How can I fix this? My error code of swagger is: "No operations defined in spec!" swagger (version 3.22.3) settings: -
django-admin file upload return 404 page in shared hosting (namecheap)
I have deployed a Django app in namecheap shared hosting. All the page and functions are working fine except file upload. File upload from django-admin(return 404 page) and custom file upload form (render root page view) is not working. I have tried with flask app and file upload is working fine. All settings about media is ok. I have contacted with namecheap support. But, they want specific problem which i can't find out. I got similar type question in stackoverflow and other forum but nobody has replied. Thank in advance. -
UUID links extra character at the end ("%7B")
Thanks in advance, since I've changed a relationship between a book and user from Foreignkey to m2m ( so a book could have multiple authors ) my links pointing to the profile aren't working anymore, In my users/urls.py path("public_profile/<uuid:user_id>/", views.PublicProfile, name="public_profile") When using a foreign key it was working fine with this code in the template {% for book in page_obj%} a href="{% url 'users:public_profile' book.original_poster.ID%}">{{book.original_poster.first_name}} {{book.original_poster.last_name}}</a> .... {%endfor%} But now with this code {% for book in page_obj%} {% for poster in book.original_poster.all%} <a href="{% url 'users:public_profile'poster.ID%}{"> {{poster.ID}}</a> {% endfor %} {%endfor%} instead of linking to users/public_profile/UUID ( which is working when typed manually ) it links to users/public_profile/UUID/%7B Does anyone have an idea why ? Thank you -
How to use the regroup tag in Django
I have the same structure that the documentation suggests but it doesn't print me <li>None <ul> <li>: </li> <li>: </li> <li>: </li> </ul> </li> prints as 920 blank items, here is my structure [{'where': 'Mumbai', 'attribute': 'title', 'error': 'India'}, {'where': 'Calcutta', 'attribute': 'nameFile', 'error': 'India '}, {' where ':' New York ',' attribute ':' sizeFile ',' error ':' USA '}, {' where ':' New York ',' attribute ':' amount_stars ',' error ': '12'}, {'where': 'Chicago', 'attribute': 'subject', 'error': 'USA'}, {'where': 'Tokyo', 'attribute': 'nameGrade', 'error': 'Japan'}, {'where': 'Mumbai', 'attribute': 'nameLevel', 'error': 'Level One'}, {'where': 'Mumbai', 'attribute': ' amount_stars', 'error': '1'}] try to make it the same with the difference that I want to group by where {% regroup list_errorsProcess by where as where_list%} <ul> {% for where in where_list%} <li> {{where.grouper}} <ul> {% for err in where.list%} <li> {{err.attribute}}: {{err.error}} </li> {% endfor%} </ul> </li> {% endfor%} </ul> suddenly something you forget (maybe you don't care about something in the view or ...) also I need to check the number of elements but tag | length tells me that there are 462 and not the 8 .count tag instead nothing, thanks any suggestion -
Use jinja template to pass value to vuejs method, from django context
I have a strange problem with Django and Vuejs. I'm passing two variables in a context to my template and Vue component as such: # Django view context = { 'var1': var1, 'var2': var2 } <!-- template --> <div> <p>Display var1: {{var1}}</p> <p>Display var2: {{var2}}</p> ... </div> <!-- html result below Display var1: value_of_var1 Display var2: value_of_var2 --> The above works perfectly however, when I try to pass and use var1 and var2 in a Vue method as shown below, I get an error: <!-- template --> ... <button @click.prevent="doThis({{var1}},{{var2}})">Do This</button> // Vuejs method method: { doThis(var1, var2){ console.log(var1, var2) } } I get the following in the console: // value_of_var1 undefined What am I doing wrong? -
Getting "status 400 Bad Request" in django rest framework with react
I am trying to record and upload an audio to django server using rest framework. My audio is getting recorded as well as the server is working fine. But they aren't working together. I am getting a status 400 Bad request. I have tried using both axios and fetch() in react but nothing is helpful. This is when I use axios : [![This is when I use fetch() to upload.][2]][2] This is when I use fetch() [2]: https://i.stack.imgur.com/k8RkQ.jpg This is react code: onStop(recordedBlob) { var headers ={ 'Content-Type' : 'multipart/form-data' } const data = new FormData(); data.append('audio', recordedBlob); console.warn(recordedBlob); /* fetch("http://127.0.0.1:8000/temp/",{ method:'POST', body:data, headers:headers }).then( res => console.log(res)).catch(error => { console.log(error); })*/ axios.post("http://127.0.0.1:8000/temp/", data, { 'headers':headers }) .then(res => { console.warn(res); }).catch((error)=>{ console.log(error); }); } My django views file : class AudioCreateView(ModelViewSet): queryset=Audio.objects.all() serializer_class = AudioSerializer def post(self, request, *args, **kwargs): if 'file' not in request.data: raise ParseError('No File Uploaded') file_obj = request.data['audio'] # do some stuff with uploaded file Audio.objects.create(audio=file_obj) return Response(data="File Received") My serializers file : class AudioSerializer(serializers.HyperlinkedModelSerializer): class Meta: model= Audio fields = ['audio'] **My django settings : ** INSTALLED_APPS = [ 'corsheaders', 'lang_translator.apps.LangTranslatorConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', … -
Get AttributeError when writing a foreign key relationship in Django Rest Framework
After reading the DRF tutorial, I try to write a API but get 'Request' object has no attribute 'customer' when I send post request to /api/images/.I just try to copy and modify codes from the DRF tutorial. Can someone tells me what's going wrong? (Customer is the foreign key of the image.) models.py class Customer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey('auth.User', related_name='customers', on_delete=models.CASCADE) class Image(models.Model): customer = models.ForeignKey(Customer, related_name='images', on_delete=models.CASCADE) figure = models.ImageField(blank=False, null=False) serializers.py # User Serializer class UserSerializer(serializers.HyperlinkedModelSerializer): customers = serializers.HyperlinkedRelatedField(many=True, view_name='customer-detail', read_only=True) class Meta: model = User fields = ['url', 'id', 'username', 'customers', 'email'] class CustomerSerializer(serializers.HyperlinkedModelSerializer): images = serializers.HyperlinkedRelatedField(many=True, view_name='image-detail', read_only=True) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Customer fields = ['url', 'id', 'first_name', 'last_name', 'email', 'images', 'owner'] class ImageSerializer(serializers.HyperlinkedModelSerializer): customer = serializers.ReadOnlyField(source='customer.email') class Meta: model = Image fields = ['url', 'id', 'figure', 'customer'] views.py class UserView(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user class CustomerViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Customer.objects.all() serializer_class = CustomerSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] def perform_create(self, serializer): """ The create() method of our serializer will now be … -
how to show each user's uploaded picture to be present at navbar with django?
How do i serve the user's uploaded picture to him when he is logged in using django? what should i code inside the src attribute in html tags? views.py: def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('app_1:home_page')) else: return HttpResponse('Time Out') else: return HttpResponse('invalid username or password') return render(request, 'app_1/login.html') i have used Django's built in User model for the job with another module called UserInfo that has an attribute with an OneToOne(User) value ... I just don't know how to reference each user's picture ... please help me ... -
NotImplementedError at /admin/authtoken/token/ may be implemented in a future release
NotImplementedError at /admin/authtoken/token/ may be implemented in a future release whhai is problem? -
Django not serving static files on Heroku when DEBUG=False
Before explaining the issue, I want to tell you that I have already tried these solutions on StackOverflow: Django Heroku not serving static files when Debug=False Django: Whitenoise not working in production with debug false Heroku Ticket I raised a ticket on Heroku also. I got this in reply: Please try running the command python manage.py collectstatic on your local machine before deploying your app to Heroku. This would make the required arrangements in your application directory which you can later push to Heroku. The reason why it isn't working is due to the ephemeral file system of Heroku. This means that any changes made to the file system will not be persistent. Every dyno boots with a fresh copy of your deployed application file system. When you run this command from the Heroku bash, it spins a one-off dyno and runs the task on this dyno. So, once you run the task and exit the bash, these changes are deleted. They do not reflect on your application's live dyno. This is why you need to make all the file system changes on your local machine and push them to your Heroku app. Furthermore, when you set the DEBUG=false in … -
which Django auth backend fails
I'm trying to use django-axes to prevent password brute force. I add django-axes authentication backend to the list of auth backends in settings so when Django iterates over backends axes checks its database entries and breaks from the loop if there were too many attempts. Now I want to show an appropriate error message on the frontend: if the login attempt was blocked by axes, I want to show the "too many attempts" error, otherwise, I want to show "wrong password" error. The problem is that I have to way to get the information about which backend blocked the request, I only know that one of the backends blocked it. So the question is how do I configure Django auth backends so that I can know which backend blocked the login attempt? -
i have the csfr token in the form but i still get this error! someone know what i do wrong? Django project
--error-- Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. --my form-- <form name="addform" id="addform" … -
what is invalid literal for int() with base 10: 'startTime'
i am getting an error of invalid literal for int() with base 10: 'startTime' hour=datetime.datetime.fromtimestamp((int(str('startTime')))/1000).strftime('%H') startTime is Integerfield in my model which contains 13 digit unix timestamp this is my query code timehour = InteractionWith.objects.values( #hour=ExtractHour('startTime') hour=datetime.datetime.fromtimestamp((int(str('startTime')))/1000).strftime('%H') ).annotate( times=Count('pk') ).order_by('hour') -
TypeError: not enough arguments for format string in Django social login
I am using social-auth-app-django for Google authentication. Whenever I am trying to use google sign-in or admin page, I am facing this error. I have added everything correctly in settings.py , views and templates. -
How to change color of select field with empty value?
I created an app with Django as its backend and I have a form that features a dropdown with Foreign Key elements. The problem is that I want the dropdown option that doesn't have a value (i.e. the first empty/placeholder option) to be a different colour when unfocused than the options that do have values. I am using Bootstrap 4 and right now the form-control class is setting all the form inputs to a specific color, even the dropdown's colour? How can I change this with CSS, JQuery or both?