Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I run my django server from pycharm?
im wondering how I run django server from pycharm? I dont know where I should run it. Does someone know? Beginning programmer -
Python join not giving back comma separated string [duplicate]
I have a Django query that returns me an array of strings. I am trying to convert them into a comma separated string. array_string = "['xyz2005.test.com', 'xyz2006.test.com']" (Pdb) joined_string = ",".join(array_string) (Pdb) joined_string "[,',x,y,z,2,0,0,5,.,t,e,s,t,.,c,o,m,',,, ,',x,y,z,2,0,0,6,.,t,e,s,t,.,c,o,m,',]" I was expecting: xyz2005.test.com, xyz2006.test.com What am I doing wrong? -
How do I add a context in django class based view
I want to add context to a class based view in django. How do I do that? from django.views.generic import ListView from .models import Post class PostDetails(ListView): model = Post context_object_name = "post" # How do I add another context? -
Django collectstatic command fails in AWS Elastic Beanstalk Amazon Linux 2 Python 3 platform
I've been struggling for several days now to deploy my Django application to Elastic Beanstalk using the Amazon Linux 2 Python 3.7 platform. After managing to deploy the app I can't run the command python3 manage.py collectstatic --noinput in order for nginx to be able to serve the static files and thus have all the necessary CSS styles for the Django Admin page. Right now I have a file named "static.config" in the .ebextensions directory that has the following YAML code: container_commands: collectstatic: command: | source $PYTHONPATH/activate python3 manage.py collectstatic --noinput I added the line source $PYTHONPATH/activate after the first failed attempt following this answer. I also have a file named "01_python.config" with the following code: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "backend_project.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: backend_project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:proxy:staticfiles": "/static/": "static/" This is the stacktrace I'm seeing in the cfn-init.log: 2020-11-04 14:06:29,217 [ERROR] Command collectstatic (source $PYTHONPATH/activate python3 manage.py collectstatic --noinput ) failed 2020-11-04 14:06:29,218 [ERROR] Error encountered during build of postbuild_1_eduvaluer_api: Command collectstatic failed Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 542, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python2.7/site-packages/cfnbootstrap/construction.py", line 260, in build changes['commands'] = CommandTool().apply(self._config.commands) File "/usr/lib/python2.7/site-packages/cfnbootstrap/command_tool.py", line 117, in apply raise ToolError(u"Command %s failed" % name) … -
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 …