Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
New ManyToManyField object is not adding
I am building a BlogApp AND i made a feature of Favorite Users in the ManyToManyField. It means user_1 can add multiple favorite users in one field. I build a view to add users. BUT when i create an instance to store favorite users from Admin before adding favorite users from site AND then if i add favorite users from site then they are adding. BUT if there is not already a instance of request.user's FavouriteUsers in Admin then it is not adding and creating a new object. So, A new object for storing favorite users of request.user is not adding, AND if object is already there then they are adding. models.py class FavoriteUsers(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) favorite_users = models.ManyToManyField(User, related_name='favorite_users', blank=True) views.py def AddFavUsers(request,user_id): obj = FavoriteUsers.objects.filter(user=request.user) user = get_object_or_404(User,id=user_id) for ob in obj: ob.favorite_users.add(user) ob.user.add(request.user) ob.save() return redirect('home') Image of already created object When object is already , manually created then favorite users are adding BUT if it is not then new object is not creating. Any help would be much Appreciated. Thank You in Advance. -
request.FILES is empty though from tag contains multipart data encryption
I am trying to upload a file to database from frontend HTML form. Here is the code: createuser.html <form method="POST" enctype="multipart/form-data" action=""> <input type="file" name="myfile"> <input type="submit"> </form> views.py if request.method == 'POST': if request.POST: myfile = request.FILES print(myfile) Output <MultiValueDict: {}> The output must be a file which I am selecting. Is there any way I could fix this? -
How to make web-scraping faster? Django project
I'm building a web-scraping application using the Django framework. I need some tips on how to speed up my application. As of right now, it takes almost a minute to load the page just parsing through 3 urls which is a problem. I'm going to need to run a lot faster as I want to parse through up to 10 urls on my webpage. As you can see, I'm only targeting one div with my code which is why my application is running so slowly. I'm thinking I could try targeting multiple divs to narrow down my "soup" but I've had difficulty with that in the past so I'm hoping to get some pointers. def stats(request): if 'user_id' not in request.session: return redirect('/') this_user = User.objects.filter(id = request.session['user_id']) this_stock = Stock.objects.filter(user_id = request.session['user_id']) progress_dict = [] for object in this_stock: URL = object.nasdaq_url page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') progress = soup.find_all('div', class_='ln0Gqe') for number in progress: progress_dict.append(number.text) context = { "current_user" : this_user[0].first_name, "progress_dict": progress_dict, "this_stock": this_stock, } return render(request, "nasdaq.html", context) -
Upload a file from react native image picker to server
can someone tell me what i m doing wrong i keep getting error 400 bad request, i can't seem to figure out how to send the image i tried to send the path, the filename and the mime but it's not working this is my request: const [image,setImage]=useState(null) const[filename,setFileName]=useState(null) const sendpic=async ()=>{ await ImagePicker.openCamera({ mediaType:'photo', width: 300, height: 400, cropping: false, }).then(image => { setImage(image['path']); const paths=image['path'] const filename=paths.substring(paths.lastIndexOf('/')+1); setFileName(filename); console.log(filename) console.log(image) const data=new FormData(); data.append('image',filename) data.append('title','3aslemajiti') const headers={ Accept:'application/json', 'Content-Type':'multipart/form-data', } try{ const response= axios.post('http://192.168.1.19:8000/Sends/',data,{headers:headers}) alert('yess!!!!!'); } catch (error) { // handle error alert(error.message); } }); }; and this is my model: from django.db import models # Create your models here. class Send(models.Model): title = models.CharField(max_length=255) image=models.ImageField(default ='null') def __str__(self): return self.title how do i write the request so it is accepted by the server? -
update function in DRF viewset.Viewset
I am trying to implement update in DRF viewset manually, i have successfully implemented list and retrieve This is what i have so far class UserViewset(viewsets.Viewset): authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) serializer_class = UserSerializer def list(self, request): queryset = User.objects.all() serializer = self.serializer_class(queryset, many = True) return Response(serializer.data) def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save( created_by=request.user, modified_by=request.user ) return Response(serializer.data, status=201) return Response(serializer.errors, status=400) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = self.serializer_class(user) return Response(serializer.data) -
Django Admin keep logout repeatedly. May because the DB is corrupted. How to fix this situation?
Let me describe how this problem Admin logout problem occurred. It was about few months ago. My DB is MSSQL. I was using Django 1.11, and I wish to update to Django 3.x . First I was updating my Django to 3.1, because of that, I have to switch django-pyodbc-azure to django-mssql-backend. And I did migrate after I update my Django to 3.1. But I didn't know that mssql-backend does not supporting Django 3.1. So I switch my Django from 3.1 to 3.0.x And I remember that I have to migrate again. But the migrations are the same. I didn't add any new migrations. Still, the migrate it applies something again: admin. {nums}_logentry_add_action_flag_choices auth. {nums}_alter_user_last_name_max_length auth. {nums}_alter_group_name_max_length auth.{nums}_update_proxy_permissions At this moment. I haven't login through Admin page. And I think I did change the Django versions after this (maybe two times again). Just because I was trying to find out which version is suit for me. So I don't really remember how many times I migrate before I found out the Admin logout problem. Anyway, I think I messed up something during the migrates. And it doesn't matter which Version of Django I use, 3.0.x ~ 3.1.x all have the … -
Django how to prevent update old user instance?
I am using django signals in my models so I need to be save user in my views. When admin updating any user blog post it's replacing old user author id with admin user. Let you explain little bit. Assume User Jhone create an Blog post and it's pending for admin approval if admin approve the post then author of blog post changing from Jhone to Admin. It's only happening when admin updating post from HTML template. I think it's happing for this line in my views: isinstance.user = self.request.user #it's saving current user id How to prevent updating old user id in my views. here is my views.py: def form_valid(self, form): isinstance = form.save(commit=False) isinstance.user = self.request.user status = self.object.is_published name = self.object.name[0:20] messages.success(self.request, f"{name} comment status {status}") return super().form_valid(form) my models.py: class BlogComment(models.model): #my fields...... def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, user=blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() if comment.is_published == "published": notify = Notifications(blog=blog, sender=sender, user=blog.author,text_preview=comment_text[:250], notification_type="Comment Approved") notify.save() if comment.is_published == "published": notify = Notifications(blog=blog, sender=sender, user=blog.author,text_preview=comment_text[:250], notification_type="Notify Author") notify.save() if comment.is_published == "rejected": … -
Django lost migration file
I have a django app connected to postgresql database (RDS instance running on AWS) Recently, I added new fields to my database tables, but forgot to run makemigrations locally and pushed the code to the server. The server went down since changes were not applied, and in order to fix the problem quickly I decided to run makemigrations and migrate directly in docker container of the application, I thought it would generate migration files, but unfortunately, it didn't. The migration was applied on database level, but there is no migration file of the changes. When running python manage.py showmigrations in the container, it outputs: redirect [X] 0001_initial [X] 0002_redirect_clicks [X] 0003_redirect_name But in database, running SELECT * FROM django_migrations; tells that there is one more migration: 103 | redirect | 0004_auto_20210707_2039 | 2021-07-07 14:39:19.058233+00 What would you advise? I thought of running makemigrations locally, generate the file and push it to vcs, and on the server apply the changes using migrate --fake. I don't know what this does exactly and I am too scared to do it without guidance, any help would be appreciated -
unabel to fetch data from data from databse in django
i create a model name subject and in the model i also have thumbnail field what i want is to implement that models field n my template my models.py class Subject(models.Model): name = models.CharField(max_length=80, blank=False,) thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name my views.py @login_required def home(request): subject_list = Subject.objects.all() return render (request, 'home.html', {'subject_list': subject_list }) my html file in ehich i tried to show it <div> <ul> {% for subject in subject_list %} <li> <a href=""> <img src="{{ subject.subject_thumbnail }}" alt=""> {{ subject.subject_name }} </a> </li> {% endfor %} </ul> </div> any suggestion what i am doing wrong here -
Customize lookup isnull
I'm trying to customize isnull lookup to return both null and blank values and django documentary doesn't give enough inforamtion about how exactly it works. i need some help writing params and return value. here is my code so far: from django.db.models import Lookup class IsNull(Lookup): lookup_name = 'isnull' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + lhs_params if rhs_params[0]: return '%s != %s and %s != %s' % (lhs, None, lhs, str()), params else: return '%s == %s or %s == %s' % (lhs, None, lhs, str()), params # User.objects.filter(first_name__is_null=True) error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: near "LIMIT": syntax error detail: Traceback (most recent call last): File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near "LIMIT": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<input>", line 1, in <module> File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) … -
How do I update data of django model by simply clicking on a button without any form?
I'm working on a Django project. My motive is to update the value of status in the database by simply clicking on a button. I don't want to submit any form. This is what I've tried: Models.py class auction_listing(models.Model): title = models.CharField(max_length=100) status = models.BooleanField(default=True) def __str__(self): return f"{self.id} : {self.title} " Here status is the boolean field. By default it's true. No form required here but I want this status is to be changed with a button click. Here is the button in my HTML template. template.html <div style="margin-top: 2%;"> <form action="{% url 'status' list.id %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger">Close</button> </form> </div> Here is my views.py function: views.py def status(request,list_id): listing = auction_listing.objects.get(pk=list_id) if request.method == "POST" and instance.status is True: instance.status = False instance.save() else: instance.status = True instance.save() return HttpResponseRedirect(reverse("displaylistitem",kwargs={"list_id":list_id})) urls.py path("<int:list_id>",views.display_list,name="displaylistitem"), path("<int:list_id>", views.status,name="status"), This is all I tried. The problem is when I press the button, it simply refreshes the page rather than updating the value of status in database. -
How to dispaly data just locally on websocket
I'm building a Chat App with django channels websocket and I have two methods, the new_message that create an instance and send to the front-end to be displayed to everyone in the room, and a fetch_messages that make a query and return the 20 messages. When the user log-in to the chat room the fetch_messages method is called and all the message are displayed, but if another user already have loged to the room, the messages will be displayed again, since that the messages already have been displayed when he loged. on my consumers.py class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): message_instances = Message.last_20_messages() messages_objects = [] for instance in message_instances: messages_objects.append(self.message_to_json(instance)) self.send_chat_message(content=messages_objects) def new_message(self, data): username = data['from'] user = get_object_or_404(User, username=username) message_insntance = Message.objects.create( user=user, message=data['message'] ) message_object = self.message_to_json(message_insntance) self.send_chat_message(content=message_object) my JS script: this is the function that I am talking about when the user log to the chat chatSocket.onopen = function(e) { chatSocket.send(JSON.stringify({ 'command': 'fetch_messages' })) } chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); if (data.length > 1) { for (let i = 0; i<data.length; i++) { createMessageDiv(data[i], username) } } createMessageDiv(data, username) }; function createMessageDiv(data, username) { let div = document.createElement('div'); div.classList.add('message'); if (data['username'] == username) … -
Undefined variable 'Listing' Pylint in VSCode
Eventhough I have installed pylint-django and made changes in settings.json file like below, I could not able to access the object named 'Listing'. It shows error as undefined variable "Listing'. { "workbench.editorAssociations": { "*.ipynb": "jupyter.notebook.ipynb" }, "terminal.integrated.tabs.enabled": true, "python.linting.pylintArgs": [ "--load-plugins", "pylint_django", "--disable=all", "--enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode",], "[python]": { "editor.wordBasedSuggestions": false }, } Kindly help. -
ImproperlyConfigured at /catalog/borrowed/
I'm a beginner in python-django coding. Currently I am trying to complete the challenge on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication but I am facing LoanedBooksByAllUserListView is missing the permission_required attribute. Define LoanedBooksByAllUserListView.permission_required, or override LoanedBooksByAllUserListView.get_permission_required(). In urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name='authors'), path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), path('borrowed/', views.LoanedBooksByAllUserListView.as_view(), name='all-borrowed'), ] In views.py from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, 'num_visits': num_visits, } # Render the HTML template index.html with the data in the context variable. return render(request, 'index.html', context=context) from django.views import generic class BookListView(generic.ListView): model = Book paginate_by = 5 class BookDetailView(generic.DetailView): model = Book class AuthorListView(generic.ListView): model … -
How to differ the web engage curl request in Django without affecting the performance of the API?
How to differ the WebEngage curl request in Django without affecting the performance of the API? -
What is / in python?
I'm wondering about / in python. I know that it divides two integers, but I've seen something like this 'NAME': BASE_DIR / 'db.sqlite3' Thank you in advance. -
How do I render individual radio buttons in my django template
I want to individually render radio button in my django template. Is that possible?? models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title forms.py: class ComplaintForm(ModelForm): highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) class Meta: model = Complaint fields = ['title', 'description', 'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') return cleaned_data template: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field" name="title">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr " name="description">{{form.description}}</div> {{message}} <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" name="submit" class="btn btn-secondary save-btn" value="Submit"><i class="fas fa-save"></i> Save</button> </form> </div> <!-- Right Container --> <div class="col right-pro-con"> <div class="img-cir"> <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} {% if request.user.profile.profile_pic.url %} <img src={{request.user.profile.profile_pic.url}} alt="" width="100px" height="100px" class="pro-img"> {% else %} <img src="{% static 'profileimages/msi.jpg' %}" alt="" width="100px" height="100px" class="pro-img"> {% endif %} <p class="my-name">{{request.user.profile.first}} <p> <p class="my-email-id">{{request.user.profile.email}}</p> </form> </div> <p class="prio-txt">Priority</p> <div class="form-check"> … -
Custom BarChart using Chart.js
I'm using normal Bar Chart, but I want to custom the Labels and Bars to make the same output in the picture below. Please give me some idea or reference. Thank You. Bar Chart image Here's my code in normal Chart, but I want to make same output in the picture var dept_chart = new Chart(ctx1, { type: 'bar', data: { labels: ["Department 1","Department 2", "Department 3", "Department 4"], datasets: [{ label: 'Sum of Product Amount', data: item_data, backgroundColor: [ 'rgba(23, 128, 173)', 'rgba(207, 154, 50)', 'rgba(196, 195, 187)', ], borderColor: [ 'rgba(23, 128, 173)', 'rgba(207, 154, 50)', 'rgba(196, 195, 187)', ], borderWidth: 1 }, { label: 'Sum of Discount Amount', fill: true, backgroundColor: 'rgba(207, 154, 50)', borderColor: 'rgb(207, 154, 50)', }, { label: 'Sum of Net Amount', fill: true, backgroundColor: 'rgba(196, 195, 187)', borderColor: 'rgb(196, 195, 187)', }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); window.onload = function(){ var ctx1 = document.getElementById("report_monthly").getContext("2d"); window.myBar = new Chart(ctx1).Bar(dept_chart, { responsive : true }); } } Im using Django in backend and API, $.ajax({ method: "GET", url: URLreport, success: function(report_data){ item_data = report_data.item setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) Chart output what … -
How to generate puppet script with python django
I am start to learning puppet, I have a file in my web and when I press run button, my web will generate a puppet script describe my file. Anyone can give me some advice to do this. You can see the photo for more virtualization. Image demo for generate a puppet script to describe the file -
403 Forbidden when coming up with a new page for staff user instead of normal user: Forbidden (CSRF token missing or incorrect.): /accounts/login/
I'm a beginner in python-django coding. Currently I am trying to complete the challenge on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication but I am facing the 403 Forbidden issue on my login page. This issue happen when i try to add a page for a staff user. Appreciate if anyone could help me. Thank you Below are the codes: In urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name='authors'), path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), path('borrowed/', views.LoanedBooksByAllUserListView.as_view(), name='all-borrowed'), ] In views.py from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, 'num_visits': num_visits, } # Render the HTML template index.html with the data in the context variable. return … -
"Missing filename. Request should include a Content-Disposition header with a filename parameter." Error? Problem with django-simplejwt
I am trying to work with djangorestframework-simplejwt and trying to follow this tutorial: https://www.jetbrains.com/pycharm/guide/tutorials/django-aws/rest-api-jwt/ Currently I'm at this point where I have a superuser account already set up and I'm using Postman to send a request to http://127.0.0.1:8000/api/token to access the TokenObtainPairView view from simplejwt. But I keep on getting this problem: I'm not sure why I'm getting this error. When I do to Headers and add in the key "Content-Disposition" and value "attachment; filename=file". I get a different problem where my body is populated with the username and password but the response keeps on saying the field is required even though I provided in Body. This is my code for urls.py urls.py from django.contrib import admin from django.urls import path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView ) urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] I'm not sure what is going on and any help would be appreciated. Thank you so much! -
best Error handling with csv reader in django
So I've got a small application, and I am uploading bulk data via CSV reader. Everything uploads great, provided I go through my CSV with a fine comb. The only issue is the error handling. Whether it works or fails, I get a 500 error page. Then I have to look through the data base to find at what point the CSV reader failed or compare row count to ensure all values went through. Here is the code for my view: def admin_calv_csv(request): template = "calves/admin_calv_csv.html" prompt = { 'order': 'Order should be eid, visual_id, dairy_id, dob, ship_in_date, ship_out_date, slug, sex, breed, destination, medical_history, milk_consumed, program,' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a CSV') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) for _ in data_set: try: next(io_string) for column in csv.reader(io_string, delimiter=','): _, created = Calf.objects.update_or_create( eid=column[0], visual_id=column[1], dairy_id=column[2], dob=column[3], ship_in_date=column[4], ship_out_date=column[5], slug=column[6], sex=column[7], breed=column[8], destination=column[9], medical_history=column[10], milk_consumed=column[11], program=column[12], ) except IntegrityError as e: error_message = str(e.__cause__) messages.error(request, error_message) test = str(_) messages.info(request, 'error on' + _) pass context = {} return render(request, template, context, messages) -
Handling 2 Django forms - passing data from one to the other
I have 2 Django forms: one, where the user uploads an article, and the second, where the user can edit a list of article words into one of three buckets (change the column value: bucket 1-3). forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ('name','last_name','docfile',) class Doc_wordsForm(forms.ModelForm): class Meta: model= Doc_words fields= ('id','word','word_type','upload',) #upload is foreign key value After the user uploads the article, I have a function in views.py that breaks down the uploaded article into a list of words. I want these words to be looped through and added to a database table(where each row is a word), then have the second form reference these words. Views.py # upload_id = (request.GET.get("id")) if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() data = request.FILES['docfile']#.read().decode('UTF-8') words=get_keywords(data) results=list(find_skills(words)) for word in results: form2 = Resume_words(word = word, word_type='exclude', upload = upload_id) form2.save() return render(request, 'word_list.html',{ "results":results }) else: form = UploadForm() return render(request, 'upload.html', { 'form':form }) I having trouble pulling these pieces together and I'm desperate for help of any kind! I having trouble with the following steps: I don't know how to capture the current users instance when saving to the table. I get an … -
How do I query data from the database base on user in a completely separated frontend Django REST
So I have this basic model: class Text(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=255) def __str__(self): return self.title so usually when you're using regular Django and you want to query Text from the database based on the user you would do: def main_page(request): userTexts = Text.objects.filter(user=request.user) context = {} return render(request, '', context) but now I've been using Django REST React stack and built a completely separated frontend and the only way I access the data from the backend is by making HTTP request to it, so now request.user wont work anymore because it's just going to return anonymousUser fortunately though I already have an authentication system working and already have a user object inside my react state all I have to do is design a view and an API call to query the data from the backend but I cant imagine how to do both of those things. -
Django Queryset filter array field by exact string
so I haven't been working with Django for too long. I am running into a problem filtering a queryset by the exact name of a string of arrays that is passed into it. Currently, I am filtering the queryset by icontains, which works. For example the current implementation works like this: If I pass in one string called "test" my queryset will be filtered and show deals with tags "test1" "test2" and "test3". This is not what I want. I want to filter by the exact name of the strings that are passed in. So if I have a "test" as one of the strings then my queryset will only search for test, not anything that is contained into it. I've tried multiple implementations, such as switching from icontains to iexact, and exact. Goal. Filter queryset by array of multiple tags. old query: values is an array of tags (strings) that are passed in values = value.replace(" ", "").split(",") return qs.filter(reduce(operator.or_, (Q(tags__iontains=item) for item in values))) What I have tried: I have tried passing in the iexact with the list of values like below. I have also tried just passing iexact, and then passing in only one hardcoded string from …