Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - i have add onclick function into html and whenever i click into different button then it will render the same data. how to fix that?
<div class="home-food-row"> {% if allmenu %} {% for menu in allmenu %} <div class="home-food-menu-col"> <div class="filterDiv breakfast"> <div class="img-price-tag"> <div class="price-tag" id="price">{{menu.price}} only</div> <img class="home-page-food-img" src="{{menu.food_img.url}}" alt="Food" width="100%"/> </div> <h1 id="foodName_1">{{menu.food_name}}</h1> <p>{{menu.food_description}}</p> <button id="order" onclick="myFunction()">Place Order</button> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <p>No Food</p> </div> {% endif %} </div> /////////////////////////// JS Code //////////////////////////// function myFunction() { var price = document.getElementById("price"); var food = document.getElementById("foodName_1"); console.log(food); console.log(price); } enter image description here enter image description here -
how to get attribute from other model in your django template
SO I have these two models, One is Members other is PaymentDetail. What I want is all the members from Member model in my template which I can get from Members.object.all() but also I want the payment_status of all those members in my template next to them. I dont know how to do it as payment_status is not in the Member model. class Members(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status') mem_note = models.TextField(null=True, blank=True) class PaymentDetails(models.Model): mem = models.ForeignKey(Members,on_delete=models.CASCADE, related_name="payment_details",verbose_name='Memeber Phone no') com = models.ForeignKey(Committees, on_delete=models.CASCADE,verbose_name='Committee Name') payment_month = models.DateField(default=datetime.now()) payment_amount_debit = models.IntegerField(null=True,blank=True) payment_amount_credit = models.IntegerField(null=True,blank=True) payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES, default="1") payment_proof = models.ImageField(upload_to='images/') payment_note = models.TextField(null=True,blank=True) I searched alot and Found out there is somehting called related name and setname, but I am kinda new so I am not getting the desired results by using them too. -
Using data from the select tag to make queries based on the given id
I'm trying to make queries or to filter data based on the given id from the select tag that I have in the html. In the index.html I have the following: <div class="row"> <label for="patientId">Choose a patient:</label> <select name="patient" id="patient"> {% for item in patientId %} <option value="{{item}}"> {{item}} </option> {% endfor %} </select> In this select I have all the ids from the database, in the same page, I also have a chart that should display data based only on this id from the select tag. For this, I have the data declared in a script tag: var ctx = document.getElementById("weeklyChart"); var myLineChart = new Chart(ctx, { type: 'line', data: { labels: {{ hourArray|safe}}, datasets: [{ label: "Value", lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", borderColor: "rgba(78, 115, 223, 1)", pointRadius: 3, pointBackgroundColor: "rgba(78, 115, 223, 1)", pointBorderColor: "rgba(78, 115, 223, 1)", pointHoverRadius: 3, pointHoverBackgroundColor: "rgba(78, 115, 223, 1)", pointHoverBorderColor: "rgba(78, 115, 223, 1)", pointHitRadius: 10, pointBorderWidth: 2, data: {{ glucoseArray|safe}}, }], }, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", titleMarginBottom: 10, titleFontColor: '#6e707e', titleFontSize: 14, borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, intersect: false, mode: 'index', caretPadding: 10, callbacks: { label: function(tooltipItem, chart) { var datasetLabel … -
Drag and Drop sorting with django and ajax
I want to add drag and drop functionality to the players field. I want to know what are the conditions and requirements for this kind of scenario. What are the steps should I follow? For now, players are stored as we select them (so first selected goes first). I also want to save the order after drag and drop, any suggestions or question improvements will be a great support. Models.py class Group(TimeStampModel, PermissionsMixin): name = models.CharField(_("Group name"), blank=False, max_length=127, unique=False) phase = models.ForeignKey("Phase", related_name="groups", on_delete=models.CASCADE, blank=False, null=True) class Meta: ordering = ["name"] Forms.py: I'm using modelMultipleChoiceField for now. class GroupCreateForm(ModelForm): players = ModelMultipleChoiceField(queryset=None, help_text=_("Please hold down 'Control', to select more than one player")) def save(self, commit=True): group = super(GroupCreateForm, self).save(False) group.phase = self.instance.phase group.created_by = get_request().user if commit: group.save() if self.instance: for player_id in self.cleaned_data['players']: player = Player.objects.get(pk=player_id) ranking = GroupRanking(order=0, player=player, group=group) ranking.save() # Trigger a compute on saving group.phase.ruleset.computeScores() return group class Meta: model = Group fields = ("name",) views.py class GroupCreateView(AccessControlMixin, CreateView): model = Group form_class = GroupCreateForm template_name_suffix = '_create' def has_access(self, user): return self.can(" ", self.phase.tournament) def get_success_url(self): return "%s" % reverse("tournaments:detail", kwargs={"pk": self.kwargs['pk']}) def dispatch(self, request, *args, **kwargs): self.phase = get_object_or_404(Phase, pk=kwargs['rpk']) return super(GroupCreateView, … -
Pagination causes duplicate elements in Django
I've the following ListView: class SentencesListView(ListView): model = Sentence paginate_by = 10 def get_queryset(self): return Sentence.objects.all().order_by('-proficiency') When the user interacts with the webpage, proficiency of all Sentences on the displayed page increases. As a result, when get_queryset will be called again (when user visits the next page), he'll see the same sentences as he did on the previous page. How can I prevent this? I've tried the following which didn't work: class SentencesListView(ListView): model = Sentence paginate_by = 10 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cached_query_set = None def get_queryset(self): if not self.request.GET.get('page') or not self.cached_query_set: self.cached_query_set = Sentence.objects.all().order_by('-proficiency') return self.cached_query_set self.cached_query_set is never not None when the test is performed inside get_queryset. Hence, the query set is always computed anew when moving to the next page. Is there a way to prevent users from experiencing duplicates? Or, is there a way to prevent get_queryset from being called when moving to the next page? -
Django The QuerySet value for an exact lookup must be limited to one result using slicing Error
I have this problem when I want to show all of the post that related to category. I couldn't find the solution in other similar questions. Thank you. Error: The QuerySet value for an exact lookup must be limited to one result using slicing. Model: class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) def get_absolute_url(self): return reverse("post", kwargs={'slug': self.slug}) View : class PostListView(ListView): """ Return all of the posts """ model = Post ordering = '-created' context_object_name = 'posts' template_name ='blog/post_list.html' def get_queryset(self): qs = Post.objects.all() if self.kwargs.get('slug'): category_slug = self.kwargs.get('slug') qs = Post.objects.filter(category = Category.objects.filter(slug = category_slug)) return qs URL: path('', PostListView.as_view(), name='posts'), # all of the posts path('category/<slug:slug>/', PostListView.as_view(), name='categoryposts'), Template: <div class="row"> {% for post in posts %} <div class="col-md-4"> <div class="card" style="width: 25rem; height: 34rem;"> <a href="{% url 'post' post.slug %}"> <img class="post-thumbnail card-img-top" src="{{post.thumbnail.url}}" alt="{{post.title}}" style="width: 24.9rem; height: 18rem;"> </a> <div class="card-body"> <h5 class="card-title"><a href="{% url 'post' post.slug %}">{{post.title}}</a></h5> <p class="post-updated">Last update at {{post.updated|date:"Y/M/d"}}</p> <p>Post by <a href="">{{post.author}}</a></p> {% if post.description %} <p class="card-text">{{post.description|slice:"80"}}...</p> {% else %} <p class="card-text">{{post.body|slice:"80"}}...</p> {% endif %} <a href="{% url 'post' post.slug %}" … -
django: get() returned more than one Freelancers -- it returned 3
i am trying to assign a freelancer to a particular gig but it shows get() returned more than one Freelancers -- it returned 3!. I have tried getting the logged in freelancer to is trying to create the git like this freelancer = get_object_or_404(Freelancers, user=user) and before i save the form i assign the value like this new_form.creator = freelancer . views.py @login_required def create_gig(request): user = request.user freelancer = get_object_or_404(Freelancers, user=user) if request.method == "POST": form = CreateGig(request.POST, request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user new_form.creator = freelancer new_form.slug = slugify(new_form.title) new_form.save() messages.success(request, f'Gig Created Successfully, Would be Live Soon') return redirect('freelance:listings') else: form = CreateGig() context = { 'form': form } return render(request, 'freelance/create.html', context) models.py class Gigs(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='gig_user') creator = models.ForeignKey(Freelancers, on_delete=models.CASCADE, related_name='gig_creator') title = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Enter what you will do", default=" I will ") -
Django ManyToMany model: unable to access one relation from the other
My models.py: class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField( "Book", related_name="books", blank=True ) class Book(models.Model): title = models.CharField(max_length=100) author = models.ManyToManyField(Author) In Django admin I first created an instance of Author, without assigning him any Book: Then I created a new Book and assigned Leo Tolstoy as theAuthor: In Django shell, I am able to access the Book's Author: >>> Book.objects.filter(title="War and Peace").first().author.first() <Author: Leo Tolstoy> But I'm unable to access the Author's Books: >>> Author.objects.filter(name="Leo Tolstoy").first().books.all() <QuerySet []> The book isn't assigned in the Admin view either: I would like to access the Author's Books as well as for the Books to show in the Author's Admin view. -
How can I send localstorage data from JavaScript ajax call and print return data from views in Django template
I have stored some data on localStorage( Itemnames and ItemIds), now I want to send itemid's to django views from ajax. I have basics knowledge of django and learning Javascript. I tried to figureit out by myself but its been more than 4 days I could not succeed, any help will be highly appreciated. My Javascript: $(document).ready(function() { var compare = localStorage.getItem("comparisionItems"); var compareObj = JSON.parse(compare); var data_url = window.location.href; console.log(compare) console.log(compareObj) $.ajax({ url: './compare', type: "POST", data: {'compare_id': compareObj }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, dataType: "json", success: function (data) { console.log(data) }, error: function () { alert("Please login"); } }); }); My views: def compare(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax and request.method == "POST": compare_id= request.POST.getlist('compare_id[itemIds]') """compare_id=request.POST.getlist('itemIds[]') """ """compare_id = request.POST.get('compare_id')""" product = get_object_or_404(Products, id=compare_id) context={ 'product':product} """ return render (request, './ecommerce/compare.html', context)""" return render (request, './compare.html', context) else: context = None return render(request,'./compare.html', context) How can I get the products which have id's pass by ajax? And is there any different ways to pass those products to the template or I can do it just like the regular Django context process? -
Group By with Django, with distinct() in one especific field
My goal is get all charge in one particular segment, distinct by user, and group by origin_province and destination_province, so: From this query: charges = charges_mean.filter(numbers_pallets = num).order_by().values('charger').distinct() I would like to group by 'origin_province' and 'destination_province', fields in Charges table, but it only response 'charger' value, obviously, and I do not know how do it. I tried something like this, but it doesn't work without Potgress Database: Mymodel.objects.filter(...).annotate(distinct_name=Concat('tcode', 'created_on', output_field=TextField())).order_by('distinct_name').distinct('distinct_name') I get it from this post: Django distinct group by query on two fields -
I am stuck when accessing the DetailView template in Django
urls.py urlpatterns = [ path('',CourseList.as_view(),name='course_list'), path('create/',CourseCreate.as_view(),name='course_create'), path('<int:cid>/',CourseView.as_view(),name='course_view'), ] views.py COURSE_PERM_GUEST = 0 COURSE_PERM_STUDENT = 1 COURSE_PERM_TEACHER = 2 COURSE_PERM_MEMBER = 3 class CourseAccessMixin(AccessMixin): permission = None extra_context = {} def dispatch(self,request,*args,**kwargs): if not request.user.is_authenticated: return super().handle_no_permission() self.course = get_object_or_404(Course,id=kwargs['cid']) user_perm = COURSE_PERM_GUEST if self.course.teacher == request.user: user_perm = COURSE_PERM_TEACHER elif self.course.enroll_set.filter(student=request.user).exists(): user_perm = COURSE_PERM_STUDENT if not request.user.is_superuser and self.permission is not None: is_accessible = False if self.permission == COURSE_PERM_GUEST and \ user_perm == COURSE_PERM_GUEST: is_accessible = True elif (self.permission & user_perm) != 0: is_accessible = True if not is_accessible: return super().handle_no_permission() self.extra_context.update({'course':self.course}) return super().dispatch(request,*args,**kwargs) class CourseView(CourseAccessMixin,DetailView): extra_context = {'title':'檢視課程'} model = Course pk_url_kwarg = 'cid' models.py class Course(models.Model): name = models.CharField('課程名稱',max_length=50) enroll_password = models.CharField('選課密碼',max_length=50) teacher = models.ForeignKey(User,models.CASCADE) def __str__(self): return '{}#{} ({})'.format( self.id, self.name, self.teacher.first_name) course_list.html {% extends "base.html" %} {% load user_tags %} {% block content %} {% if user|is_teacher %} <div class="mb-2"> <a href="{% url 'course_create' %}" class="btn btn-sm btn-primary">建立課程</a> </div> {% endif %} <div id="course_list"> {% for course in course_list %} <div class="list-group"> <div class="list-group-item d-flex"> {% if user.is_authenticated %} <a href="{% url 'course_view' course.id %}">{{ course.name }}</a> {% else %} {{ course.name }} {% endif %} <small class="ml-auto">{{ course.teacher.first_name }} 老師</small> </div> </div> {% endfor %} … -
Django views best practice : explicit or implicit context?
I'm wondering if there is a 'best' solution between explicit context definition and implicit use of locals() parameter in view rendering. The original way of doing is to 'declare' each variable to be used in the context of a view, thanks to a dictionary, but Django proposes some shortcuts and also offers the ability to take into account all variables defined in a view to be part of the context. Are there any differences between both options (context variable defined in a dict vs 'locals()'), and is one of them 'better' (and why?)? Btw (subsidiary question): I'm quite new to Django and I never used return HttpResponse(...) but always return render(...), am I wrong? -
Django launch windows app from website Django?
in an application, I want to open the zoom application on the user's computer from my website, how can I do this? -
Which method of 'Django Serializer' do I need to customize?
The frontend sends the json in an array. I received the value with difficulty as shown in ex) below. ex) applier_phone = data.get('phone')[0] applier_name = data.get('name')[0] applier_birth = data.get('birth')[0] applier_gender = data.get('gender')[0] But I want to get the value using Serializer. In this case, which method of Serializer do I need to customize? -
Django pdf file not finishing its downloading in browser
views.py def showName(request): if request.method == 'POST': uploaded_file = request.FILES['user_initial_pdf'] if uploaded_file is not None: import PyPDF2 import os from io import BytesIO from django.conf import settings #Merging 2 pdf files pdfObject1 = PyPDF2.PdfFileReader(uploaded_file) pdfWriter1 = PyPDF2.PdfFileWriter() for pageNum in range(pdfObject1.numPages): pageObj = pdfObject1.getPage(pageNum) pdfWriter1.addPage(pageObj) for pageNum in range(pdfObject1.numPages): pageObj = pdfObject1.getPage(pageNum) pdfWriter1.addPage(pageObj) pdfOutputFile = BytesIO() pdfWriter1.write(pdfOutputFile) #using FileSystem storage to store the merged pdf in merdia directory fs = FileSystemStorage() fs.save(uploaded_file.name,pdfOutputFile) #getting the file path file_path = settings.MEDIA_ROOT +'/'+ uploaded_file.name #creating wrapper of file object of the required pdf to be sent as downloadable file to client side wrapper = FileWrapper(open(file_path,"r",encoding="utf8")) response = HttpResponse(wrapper, content_type = 'application/pdf') response['Content-Length'] = os.path.getsize( file_path ) response['Content-Disposition'] = 'attachment; filename="sample.pdf"' return response else: return HttpResponse("File has not been uploaded or is empty!") return HttpResponse("No Post method") Above is the function in views.py which takes in a single pdf and basically merge with itself and send it back to the user. Error/Issue: For some reason my pdf file seems to be stuck at near completion and never finishes Note: I have just started learning django and I am not using any models as of such since I havent started yet so please forgive me … -
Django change password
Trying to change password using PasswordChangeView, but cannot get it working. urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('profiles/settings/', update_profile, name='update_profile'), path('profiles/settings/', auth_views.PasswordChangeView.as_view(template_name='accounts/settings.html'), name='password_change'), ] And i am trying to get the input fields correct in my html <div class="tab-pane fade" role="tabpanel" id="password"> <form id="id_password_change_form" method="POST" class="form-signin">{% csrf_token %} <div class="form-group row align-items-center"> <label class="col-3">Current Password</label> <div class="col"> <input type="password" placeholder="Enter your current password" name="old_password" class="form-control" id="id_old_password" required="true" /> </div> </div> <div class="form-group row align-items-center"> <label class="col-3">New Password</label> <div class="col"> <input type="password" placeholder="Enter a new password" name="new_password1" class="form-control" id="id_new_password1" required="true" /> <small>Password must be at least 8 characters long</small> </div> </div> <div class="form-group row align-items-center"> <label class="col-3">Confirm Password</label> <div class="col"> <input type="password" placeholder="Confirm your new password" name="new_password2" class="form-control" id="id_new_password2" required="true" /> </div> </div> {% for field in form %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} {% endfor %} <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Change Password</button> </div> </form> There is no error, and it do not update the password as supposed to. according to PasswordChangeView, I should not need to alter anything. -
error while hosting django project on heroku
I am new in web development. I create E-Commerse website and now want to host this website on Heroku but there is some problem I don't know what is it. My project is working perfectly. Successfully installed Django-3.1.5 Flask-1.1.2 Jinja2-2.11.3 MarkupSafe-1.1.1 Pillow-8.1.0 Werkzeug-1.0.1 asgiref-3.3.1 click-7.1.2 django-autoslug-1.9.8 django-crispy-forms-1.10.0 gunicorn-20.1.0 itsdangerous-1.1.0 pycryptodome-3.9.9 pygame-2.1.0 pytz-2020.5 sqlparse-0.4.1 whitenoise-5.3.0 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_fd56140f/manage.py", line 22, in <module> main() File "/tmp/build_fd56140f/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 109, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 316, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_fd56140f/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable … -
Django ManyToMany | TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use course_tags.set() instead
My model: class Course(models.Model): ... course_tags = models.ManyToManyField(CourseTag, related_name='course_tags', blank=True) ... My Serializer: class CourseSerializer(serializers.ModelSerializer): ... course_tags = CourseTagsSerializer(many=True, required=False) ... class Meta: model = Course fields = [...'course_tags'...] def create(self, validated_data): ... tags_data = validated_data.pop('tags', None) ... course, _ = Course.objects.create( author=author, **validated_data) if tags_data: for tag in tags_data: new_tag, _ = CourseTag.get_or_create(title=tag.get('title')) course.course_tags.add(new_tag.id) course.save() I'm sending POST request to this serializer. Response: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use course_tags.set() instead. I tried working method but, my code is not working. -
How to mitigate the slow function in Django view
My Django website is in shared server ( nginx with uwsgi & Sqlite). The database is huge, when users search for certain model instances, it slows down the server as it wait for the query to finish. VIEW.PY def Newssearch(request): if request.method == "POST": searchdata = request.POST.get('searchdata') result = News.objects.filter(titleEnglish__icontains=searchdata)[0:8] return render(request, 'newsfront/searchresult.html',{'news':result}) The server (Pythonanywhere.com) seems to not support async functions. Any idea how to reduce the priority of the above function , so that if multiple types frequent requests come, it gives less priority to the search function. -
REST API endpoiint call of a signle id gives mutliple results with similar begining alphabtes
I am learning REST API Django and would appreciate your help in understaing the below case. in myproject/abcapp/forms.py from django import forms from .models import * class ProfileForm(forms.ModelForm): class Meta: model=Profile fields = "__all__" class Zoo_data_2020Form(forms.ModelForm): class Meta: model=Zoo_data_2020 fields = "__all__" in myproject/abcapp/models.py from django.conf import settings from django.db import models class ProfileQuerySet(models.QuerySet): pass class ProfileManager(models.Manager): def get_queryset(self): return ProfileQuerySet(self.model,using=self._db) class Profile(models.Model): name=models.CharField(settings.AUTH_USER_MODEL,max_length=200) subtype=models.CharField(max_length=500) type=models.CharField(max_length=500) gender=models.CharField(max_length=500) objects = ProfileManager() class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' managed = False db_table ='profiles' def __str__(self): return '{}'.format(self.name) class Zoo_data_2020QuerySet(models.QuerySet): pass class Zoo_data_2020Manager(models.Manager): def get_queryset(self): return Zoo_data_2020QuerySet(self.model,using=self._db) class Zoo_data_2020(models.Model): name=models.CharField(max_length=200) size=models.DecimalField(decimal_places=3,max_digits=100000000) weight=models.DecimalField(decimal_places=3,max_digits=100000000) age=models.DecimalField(decimal_places=3,max_digits=100000000) objects = Zoo_data_2020Manager() class Meta: verbose_name = 'zoo_data_2020' verbose_name_plural = 'zoo_data_2020s' managed = False db_table ='zoo_data_2020' def __str__(self): return '{}'.format(self.name) in myproject/abcapp/api/views.py: from rest_framework import generics, mixins, permissions from rest_framework.views import APIView from rest_framework.response import Response import json from django.shortcuts import get_object_or_404 from abcapp.models import * from .serializers import * def is_json(json_data): try: real_json = json.loads(json_data) is_valid = True except ValueError: is_valid = False return is_valid class ProfileDetailAPIView(generics.RetrieveAPIView): permission_classes = [] authentication_classes = [] queryset= Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'id' class ProfileAPIView(generics.ListAPIView): permission_classes = [] authentication_classes= [] serializer_class = ProfileSerializer passed_id = None search_fields = ('id','name','animal') … -
preserve data while making changes to fields of model in django
I have two models which are Contact and UpdateInfo. Update model is a foreignkey relationship with Contact like below: class Contacts(models.Model): full_name = models.CharField(max_length=100, blank=True) notes = RichTextField(blank=True) /............./ class UpdateInfo(models.Model): contacts = models.ForeignKey(Contacts,on_delete=models.CASCADE, related_name='update_info') updated_at = models.DateTimeField(auto_now=True) modified_by = models.CharField(max_length=100, blank=True) Now what I need is to put the notes field into UpdateInfo model and remove from Contacts model. Because now the businees requirement has changed and what they need is they need to add notes in the existing notes and want to see them who added the notes and when they added it with the notes appended. But the problem is if I remove the notes field from Contacts and add it to Updateinfo model , there are many data into the production and the notes field data will be lost. Now how can we run migrate in such a way that I add notes field into the Updatinfo model and also migrating the data at the same time.?? Is this what is done by dev ops or we should do it?? Because usually dev ops are migrating the data to the production server from staging area. I need expert opinion on this. -
render() got an unexpected keyword argument 'board_id'
I have this function to get items from DB according to the PK: def new_topic(request, board_id): board = get_object_or_404(Board, pk = board_id) user = User.objects.first() if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save(commit=False) topic.board = board topic.created_by = user topic.save() post = Posts.objects.create( message = form.cleaned_data.get('message'), created_by = user, topic = topic ) return render('board_topics', board_id = board.pk) else: form = NewTopicForm() return render(request,'new_topic.html', {'board':board, 'form':form}) But it gives this error: render() got an unexpected keyword argument 'board_id' -
How to save image file to django obj
I am trying to set an image file from local path to the model GameFilm but the issue is print(File(open(path, 'rb'))) returns None so when i do obj.thumbnail = File(open(path, 'rb')) it will just set obj.thumbnail to None. My Model class GameFilm(models.Model): thumbnail = models.ImageField(null=True, blank=True, upload_to='images/') created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey('users.User', on_delete=models.PROTECT, null=True, blank=True, related_name='game_films') title = models.CharField(max_length=150) description = models.TextField() film = models.FileField(upload_to='films/') My My problem function Here I am extracting an image at the millisecond 200 from the video in the path video_path. Then, I try to open the file and set it to obj.thumbnail. Then django supposed to upload it to aws s3. Finally, I will delete the local image that is just created. vidcap = cv2.VideoCapture(video_path) millisecond = 200 vidcap.set(cv2.CAP_PROP_POS_MSEC, millisecond) success, image = vidcap.read() if success: cv2.imwrite("framed.jpg", image) # save frame as JPEG file path = f'{settings.BASE_DIR}/framed.jpg' obj = GameFilm.objects.get(id=1) obj.thumbnail = File(open(path, 'rb')) obj.save() os.remove(f'{settings.BASE_DIR}/framed.jpg') -
DRF Viewset problem with using MultiPartParser/FormParser
django version = 2.2.16 drf version = 3.11.0 I would like to know what is the root cause of this problem. I have implemented similar code on previous project with similar settings without this problem. It works fine with JSONParser and FileUploadParser only. My modelviewset class OutletViewset(viewsets.ModelViewSet, mixins.ListModelMixin): permission_classes = [IsAuthenticated] parser_classes = [JSONParser, MultiPartParser] queryset = Outlet.objects.all() serializer_class = serializers.OutletSerializer def get_queryset(self): if "user_id" in self.request.query_params: user_id = self.request.query_params.get("user_id", None) queryset = Outlet.objects.filter(user=user_id) else: queryset = Outlet.objects.all() return queryset My serializer class OutletSerializer(serializers.ModelSerializer): class Meta: model = models.Outlet fields = "__all__" def update(self, instance, validated_data): [setattr(instance, k, v) for k, v in validated_data.items()] instance.save() return instance The error I met: Environment: Request Method: GET Request URL: http://localhost:8000/commons_kl/api/v1/outlets/ Django Version: 2.2.16 Python Version: 3.7.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'drfpasswordless', 'rest_framework_api_key', 'rest_auth', 'django_extensions', 'commons_kl'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', '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'] Template error: In template D:\Work\commonsKL\lib\site-packages\rest_framework\templates\rest_framework\horizontal\select.html, error at line 15 __str__ returned non-string (type NoneType) 5 : <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}"> 6 : {{ field.label }} 7 : </label> 8 : {% endif %} 9 : 10 : <div class="col-sm-10"> 11 : <select class="form-control" name="{{ field.name … -
how to redirect return to same page after POST in this case. django
I am creating this project in django. I am working on recording Add the number of products by BARCOD , where I go to a product -detail view, then hit the product link. Add the number of product in form Everything works fine, but there is one thing. After add number of products by BARCOD I get sent back to a random(?) ....but I would like to stay on the same page Add the number of product in form . But how??? views def returnitm_PK(request,item_PK_id): clientR=ClientPK.objects.get(place=request.POST.get("clientR")) item_PK=StockPK.objects.get(pk=item_PK_id) quan_BARCOD=request.POST.get("quan_BARCOD") Ear_number=request.POST.get("Ear_number") transaction=TransactionPK(item_PK=item_PK,clientR=clientR,quan_BARCOD=quan_BARCOD,Ear_number=Ear_number) transaction.save() if quan_BARCOD== '0009478908' : item_PK.R1=item_PK.R1+int(1) if quan_BARCOD== '0005663140' : item_PK.R2=item_PK.R2+int(1) item_PK.save() context = {'transaction':transaction,'item_PK':item_PK,'clientR':clientR, 'quan_BARCOD':quan_BARCOD,'Ear_number':Ear_number, } return render(request, "details_PK", context) urls path('F_add_items/',views.F_add_items,name='F_add_items.html'), path('F_list_history/', views.F_list_history, name='F_list_history.html'), path('F_list_item/', views.F_list_item, name='F_list_item'), path('<int:item_PK_id>/details',views.details_PK,name='details_PK'), path('<int:item_id>/',views.details,name='details'), path('<int:item_id>/transfer',views.transferitm,name='transferitm'), path('<int:item_id>/returnitm',views.returnitm,name='returnitm'), ############################################################################### path('F_add_PK/',views.F_add_PK,name='F_add_PK.html'), path('F_list_history_PK/', views.F_list_history_PK, name='F_list_history_PK.html'), path('F_list_item_PK/', views.F_list_item_PK, name='F_list_item_PK'), path('<int:item_PK_id>/returnitm_PK',views.returnitm_PK,name='returnitm_PK'), details_PK {% extends 'base.html' %} {% block content %} <center> <div class="card" style="width: 50rem;"> <div class="card-body"> <form action="returnitm_PK" method="POST" > <div class="card-header">add {{ item.name }}</div> {% csrf_token %} <input type="hidden" name="item" value="{{ item.name }}"> <div class="form-group"> <label for="clientR">clientR</label> <select name="clientR" class="form-control" id="client"> {% for clientR in ClientPKs %} <option value="{{ clientR.place }}">{{ clientR.place }}</option> {% endfor %} </select> </div> <!-- <div class="form-group"> <label for="Ear_number">رقم الاذن</label> <input type="text" class="form-control" …