Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'charmap' codec can't encode characters in position 100-101: character maps to <undefined> in "requests.json()" [on hold]
Error Getting: 'charmap' codec can't encode characters in position 100-101: character maps to When Getting response from requests response = requests.post(url, data=json_data) response_json = response.json() print(response_json) Error Getting: 'charmap' codec can't encode characters in position 100-101: character maps to -
Django Heroku deployment - ! [remote rejected] master -> master (pre-receive hook declined)
There are a few posts with this particular issue however I've tried about five or six different suggestions from those posts and have had no luck. when trying git push heroku master I get the following error: (env) PS C:\Users\Shaun\Desktop\DjangoBlog\src> git push heroku master Total 0 (delta 0), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to murmuring-dusk-96030. remote: To https://git.heroku.com/murmuring-dusk-96030.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/murmuring-dusk-96030.git' From the build log on the Heroku website: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I have a simple static website running Django 2.2.3 as back end. I've been developing in a virtual environment on my local machine and have the following project structure shown blow, where 'src' was what I renamed the folder created by the django-admin startproject command. I'd like to deploy my site on Heroku so I've signed up, installed git and the Heroku CLI. In my terminal I've logged in to Heroku … -
Python mysql client installing on Mac
I am trying to install mysqlclient in a virtual environment. Python version is 3.0 So here is what I did Created a Virtual environment, activated it from terminal Installed the below, pip install django pip install mysqlclient Both installed without any errors. So I activated the virtual environment in terminal by using this, cd users/myenv/bin/ and then source ./activate Next I navigated to my project folder using cd users/pyworkspace/project I then started the server using this and python manage.py runserver then I got this error below, Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/_mysql.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/user/Desktop/python/myenv/lib/python3.6/site-packages/MySQLdb/_mysql.cpython-36m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/user/Desktop/python/myenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, … -
Django model match type
i have match table and i want to add Match type (like final. semifinal. quarter final. third place match. 1st match 2.match 3.match 4.match and more. If match in a league there may even be a 10th match What should you suggest me class MatchQuerySet(models.QuerySet): def finished(self): return self.filter(status=Match.STATUS_FINISHED) def started(self): return self.filter(status=Match.STATUS_STARTED) def playing(self): return self.filter(status=Match.STATUS_PLAYING) def cancelled(self): return self.filter(status=Match.STATUS_CANCELLED) def unknown(self): return self.filter(status=Match.STATUS_UNKNOWN) class Match(models.Model): STATUS_FINISHED = 'Bitti' STATUS_STARTED = 'Başladı' STATUS_PLAYING= 'Oynanıyor' STATUS_CANCELLED= 'İptal' STATUS_UNKNOWN= 'Bilinmiyor' STATUS_PENDING= 'Bekleniyor' STATUSES = ( (STATUS_FINISHED, 'Bitti'), (STATUS_STARTED, 'Başladı'), (STATUS_PLAYING,'Oynanıyor'), (STATUS_CANCELLED,'İptal'), (STATUS_UNKNOWN,'Bilinmiyor'), (STATUS_PENDING,'Bekleniyor'), ) name=models.CharField(max_length=255) slug=models.SlugField(unique=True,max_length=255) status = models.CharField(max_length=20,choices=STATUSES,default=STATUS_UNKNOWN) map=models.ForeignKey('GameMap',null=True,blank=True,related_name='matchmap',on_delete=models.PROTECT) league=models.ManyToManyField(League,blank=True,null=True) objects = MatchQuerySet.as_manager() -
About the Functions in Python
I was Trying to do write code related to this concept in python: We have a various list(eg:[1,2,3],[3,5,6],[5,6,7,8])like this a 1000's of set.We have forgotten to add num(10,20) which is common in all the list. We cannot add (10,20) in each list, which is a waste of time. How to append the num(10,20) in all the 1000 sets? Please, help me with this... -
Can i restrict data between staff user in same model?
I'm new in Django.I have to create staff user but distinct data between them of same model in django-admin. Can i add new permission in User model and implement in default admin? I have not idea about how to implement. i.e. i have 2 staff user, and add data in same model. If staff-user-1 is login then show only his added data only (can not see data added by staff-user-2). is possible in built-in django admin ? Thanks!!! -
Access-Control-Allow-Origin Issue in vue.js and django
I deploy my service in my own computer and it all works very well and I decided to put it on my server. But I find some request are restricted by 'CORS' and some are not. The web server is Nginx deployed on the Linux. The backend framework is Django, with DRF provided the api service.The frontend framework is Vue.js.And the Ajax request library is using 'axios'. The code runs very perfect on my own Mac and have no CORS problem. But it got problem on the server. By the way, the mode for the route in Vue.js is historymode. Here is my Nginx configure code: server { listen 80; server_name 167.179.111.96; charset utf-8; location / { root /root/blog-frontend/dist; try_files $uri $uri/ @router; index index.html; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods *; } location @router { rewrite ^.*$ /index.html last; } } Here is my Vue.js code that has the 'CORS' problem. main.js Vue.prototype.API = api Vue.prototype.GLOBAL = global Vue.prototype.$axios = Axios; Axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded' Axios.defaults.headers.post['Content-Type'] = 'multipart/form-data' redirect.vue <template> <div id="notfound"> <div class="notfound"> <div class="notfound-404"> <h1>Redirect</h1> </div> <h2>Wait a few seconds, page is redirecting</h2> <p>You are logging...authorization code is {{code}}</p> </div> </div> </template> <script> export default { name: 'redirect', data(){ … -
Django Form doesn't get password
I'm trying to make a user registration views using django forms. I looked online, but nothing I found can help me; or probably I can't get the reasoning, so a explanation is welcome. I changed the standard user with a custom class named "Utente" (Italian name) View function is a simple one that configure "context" dict to be passed to template, so that form or confirmation or error can be notified. views.py def registrazione(request): context = {} if request.method == 'POST': context.update({ 'stato':'post'}) form = UtenteChangeForm(request.POST) if form.is_valid(): print("--FORM\n",form.cleaned_data,'\n-------') utente = Utente.objects.create_user(**form.cleaned_data) print("---UTENTE\n", utente) login(request, utente) if utente is not None: context.update({'utente':utente.username}) else: print('ERROREEEEEEEEEEEE') else: context.update({ 'stato':'errore' }) else: # GET form = UtenteCreationForm() if request.user.is_authenticated: context.update({ 'stato':'loggato' }) else: context.update({ 'stato':'anonimo'}) context.update({'form':form }) return render(request, 'profilo/registrazione.html', context) The form should extends the standard user creation form. forms.py lass UtenteCreationForm(UserCreationForm): username = forms.CharField(min_length=5) email = forms.EmailField(min_length=5) first_name = forms.CharField() last_name = forms.CharField() data_nascita = forms.DateField(input_formats=['%d/%m/%Y']) cellulare =forms.RegexField(regex=r'^\+?\d{9,15}$') residenza = forms.CharField(min_length=5) class Meta(UserCreationForm): model = Utente fields = ('username','first_name', 'last_name', 'email', 'data_nascita', 'cellulare', 'residenza') The print of form.cleaned_data put in stdout (one for all): --FORM {'username': 'thomas', 'email': 'thoma@g.com', 'cellulare': '3341193124', 'residenza': 'viq culonia', 'password': None} First Problem why password is … -
Redirecting login page to home page when user is logged in using django 2.2
I want to redirect users to the homepage when they already logged in and tried to access the login page again. I am using django 2.2. I tried to use user.is_authenticated but it didn't work {% block content %} {% if user.is_authenticated %} {% block chess_page %} {% endblock %} {% else %} <div id="logo"> <img src="../../static/img/chess-logo.jpg" name="logo-pic"> <h2>Chess</h2> </div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endif %} {% endblock %} chess_page is the homepage I want to redirect to -
Store Uploaded CSV to Browser Storage
Any way we can store CSV file in Browser Storage and retrieve it later and process in the backend. Issue: I want to add Import Question Button to Django admin Form View. It works fine if the record is already saved. In case of the new record, if csv file selected and some of the fields are not validated, then Django auto reload while saving the record and due to that selected csv is cleared. -
Django Models not working: module 'django.contrib.admin' has no attribute 'Modeladmin'
I am making a eCommerce website from a youtube tutorial and I have an error that is really bugging me around. I tried google but it didn't work. Then I tried messing with Django but that made it worse, so I changed it back. This is the code for admin.py: from django.contrib import admin # Register your models here. from .models import profiles class profileadmin(admin.Modeladmin): class Meta: model = profiles admin.site.register(profiles, profileadmin) The full error message is this: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03ED28A0> Traceback (most recent call last): File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\roche\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in … -
On Windows in the "settings.py" file not getting the environment "os.environ" variables in Django
on Windows in the settings.py file not getting the environment variables in Django but working file in Ubantu. -
Filters with Django and jQuery
I was trying to add some filters to a project that I'm currently working on to filter videos by year, genre, language, and quality: year, language and quality filters work just fine so I removed their code. When it comes to the genre I have a field in the model called tags which is a comma separated values. so for example, if the value is 'action, comedy, drama' and someone is looking for a genre of 'comedy' I want them to be able to find it from these tags. Django code: videos = Media.objects.order_by( '-date').filter(is_published=True) if 'genre' in request.GET: genre_tags = request.GET['genre'] if genre_tags: genre_tags = videos.filter(tags=genre_tags) context = { 'medias': paged_movies, 'values': request.GET } return render(request, 'media_files/listing.html', context) HTML code: <select class="filter-genre"> <option value="">All</option> <option {% if values.genre == 'action' %} selected {% endif %} value="action">Action</option> <option {% if values.genre == 'adventure' %} selected {% endif %} value="adventure" >Adventure</option> <option {% if values.genre == 'animations' %} selected {% endif %} value="animations" >Animations</option> <option {% if values.genre == 'crime' %} selected {% endif %} value="crime" >Crime</option> <option {% if values.genre == 'horror' %} selected {% endif %} value="horror" >Horror</option> <option {% if values.genre == 'documentary' %} selected {% endif %} … -
How to Deploy Django app with ChannelNameRouter
I am using django-private-chat in one of my application. it starts the chatserver on running command python manage.py run_chat_server please help me deploying it on production server to run the chat server automatically. i have tried adding the ChannelnameRouter class in routing.py of my project application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ # path("notification_u/", UserNotificationConsumer), ]) ), "chat-channel":MessageRouter(), }) -
Unable to call custom template tag
In a html page, I'm trying to call django custom template tag but it seems to me that its never reaching that template tag function. home.html page {% load custom_tags %} {% if has_profile %} <p> Creator </p> {% else %} <li><a href="{% url 'update_profile' %}" class="btn btn-simple">Become a Creator</a></li> {% endif %} custom_tags.py from django import template from users.models import Profile register = template.Library() @register.simple_tag def has_profile(): return 1 Please let me know if you need any information. Thanks! -
Django All_auth/rest_auth e-mail address validation using HTTP GET request
I use Django all_auth and rest_auth for a backend service of a mobile app. I integrated the registration and login API and all works fine. Now I have to integrate the e-mail address validation logic. After the registration (without social), I have to send an e-mail with the link that the user will use to validate your account. I added this configurations into my Django settings: ACCOUNT_EMAIL_VERIFICATION = 'mandatory' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' Also this works fine. I'm able to receive the e-mail after the registration of a new account. In the received e-mail I have the link to validate the account also. I would like to have the validation of the e-mail when the user simply will click on the link. So, I would like to use only the GET HTTP method. I added, as suggested into the documentation, this setting also: ACCOUNT_CONFIRM_EMAIL_ON_GET = True I use this url linked to the all_auth views. But, if I try to click on the link from the received mail, I obtain this error: KeyError at /account-confirm-email/NzU:1hjl8A:z5Riy8Bjv_h0zJQtoYKuTkKvRLk/ 'key' /allauth/account/views.py in get self.object = self.get_object() ... ▶ Local vars /allauth/account/views.py in get_object key = self.kwargs['key'] ... ▶ Local vars This seams that setting is … -
DJANGO Queryset filter according to inner calculations on nested model
I have a model with the following fields: required_visits : a positive integer person - another model with: name,age,curr_week_visits I would like to filter all the rows in which the following calculation is true: required_visits__minus__person__curr_week_visits__gt=0 in words: the model's required visits minus the person's current weeks visits is bigger than 0 What is the right way to write this filter queryset? -
How can you make a django model which can be displayed on the main page and not on admin page
i'm just doing some studying regarding django and finished a crashcourse on django, in the crashcourse he only showed how to display a Model on the admin page but what if I want a user to use the model and not specifically a admin? E.g what if I want anyone that visits /todo/ to be able to add a todo and not make the todo only be addable by the admin panel. -
Event listener works in on context but not another - code identical, and no errors observed. Possible causes?
I'm bamboozled. I use a select2 widget on a web page, implemented by django-autocomplete-light, and I attach an event listener to the it as follows: const game_selector = $("#"+id_prefix+"game"); game_selector.on("change", switchGame); Works a charm. I select a new game in the select box and the switchGame function is called. That is running on Django development server with manage.py runserver. And I can see how groovy this is in Chrome's debugger: There it is, switchGame(event) is the handler. And it all works too. No drama. But I publish the code to my webserver and suddenly it doesn't work. The event listener never fires. switchGame is never called. It's serving the self same code, looks the same in the client and in Chrome's debugger. All fine. I can even see the event listener is attached, albeit the order is different: Severed by the development server there there is a select2 handler above switchGame in the list and served from the production server the same select2 handler is listed below the switchGame handler. Can the order matter? And why would the order differ? In the end I am looking at the same binding code above, and I can set a breakpoint inside switchGame … -
I want to include Email in signup.html so that users can request to reset password in password_reset_form.html
I was creating a Login Page using Django through a tutorial. While signing up first time through "py manage.py createsuperuser" it asked for email. Than i created the password reset page, and the signup.html page. When i reset a password it sends email to the registered email of my email. When i created a user in the signup.html, it did not ask for email. How would i code it to ask for email so that we can use the password reset option for every user. -
How to create temporary array hotel Check-In list in Django?
I am trying to create a temporary table of people who are Checked-In in Hotel, is there any way of creating a temporary array of elements in Django? -
Do websockets send and receive full messages?
I am new to web development and I am trying to write a simple web game using python and django for my server with some javascript for the front end graphics. I am using the channels package to use websockets for the communication and I have a little question about websockets. In python, I know that when we use sockets, the message isn't guaranteed to be sent fully. For example, if I use socket.send in python, I may not send the entire message and in that case I need to resend what is left, and on the receiving side, I am not guaranteed to get the full message using socket.recv (assuming the bufsize argument is big enough for the full message), so I have to keep calling recv until I get the entire message. My question is: Is it the same with websockets or not? I tried looking for this in the MDN docummentation and in google, but I couldn't find any information on this. In addition, every example I have seen online didn't take this into account, so it seems like what I send with socket.send (in javascript) is exactly what I get on the other end and vice … -
How to filter in DRF ListAPIView using django_filters FilterSet on JSONField field
i want to make an API request in Django Restframework like http://localhost:8000/apis/services/?page=1&name=2 The model from django.contrib.postgres.fields import JSONField class Service(models.Model): name = JSONField(default=dict) The APIView class DashboardServicesAPIView(ListAPIView): queryset = Service.objects.none() serializer_class = ServiceSerializer permission_classes = (AllowAny,) filter_class = ServiceFilter def get_queryset(self): return Service.objects.all() The FilterSet class ServiceFilter(django_filters.rest_framework.FilterSet): name = django_filters.CharFilter(field_name="name", lookup_expr='icontains') class Meta: model = Service fields = [ "name"] querying with filter querystring is not working the same result is always returned. Any help on what i missed dealing with JSON? -
Change subprocess Popen from file to `Django InMemoryUploadedFile`
I have a function that require filename as an input argument and return list of str. import subprocess def get_length(filename: str) -> typing.List[str]: result = subprocess.Popen(["ffprobe", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return [x.decode('utf-8') for x in result.stdout.readlines() if "Duration" in str(x)] In the Django application. I use it with InMemoryUploadedFile. My quick solution is write down a file to disk and read it to the function. Question: Is it possible to let my get_length() read from the InMemoryUploadedFile rather than physical file`? -
Django rest "this field is requiered" on a many to many field when blank=True
I have an object I would like to be able to make via django-rest-api UI. This object has a manytomany field that holds other objects on it. Even though that field is blank param is set to True, I get a response that "this field is requiered". class Post(models.Model): title = models.CharField(max_length=100) slug = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True) content = HTMLField('Content', null=True) black_listed = models.ManyToManyField('profile_app.Profile', related_name='black_listed_posts', blank=True) score = models.PositiveIntegerField(null=True, default=0, validators=[MaxValueValidator(100)]) serializers.py: class PostSerializer(serializers.HyperlinkedModelSerializer): black_listed = ProfileSerializer(many=True) read_only = ('id',) def create(self, validated_data): self.black_listed = [] class Meta: model = Post fields = ('id', 'title', 'slug', 'description', 'content', 'black_listed', 'score') views.py: class PostViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() lookup_field = "slug" def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.black_listed = [] if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) As you can see, i tried overriding the create() method on both serializer and viewset, but that didnt work and still gave me that the black_list field is requiered. What i expected that if the field is not required in the db, then the serializer can set it to None on the creation what am i missing here?