Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnicodeDecodeError when using django serializers
I have a custom django user model and a "Photo" model with Foreign Key as "CustomUser" model: class CustomUser(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' objects = CustomUserManager() email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=10) bio = models.CharField(max_length=240, blank=True) city = models.CharField(max_length=30, blank=True) profile_pic = models.ImageField(null=True, blank=True) date_of_birth = models.DateField(blank=True, null=True) def __str__(self): return self.email and class Photo(models.Model): image = models.ImageField(blank=False, null=False, upload_to="images") author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) title = models.CharField(max_length=200) def __str__(self): return self.title I am trying to get the 'profile_pic' field (defined in CustomUser) from Photo Serializer but i get an utf-8 error. error image Photo Serializer: class PhotoSerializer(ModelSerializer): email = serializers.SerializerMethodField('get_user_email') username = serializers.SerializerMethodField('get_username') profile_pic = serializers.SerializerMethodField('get_profile_pic') class Meta: model = Photo fields = ['id', 'author','image', 'title','email', 'username', 'profile_pic'] def get_user_email(self, photo): email = photo.author.email return email def get_username(self, photo): username = photo.author.username return username def get_profile_pic(self, photo): photo_url = photo.author.profile_pic return photo_url If I replace get_profile_pic with the following code below, it gives the correct image url. But is there any other way to do it? Also I would like to know the reason for the error. def get_profile_pic(self, photo): request = self.context.get('request') photo_url = photo.author.profile_pic photo_url = 'media/' + str(photo_url) return request.build_absolute_uri(photo_url) -
Broadcasting with self.channelr_layer.group_send does not send to all users
I am trying to make a chat application between two users using a WebsocketConsumer. When connecting, both users pass on the same "room_name". Everything is working except broadcasting a new message to all channel_layers in the group. When I try to broadcast the new message to all users in the group, only the last connected user gets the broadcast, but twice. The connect method in consumer.py def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() Broadcasting method in consumer.py def send_chat_message(self, message): print("This should broadcast to everyone connected.", message) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) Method to pass message to websocket def chat_message(self, event): message = event['message'] self.send(text_data=json.dumps({ 'message': message })) -
Nginx Reverse Proxy with Gunicorn Treats Site Names Differently
We have a Django project that is served in production using Nginx and Gunicorn reverse-proxy setup. Everything seems to work except for one small detail. Somehow, the browser "sees" the following addresses as different sessions. Suppose I log into the site using the example.com address. Then, if I visit www.example.com, the browser does not see that the user has logged in. My suspicion is that this has something to do with the way Nginx or Gunicorn are setup. Any help on how to resolve this discrepancy is appreciated. Nginx config: server { root /home/example/mysite; # Add index.php to the list if you are using PHP index index.html index.htm; server_name example.com www.example.come; client_max_body_size 512M; location /static/ { alias /home/example/mysite/static/; expires 30d; add_header Vary Accept-Encoding; access_log off; } location /media { alias /home/example/mysite/media/; expires 30d; add_header Vary Accept-Encoding; access_log off; } location / { # try_files $uri $uri/ =404;# proxy_pass http://127.0.0.1:8080; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; proxy_connect_timeout 6000; proxy_send_timeout 6000; proxy_read_timeout 6000; send_timeout 6000; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /home/ubuntu/ssl/example_com_chain.crt; ssl_certificate_key /home/ubuntu/ssl/server.key; #include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot #ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by … -
Unknown format code 'g' for object of type 'str'
I am trying to implement a simple function of float numbers and I got this error: Unknown format code 'g' for object of type 'str. What is the cause of this and how do I resolve this. from django import template register = template.Library() @register.filter def human_format(num): num = float('{:.3g}'.format(num)) magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude]) -
How do you join multiple model on a foreign key field using django ORM?
Want to join three tables and get data. Where model_c and model_b have a foreign key to model_a. But all model does not have a foreign key class Model_A(models.Model): name = models.CharField() class Model_B(models.Model): model_a = models.ForeignKey(Model_A) name = models.CharField() class Model_C(models.Model): model_a = models.ForeignKey(Model_A) name = models.CharField() Want query as below. SELECT * FROM model_c JOIN model_a ON model_a.id = model_c.model_a JOIN model_b ON model_a ON model_a.id = model_b.model_a; -
Saving records in related models using Django views and Ajax
I have been trying to update related model objects in Django app using Ajax. In order to update a model I have used the following view and the records save without problem. However, on similar lines, if I try to save data in related models (i.e. to save Django inline formset data) nothing seems to be working (unable to find solution to my predicament on the web including SO). The following is the set up for saving records in one model: My views.py class CreateViewFactorA(CreateView): template_name = ... model = ModelFactorA form_class = FormCreateFactorA # AJAX FUNCTION ******************* def postFactorA(self, *args, **kwargs): if self.request.is_ajax and self.request.method == "POST": form = self.form_class(self.request.POST) if form.is_valid(): instance = form.save() ser_instance = serializers.serialize('json', [ instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": ""}, status=400) My template $('#PostFactorA').submit(function(e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ url: "{% url 'factora_create' %}", type: 'POST', dataType: 'json', data: serializedData, success: function(response) { console.log('Data Saved'); }, error: function (response) { alert(response.responseText); } }); }); I am trying to use the Ajax post in order to avoid page reload. What changes are needed in the view (as above) so that the formset data may be … -
Make message disappear after several seconds
I'm displaying error messages on the screen and i want these messages to disappear after X seconds. I'm using a simple script that works if one message is displayed on the screen. If two messages are displayed, see example below, only the first message is disappeared, the second one remains on the screen. How can i remove both messages? I'm using this script: setTimeout(function() { $('#message').fadeOut('slow'); }, 15000); Script that produces the messages. {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div id="message"> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button> {{ error|escape }} </div> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button> {{ error|escape }} </div> {% endfor %} {% endif %} Thank you for help. -
Why django-admin is throwing error in cmd?
I am trying to install django in my newly installed windows 10. When i run pip install django it says requirements already satisfied, but when i run django-admin then it throws some error in comand prompt. Here is the message i'm getting when i run django-admin django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException here is the screenshot of what i'm talking about -
Broadcast a message to everyone periodically using Django channels
I'm new to Django channels. I created a WebSocket and I want to send some info to every user periodically. Each user connects to my WebSocket when goes to my website and see the info on top of each page. I have no idea whether it is necessary to create a group or not. But how can I send info to every visitor periodically? May be something like this: class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) await self.channel_layer.group_send( { "text": 'Hello user!' } ) # OR await self.send({ "type": "websocket.send", "text": 'Hello user!' }) Thanks in advance... -
Passing variables to a container on startup
I want to setup my Django app in kubernetes environment in such a way that while creating the app container, environment variables are passed such that those environment variables are used to initiate the containers. For example on starting the app container I want to issue management commands such as python manage.py createuser --lastname lname --firstname --fname --number --num " and so on. How to pass these variable values such as lname and fname above inside the container in a generic way such that every time new values can be passed depending on the user credentials and they do not need to be hard coded everytime? -
Rest Framework - How to apply field-level permissions after create/update?
I have implemented field-level permissions by overriding get_fields() as follows: def get_fields(self): viewable_fields = {} fields = super().get_fields() request = self.context.get('request', None) model = self.Meta.model model_name = model._meta.model_name try: user = request.user except AttributeError: return viewable_fields for field_name in fields: if user.has_perm('view_' + model_name + '_' + field_name): viewable_fields[field_name] = fields[field_name] return viewable_fields That works fine for list and detail views, but when I tried to apply that mixin to create/update views, the nested fields were empty. I have removed it from create/update views, but then I get all fields returned after the operation is completed. For example, there's an "internal_notes" field that users with "team" group can view, but others cannot. If I "patch" an update by one of the users who cannot view that field, the "internal_notes" field is returned after the update process completes. Note that I do not pass the "internal_notes" field in the update. I do partial updates (with PATCH), so in my test I only passed "initials" as the field to change. Here's an edited version (some fields omitted for brevity) of the result from a detail view. Note: no "internal_notes", which is correct. "results": { "id": 1, "client": "Acme Honey", "url": "http://demo1.mysite.api/clients/team/1/", "team_member": … -
React Native + Django DRF network error on POST
I'm developing a React Native app. As a backend I'm using DJango DRF. I'm trying to make POST request for creating a new element on backend, this is my code in React: **API.JS** const routes = { accounts: { get: () => requestHelper({ method: "get", url: "accounts/", }), post: (data) => requestHelper({ data, method: "post", url: "accounts/", }), }, }; **API CALL** const formData = new FormData(); const image = { uri: data.image, name: data.timestamp + ".jpg", type: "image/jpeg", }; _.map(data, (item, name) => { formData.append(name, item); }); formData.append("image", image); await api.accounts .post(formData) .then((res) => { console.log(res, "OK"); }) .catch((err) => { console.log(err); }); }; Te request is reaching backend and the new Account is being created on database (including the image). The problem is that,despite that Django is returning 200_OK, the api call is going to the catch statement, and this error appears on console: Network Error Stack trace: node_modules/axios/lib/core/createError.js:15:0 in node_modules/axios/lib/adapters/xhr.js:81:4 in dispatchXhrRequest node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent node_modules/react-native/Libraries/Network/XMLHttpRequest.js:575:10 in setReadyState node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0 node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue [native code]:null in callFunctionReturnFlushedQueue I think is an Image problem, because I've removed for testing and same error appears. Could you … -
Calling view with template in another app view django
I have a Django project with two Django apps. one as post which both have views called index. I tried using index view of the post app from the index view of the user app. but the get a TemplateDoesNotExist Error -
Facing an issue while trying to apply filter function in get method for django rest framework
Serializers.py class book_detailsSerializer(serializers.ModelSerializer): class Meta: model = book_details fields = '__all__' views.py class book_detailsList(APIView): def get(self,request): book = book_details.objects.all() b_serial = book_detailsSerializer(book) return JsonResponse(b_serial.data) class book_details(models.Model): bookid = models.CharField(max_length=10) booktitle = models.CharField(max_length=20) category = models.CharField(max_length=10) author = models.CharField(max_length=20) availability = models.BooleanField() no_of_copies = models.IntegerField() issuable = models.BooleanField() 1.while trying to return all the books that can be issued facing issue, "AttributeError at /details/isssuable/" where details/issuable is url path 2.Actual error: Got AttributeError when attempting to get a value for field bookid on serializer book_detailsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'bookid'. Request Method: GET Request URL: http://127.0.0.1:8000/details/isssuable/ Django Version: 3.1.2 Exception Type: AttributeError Exception Value: Got AttributeError when attempting to ?get a value for field bookid on serializer book_detailsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'bookid'. -
Cronjob running only once in Django
I'm trying to do a cronjob for a Django application using the django-cron lib. The problem is that the cronjob only runs once and it should run every minute. class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS, retry_after_failure_mins=RUN_EVERY_MINS) code = 'myapp.my_cron_job' def do(self): # My code To get around this, I also tried to create the cronjob via crontab, but it didn't work either. */1 * * * * source /home/me/.baschrc && source/me/Documents/project/app/source/bin/activate && python source/me/Documents/project/app/manage.py runcrons > source/me/Documents/project/app/cronjob.log -
Single object value from django ORM
If we want to fetch only one field from a single entry, which query is more efficient, or are they generating the same MySQL query internally? Person.objects.only('first_name').get(pk=1).first_name Person.objects.get(pk=1).first_name Is the first query fetching the entire content of the row or just the single field first_name? -
Error while transferring data from sqlite to my sql
Error Name- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I have given the commandpython manage.py dumpdata > datadump.json than I have given the command python manage.py loaddata datadump.json and I got mentioned Error. -
Is it possible to integrate Zoom API into the django project [closed]
I would like to ask if it is possible to integrate the Zooma API into the django project, if there is such a thing and one of you knows maybe a tutorial or a tutorial video I would appreciate -
Django: Getting Interface Error, Exception Value: (0, '') when using remote MySQL DB but not local DB
Trying to login to my app, I am getting this error when I am using a MySQL DB hosted remotely but not when I am connecting to my locally hosted XAMPP one. I've read a couple entries on my question but they mostly mention cursors that aren't explicitly closed, which I don't need to since I am using with in all my raw queries. I am using django-allauth for my authentication. Traceback: Environment: Request Method: GET Request URL: http://localhost:8000/accounts/login/?next=/ Django Version: 3.1.2 Python Version: 3.8.6 Installed Applications: ['ewhale_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'users.apps.UsersConfig', 'pages.apps.PagesConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) The above exception ((0, '')) was the direct cause of the following exception: File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Ej\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", … -
Django rich text editor inside django template not for Admin
How can I set rich text editor inside Django Template without using crispy form {{form.media}}. I am not using crispy form right now. What to do. -
Roles in Django
I'm creating web based system, where I have 5 or 6 different roles and access type. I made a research how to achieve this and everything is made only when create group in django admin and assign user into it but only from the administrative part. I need to create this from the views. I already have a form to add users with email and drop down menu to set the role type. Any suggestions will be appreciated, because till now I don't have idea how to achieve this without to assign the users from django admin. my model.py for users: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must … -
Custom Django-Allauth SignUp form not adding new users
I tried to create a custom Signup Form with allauth but when I submit the form on the frontend it directs to the success_url and upon inspection in the admin panel a new user wasn't created. # forms.py from allauth.account.forms import SignupForm class SimpleSignupForm(SignupForm): mobile_number = PhoneNumberField(required=True) first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, required=True) address = AddressField(required=True) type = forms.ModelChoiceField(queryset=UserType.objects.all()) def save(self, request): user = super(SimpleSignupForm, self).save(request) user.mobile = self.cleaned_data['mobile_number'] user.address = self.cleaned_data['address'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.type = self.cleaned_data['type'] user.save() return user def __init__(self, *args, **kwargs): super(SimpleSignupForm, self).__init__(*args, **kwargs) visibles = self.visible_fields() visibles[0].field.widget.attrs['class'] = 'form-control' # settings.py ACCOUNT_FORMS = {'signup': 'my_app_path.forms.SimpleSignupForm'} On the template file I made sure the <form> tag has method='POST' and that I included {% csrf_token %} in the form. The button is also a a submit type. I've also made sure {{ form.as_p }} has all the required fields when submitting. There are no errors or warnings popping up anywhere. -
Non-ASCII characters are not correctly displayed in PDF when served via HttpResponse
I have generated a PDF file which contains Cyrillic characters (non-ASCII) with ReportLab. For this purpose I have used the "Montserrat" font, which support such characters. When I look in the generated PDF file inside the media folder of Django, the characters are correctly displayed: However, when I try to serve this PDF via HttpResponse, the Cyrillic characters are not properly displayed: The code that serves the PDF is the following: # Return the pdf as a response fs = FileSystemStorage() if fs.exists(filename): with fs.open(filename) as pdf: response = HttpResponse( pdf, content_type='application/pdf; encoding=utf-8; charset=utf-8') response['Content-Disposition'] = 'inline; filename="'+filename+'"' return response I have tried nearly everything with success. Actually, I do not understand why, if ReportLab embeddes correctly the font (local file inside media folder), the file provided to the browser is not embedding the font. -
stop or kill thread in python
I am creating a function that creates threads. if I recall the function running threads should be terminated. and new threads should be created. def callme(): t1 = thread(target=somefunction, args=(,)) t2 = thread(target=somefunction, args=(,)) t1.start() t2.start() t1.join() t2.join() def somefunction(): for i in range(10000000): print(i) callme() #callme1 sleep(2) callme() #callme2 if I callme1 than 2 threads should be created after 2 seconds I call callme2 then, threads of callme1 should be killed or stopped. and 2 threads of callme2 runs I am using some kind of this technique in Django if I fetch the URL than some view function calls, which contains these types of thread structures. -
'function' object has no attribute 'all' which was working fine before
My code was working fine before now, all of a sudden is starts to show 'function' object has no attribute 'all', its an api, this is the serializers and error is from the return statement return OrderItemSerializer(obj.items.all(), many=True).data class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() total = serializers.SerializerMethodField() coupon = serializers.SerializerMethodField() class Meta: model = Order fields = ( 'id', 'order_items', 'total', 'coupon' ) def get_order_items(self, obj): return OrderItemSerializer(obj.items.all(), many=True).data What do i do?