Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to update one only one field
I'm working on a small project using Django / Rest Framework. I would like to update my table ( since I have already some rows ) I want to update only one column status but I get an error about other fields are required: how can I update only one field, exactly status, I want to set the status to 1, without updating the other columns, (Django keep telling me other fields are required like title, mobile) this is my code : obj = Task.objects.filter(id=tasks['id']).first() serializer = self.serializer_class(obj, data = {'status':1}) if serializer.is_valid(): serializer.save() -
How can I traverse through two list concurrently in one for loop using in django templates to be implemented in a chatbot app
So I am trying a chatbot application where the user will take a user string response and after that, the chatbot will throw a reply. Meaning that it should be able to traverse in two string lists user_response and chat_response in one for loop. The problem that I am having is that I have no idea how to implement this in Django that suits the way I need to implement it. I should implement it this way: {% for chat in user_chat#<-not sure here %} <div class="chat self animated slideInUp fast"> <div class="user-photo"> <img src="{% static 'images/account_200px.png'%}"alt="Self"></div> <div class="chat-message">{{ user_chat }} </div> </div> <div class="chat friend animated slideInUp fast"> <div class="user-photo"> <img src="{% static 'images/icon-at.png'%}"alt="Dog"></div> <div class="chat-message"> {{ response #<-the response from system|safe}} </div> </div> {% endfor %} Meaning in that one instance of a loop I should be able to render two divs with different classes that obviously have different messages that came from two different string lists. Like for loop{ render(user_chat) render(system_response) } Which in turn should produce this kind of response Given that: user_chat = ["Hi", "I am okay", "good!"] system_response = ["How are you", "How Okay are you?", "Oh that's great to hear"] Will make Hi … -
I have a static react app in Django DRF app. I want to pass a url with parameters to my react static app. But Django catches my reuest url
mysite.org/donate/27/99/3cdb23510af9f36aac7e7b741f8deddc482c5e25 I want to pass this to my react app url.py urlpatterns = [ path('', index, name="index"), path(r'posts',index,name="index"), path(r'donate/$/$/$',donate,name="donate"), # path(r'/',index, name="index"), # path(r'/$', index, name="index"), path('admin/', admin.site.urls), path('api/v1/', include('posts.urls')), path('api/profiles/', include('posts.profile_url')), path('api/likes/', include('posts.like_url')), path('api/follows/', include('posts.follow_url')), path('api/comments/', include('posts.comment_url')), path('api/volunteers/', include('posts.volunteer_url')), path('api/donates/', include('posts.donate_url')), path('api/bids/', include('posts.bid_url')), path('api/locations/', include('posts.location_url')), path('api-auth/', include('rest_framework.urls')), path('api/v1/dj-rest-auth/', include('dj_rest_auth.urls')), path('api/v1/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('swagger/', schema_view.with_ui( # new 'swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui( # new 'redoc', cache_timeout=0), name='schema-redoc'), path('api/login/', CustomAuthToken.as_view(), name='login'), path('api/register/', CreateUser.as_view(), name='register') ] views.py from django.contrib.auth import get_user_model from rest_framework import viewsets # new from .models import Profile from .models import Post from .models import Like from .models import Follow from .models import Comment from .models import Volunteer from .models import Donate from .models import Bid from .models import Location from rest_framework import serializers from django.shortcuts import render #frontend from .permissions import IsAuthorOrReadOnly from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from .serializers import ProfileSerializer, PostSerializer, UserSerializer, LikeSerializer, FollowSerializer, CommentSerializer, VolunteerSerializer, DonateSerializer, BidSerializer, LocationSerializer # new def donate(request): return render(request, "build/index.html") def index(request): return render(request, "build/index.html") I have a static react app in build folder that is accepting request in my local env with integration with django. If django is accepting all the url requests. How can I forward … -
method_descriptor object has no attribute 'now' - while returning in function
while running the below snippet the error is thrown on datetime.time.now() Error msg : method_descriptor object has no attribute 'now' from datetime import datetime def samplefun(file_path, max_width=0, width=0, height=0): file_dir = _get_file_dir(file_path) file_name = _get_file_name(file_path) return f"{file_dir}/thumbnails/{max_width}/pro_pic{datetime.time.now()}.jpg" -
django rest framework generate file link from frontend(8000) domain not backend(8080)
I'm using DRF for backend and React for frontend. In DRF I return link to my local saved file. Django application takes 8080 port and react 8000. And when I create Request from Frontend, DRF return path to file with localhost:8000/media/... I need localhost:8080/media/... -
Clashing reverse accessors and queries in Django for many to many field?
from django.db import models class Appointment(models.Model): doctors = models.ManyToManyField('Doctor', through='AppointmentAccess', related_name='appointments') class Doctor(models.Model): appointments = models.ManyToManyField('Appointment', through='AppointmentAccess', related_name='doctors') I get the following error: core.Appointments.doctors: (fields.E302) Reverse accessor for 'PatientProfile.users' clashes with field name 'Doctor.appointments'. HINT: Rename field 'Doctor.appointments', or add/change a related_name argument to the definition for field 'Appointment.doctors'. core.Appointment.doctors: (fields.E303) Reverse query name for 'Doctor.appointments' clashes with field name 'Appointment.doctors'. HINT: Rename field 'Doctor.appointments', or add/change a related_name argument to the definition for field 'Appointment.doctors'. core.Doctor.appointments: (fields.E302) Reverse accessor for 'Doctor.appointments' clashes with field name 'Appointments.doctors'. HINT: Rename field 'Appointment.doctors', or add/change a related_name argument to the definition for field 'Doctor.appointments'. core.User.patient_profiles: (fields.E303) Reverse query name for 'Doctor.appointments' clashes with field name 'Appointments.doctors'. HINT: Rename field 'Appointments.doctors', or add/change a related_name argument to the definition for field 'Doctor.appointments'. Why? Can someone help me understand this error? The many to many field should be kept track of through the AppointmentAccess table instead of generating a new intermediary table. How does the related name appointments clash with doctors? -
How to NOT override context in Django DetailView with get_context_method?
I use get_context_method in my DetailView class to get a pk value needed for my query. But now I cant get object values in my template, cause get_context_method just override them. Is there any other way to get a pk key in DetailView? Or how to not override object values? In other words, how to make this work properly? ##views.py class UserDetailView(DetailView): model = User def get_context_data(self, **kwargs): context = super(UserDetailView, self).get_context_data(**kwargs) id = int(self.kwargs.get('pk')) props = Statistics.objects.filter(user=id, property=100) extra_context = {'user_property':props} return extra_context Template: div class="container"> <div class="col-sm-6"> <h1>{{ object.user.full_name }}</h1> <h5>Property</h5> <div class="flex-container"> <div class="flex-scores"> <ul class="scores"> <li>{{user_property}} </div> </ul> </div> </div> -
Python How to get the dates of the weeks?
Let say in the month of April, in week-1 dates will start from April 1 to April 7, then week-2 would be April 8 to April 14, week-3 would be April 15 to April 21, then April 22 to April 28 for week-4. But there is still 2 remaining days because the end date of April is 30. My question now is, how can i get the April 1, 2, 3, 4, 5, 6, and 7 in week one? Then April 8, 9, 10, 11, 12, 13, 14 in week two, and etc.? -
django preview generator for s3 bucket
i am using django preview generator to generate thumbnail of a pdf and it is working fine in local path = settings.BASE_DIR cache_path = str(path) + '/media/thumbnail' manager = PreviewManager(cache_path, create_folder=True) img_obj = serializer.file_uploads.url url = str(path) + str(img_obj) pdf_or_odt_to_preview_path = str(url) path_to_preview_image = manager.get_jpeg_preview(pdf_or_odt_to_preview_path) but when using s3 bucket it is unable to detect the directory of uploaded file my s3 bucket setting is: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') # AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'edubook.s3boto3.CustomS3Boto3Storage' AWS_S3_REGION_NAME = 'ap-south-1' AWS_S3_CUSTOM_DOMAIN = 'https://abc.s3.amazonaws.com/' -
Accessing Forienkey objects from the queryset recieved through AJAX
I ask for a queryset from my views.py on a AJAX request in django. The model in use has a foriegnkey field which is related to User. I am not able to access those foreignkeyed elements. My views.py looks like this @csrf_exempt def replies(request): if request.is_ajax and request.method == "POST": cid = request.POST.get('cid', None) data = { 'replies': serialize("json", Comment.objects.filter(replyTo=cid[1:])) } return JsonResponse(data) My model Comment looks like this class Comment(models.Model): commenter = models.ForeignKey(User, on_delete=models.CASCADE) cid = models.UUIDField(default=uuid.uuid4, editable=False) commentText = models.TextField() likes = models.ManyToManyField('User', related_name='likes') commentOn = models.ForeignKey(Article, related_name='commentOn', on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(default=timezone.now) replyTo = models.UUIDField(null=True, blank=True) def __str__(self): return f'{self.commenter.first_name + " [" + str(self.likes.count()) + "]"}' and the my ajax request looks like this $.ajax({ type: 'POST', url: '{% url 'replies' %}', data: { 'cid':id }, dataType: 'json', success: function (data) { if (data.replies) { var htmldata="" var actual = JSON.parse(data.replies); for(var x in actual){ htmldata+="<p>"+actual[x].fields.commentText+" "+actual[x].fields.commenter.first_name +" "+actual[x].fields.created_at+"</p>" } box.html(htmldata); } } }); I get a output like <my comment text> undefined <date time> I am able to get why am i getting "undefined" in place of the users first_name. Thanks in advance. -
How to use dropbox with Django on heroku?
I'm fairly new to django. So heroku doesn't support image storage so I will have to use an other container for it. I've found a lot of tutorials for using Amazon S3 but I would like to use dropbox since it's free. Is this possible? I've found this package https://django-storages.readthedocs.io/en/latest/ but I still don't understand how to use it. If anybody has used it please help me out. Thanks. -
Django: How to filter property through ORM or Mysql?
model: class Production(models.Model): copy = models.ForeignKey('self', related_name='children', on_delete=models.SET_NULL, blank=True, null=True) @property def num(self): n = 0 if self.copy: n += 1 n += self.copy.num return n I want to filter out data that has been copied more than 2 times. But my approach is too slow. qs = [q for q in Production.objects.filter(copy__isnull=False) if q.num > 2] Is it possible to use ORM or MySQL? -
Redirect to referer after post in CreateView in django
I have defined a CreateView in django I want to redirect to the referer of that view if that referer contants ‘center’. The idea is like “iredirect the page that brought you to the CreateView if that page’s path contains ‘center’” I am trying with the following code but is not working since self.request.META.get('HTTP_REFERER') is returning the path of the same createView class CompanyCreateView(LoginRequiredMixin, CreateView): model = CompanyModel context_object_name = 'company' template_name = 'riesgo/company/company_form.html' form_class = CompanyForm def get_success_url(self): if self.request.method == 'POST' and "_continue" in self.request.POST: return reverse('riesgo:company_update', kwargs={'pk': self.object.id}) elif 'center' self.request.META.get('HTTP_REFERER','/'): # here I want to redirect to page that brought you to the createview of the company else: return reverse_lazy("riesgo:company_detail", kwargs={"pk":self.object.id}) -
Using relay mutate_and_get_payload when using graphene-file-upload library
Currently, I am working on a project where we use relay for all views. In one of the views, we are to upload a file and we are using graphene-file-upload which uses graphene.Mutation mutate(). My question is there a way we can use relay mutate_and_get_payload()? I have tried bu failed at the moment -
How do I eliminate Unique Constraint failure in django?
Based on this, I'd like to get a clarification here. How would I ensure that editing/updating the teacher details does not create anew user with the same details??? I think this is the case when I attempt to update/edit an already saved teacher. Please help me out. The teacher model. class TeacherData(models.Model): id = models.AutoField(primary_key=True) teacher_user = models.OneToOneField(User, on_delete=models.CASCADE,null=True,blank=True) school = models.ForeignKey(School,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) code = models.IntegerField(unique=True) email = models.EmailField() phone = models.IntegerField() def save(self, *args, **kwargs): self.user = User.objects.create_user(username=self.first_name,password=str(self.code),is_teacher = True,is_student = False,school_id=self.school.id) self.user.save() # mandatory as create_user is not recognized as save operation super().save(*args, **kwargs) The user model. class User(AbstractUser): school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True) #role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False) is_student = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) The traceback. Traceback (most recent call last): File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\contrib\auth\mixins.py", line 52, in … -
Javascript/Jquery toggle id with multiple variable
this is my first question, so apologies if not written clearly. I want to dynamically toggle a comment form after reply button is pressed. There are multiple comments (in below example three) to which a form (with different id) can be rendered separately. I am able to do this with static id for form but not with dynamically defined id... I have tried this static approach and this works fine. var functs_t = {}; functs_t['fun_27'] = $('#reply_comment_id_27').click(function() {$('#form_comment_id_27').toggle('slow');}); functs_t['fun_23'] = $('#reply_comment_id_23').click(function() {$('#form_comment_id_23').toggle('slow');}); functs_t['fun_21'] = $('#reply_comment_id_21').click(function() {$('#form_comment_id_21').toggle('slow');}); However, I am having struggling with a dynamic approach. var i; var functs = {}; for (i=0; i<comment_qs_id_list.length; i++) { var comment_id = comment_qs_id_list[i].toString(); var reply_comment_id = 'reply_comment_id_'+ comment_id; var form_comment_id = $('#'+reply_comment_id).attr('name'); // works >>> toggles comment 27 functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+'form_comment_id_27').toggle('slow');}); // does not work //functs['func_reply_comment_'+comment_qs_id_list[i]] = $('#reply_comment_id_'+comment_qs_id_list[i]).click(function() {$('#'+form_comment_id).toggle('slow');}); // works >> toggles everything (but what I want is to hide initially and only toggle after clicking reply button) //$('#'+form_comment_id).toggle('slow'); }; Thanks so much! -
Exception Value: 'User' object has no attribute 'update' thrown in DJANGO ORM
I couldn't figure what is wrong with below statement , I am getting 'User' object has no attribute 'update' thrown in DJANGO ORM if "device_id" in request_data: try: User.objects.get(device_id=request_data["device_id"]).update(device_id=None) except ObjectDoesNotExist: pass -
How to add GST calculation in Django oscar
I want to add GST calculations in django oscar. I need help on this as i am new to django oscar. please guide. -
npm run cannot find module webpack.js
im currently on a djangoRest and React course. I have experience on npm and python but this error is something i can't solve. Everithing went well until i "npm run dev" package.json file { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.13.16", "@babel/preset-env": "^7.13.15", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": "^5.34.0", "webpack-cli": "^4.6.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "@material-ui/core": "^4.11.3", "@material-ui/icons": "^4.11.2", "react-router-dom": "^5.2.0" } } webpack.config.js file const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; Error npm run dev > frontend@1.0.0 dev E:\Programacion cursos\Harvard\React&JavaScript\VsCode\react_django\frontend > webpack --mode development --watch "JavaScript\VsCode\react_django\frontend\node_modules\.bin\" no se reconoce como un comando interno o externo, programa o archivo por lotes ejecutable. internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module 'E:\Programacion cursos\Harvard\webpack\bin\webpack.js' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) … -
Enabling live restore on docker is giving OperationalError at [my-endpoint] could not translate host name "db" to address
I try to enable live restore following the official docs, just edit /etc/docker/daemon.json and reload docker daemon. When I check with docker info, it's showing Live Restore Enabled: true. So I think live restore is enabled. However, when I kill docker service by sudo systemctl stop docker and visit my Django app, it's giving an error, OperationalError at /product/69/ could not translate host name "db" to address: Temporary failure in name resolution Look like it cannot connect to the db. Before killing the docker service, it was working well. I didn't change my docker-compose.yml file. Did I miss anything? What did I dowrong? Here is the content: version: '3.7' services: db: image: postgres:12.4-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_DB=${SQL_DATABASE} - POSTGRES_USER=${SQL_USER} - POSTGRES_PASSWORD=${SQL_PASSWORD} web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code - ./static:/static/ expose: - 8000 depends_on: - db env_file: - ./.env nginx: restart: always build: ./nginx volumes: - ./static:/static/ ports: - "80:80" - "443:80" depends_on: - web -
How to get total duration in Django
I am trying to display duration time for an particular work. class UserData(models.Model): uid = models.CharField(max_length=100) email = models.CharField(max_length=100) start_date = models.DateField(auto_now_add=True,editable=False) end_date = models.DateTimeField(auto_now=True) @property def duration(self): if not (self.start_date and self.end_date): return None a,b=self.start_date, self.end_date return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60) But while i call duration property for getting total time, it's give unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date' error. How can i get the duration date please from my UserData model? -
posting with ajax within a ajax get method in django
i have a complain box which shows messages from users to admin .. this messages are coming through ajax get request so that it looks real time now i want to send back reply clicking on that reply button with a modal showing message input by default the reply button will add the receiver id while clicking on reply but i am stuck let me show you models.py class Message(models.Model): sender = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') receiver = models.ForeignKey(User,on_delete=models.CASCADE,related_name='to_user') msg = models.CharField(max_length=1000,blank=True,null=True) sent = models.DateTimeField(auto_now_add=True) mark_as_read = models.BooleanField(default=False) def __str__(self): return self.sender.username + ' messaged ' + self.receiver.username views.py def reply_to_complains(request,id): url = request.META.get('HTTP_REFERER') my_id = request.user.id if request.method == 'POST': msg = request.POST.get('msg') Message.objects.create( receiver_id=id, sender_id=my_id, msg=msg, ) return HttpResponseRedirect(url) form <form method="post" action="{%url 'reply_to_complains' id%}"> {% csrf_token %} <div class="form-group"> <label for="message-text" class="col-form-label">Message:</label> <textarea id="msg_by_admin" name="msg" placeholder="type here .." required></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Send message</button> </div> </form> ajax get <script> setInterval(function () { $.ajax({ method: "GET", url: "get_complains", success: function (data) { console.log(data) $("#msg").empty(); $.each(data, function (key, value) { var a = value.Sender.charAt(0).toUpperCase() + value.Sender.slice(1); var b = value.Msg; var c = value.Sent.substring(0, 10) var Read = value.Read; console.log(Read) this line ---> var … -
PyCharm 2021.1 Community Edition auto import Django CASCADE
I upgraded PyCharm Community Edition to 2021.1 a few days ago. But I found it can't resolve some Django auto import correctly now. For example, I set CASCADE as on_delete for one ForeignKey, it should suggest me to import django.db.models.CASCADE, but it suggest tkinter.CASCADE instead. -
Using Fetch with Javascript and Django
I am new to Javascript and I am using Django. I've read documentation about the Javascript fetch API but I'm confused about something - if anyone can explain it I'd really appreciate it. I've seen code that didn't include a url for the API. Where is this coming from within the framework - when I write code, how do I know what to put right after the fetch part? Example: const load_like = (post, postLikes, likePost, current_user) => { const csrftoken = getCookie('csrftoken'); fetch(`/post/${post.id}`, { method: 'PUT', body: JSON.stringify({ likes: [post.original_poster.id] }), headers: { "X-CSRFToken": csrftoken } }) .then(response => response.json()) .then(data => { display_likes(data, postLikes, likePost, current_user) }) } Is this done in urls.py ? For example would it be: path("post/<int:post_id>", views.post, name="post" ), I want to make sure I understand how to write this type of line and understand why these parts should go here: fetch(`/post/${post.id} -
What is the best approach to deploy nextjs project to google app engine standard environment?
I have created nextjs project with Isomorphic admin theme