Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostUpdateView is missing a QuerySet. Define PostUpdateView.model, PostUpdateView.queryset, or override PostUpdateView.get_queryset()
i am trying to edit a reply(message) done by a user on the website but when pressing the edit button instead of taking me to the page to edit it, it gives me this error: PostUpdateView is missing a QuerySet. Define PostUpdateView.model, PostUpdateView.queryset, or override PostUpdateView.get_queryset(). urls.py: path('boards/<int:board_id>/topics/<int:topic_id>/posts/<int:post_id>/edit/', views.PostUpdateView.as_view(), name='edit_post'), views.py: my application is called firstapp from os import name from django.db.models.base import Model from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse, response from firstapp.models import Board from django.contrib.auth.models import User from firstapp.models import Topic,Post from django.views.generic import UpdateView from django.utils import timezone class PostUpdateView(UpdateView): Model = Post fields = ('message',) template_name = 'edit_post.html' pk_url_kwarg = 'post_id' context_object_name = 'post' def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_dt = timezone.now() post.save() return redirect ('topic_posts',board_id=post.topic.board.pk,topic_id=post.topic.pk) models.py: class Board(models.Model): name = models.CharField(max_length=50,unique=True) description = models.CharField(max_length=150) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(Topic__board=self).count() def get_last_post(self): return Post.objects.filter(Topic__board=self).order_by('-created_dt').first() class Topic(models.Model): subject = models.CharField(max_length=255) board = models.ForeignKey(Board,related_name='topics',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='topics',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) updated_by = models.ForeignKey(User,null=True,related_name='+',on_delete=models.CASCADE) updated_dt = models.DateTimeField(null=True) def __str__(self): return self.subject class Post(models.Model): message = models.TextField(max_length=4000) Topic = models.ForeignKey(Topic,related_name='posts',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(User,null=True,related_name='+',on_delete=models.CASCADE) updated_dt = models.DateTimeField(null=True) def __str__(self): truncated_message= Truncator(self.message) return truncated_message.chars(30) … -
Django - ATFinfo() missing 1 required positional argument: 'test_case_ID'
I'm trying to add comments to my project and I've got this error: ATFinfo() missing 1 required positional argument: 'test_case_ID'. Here is my code. views.py def ATFinfo(Request,test_case_ID): if Request.method == 'POST': pi = APIDetails.objects.get(pk=test_case_ID) atfParam= list(APIParameter.objects.all('id','parameterName','parameterValue').filter(TC_ID=pi)) atf = APIDetails.objects.all() return render(Request, 'hello/ATF_Dashboard.html',{'ATF': atf, 'Param': atfParam}) here's my url: from django.urls import path from hello import views urlpatterns = [ path('api/taf_callback/', views.ATFinfo, name = 'ATFinfo'), ] Please help me to solve this issue not able to get the issue. -
Django send notification based on interaction with object
I've a post, where I need to send a notification when it is liked the 1st,5th,10th,25th,50th time. I was looking for an optimal way to this. What I've in mind right now is to store in the model something like first_interaction Boolean fifth_interaction Boolean So on.. Could there be a better way for this? -
duplicate .py files created for html and txt files in project after running compilemessages in django
I wanted to create .po and .mo files in my LOCALE folder therefore run makemessages and compilemessages commands. However, this also created .py duplicates of all files in the project that did not have .py extension. So now I have requirements.txt.py which content looks like this: XXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXX XXXXXXXXXXXXXX X XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XX XXXXXXX XXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XX XXXXX and many more files like that. Can anyone help me to solve this issue? -
JavaScript & Django -run the time continuously without refreshing the page
I have developed an Django application where it will take the time based on the timezone and it's working properly how could I make the time runnining continuously without refreshing the page. Even i have no idea to implement it in js or ajax. If anyknow how could be possible to implement django code with the js or ajax. P.S.I just tried writing js for the particular label which is "mytime" that holds the time which is supposed to be running continuously without refreshing the page. Thanks in advance single.html {% extends 'base.html' %} {% block content %} #js script <script type = 'text/JavaScript'> build() function build(){ var wrapper = document.getElementById('mydate') var url = 'http://localhost:1700/api/ben/' fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data) var detail = data for (var i in detail){ // var item = '<td id ="td-row-${i}" class="table table-striped table-hover"> // <span class='currenttime'> ${detail[i].currenttime}</span> // </td>' } // var detail = data // var item = '<td id ='mydate'> {$(my_date)}</td>' } ) } <div class="container-md" id='firstcontainer'> <form action="" method="POST" autocomplete="off"> {% csrf_token %} <div class="container-md"> <h3 id ='user'>Search</h3> <div class="row"> <div class="input-group" > <div class="col-md" > <input class="form-control" type="search" placeholder="Search" id='btnsearch' name="finder" > <br> </div> <div class="pull-left"> <button class="btn … -
Run Selenium tests via Jenkins on Docker Django app
I would like to run Selenium integration tests on a Development server. Our App is Django app and it is deployed via Jenkins and Docker. We know how to write and run Selenium tests localy We know how to run tests with Jenkins and present Cobertura and Junit reports The problem we have is: In order for Selenium tests (apart from unit tests) the server needs to run So we can't run tests before we build docker image How to run tests inside docker images (this could be potentially achieved via script called inside Dockerfile...) BUT even more important: How can Jenkins get the reports from inside docker containers Whats are the best practice here. The Deployment structure: Jenkins get code from GIT Jenkins Builds docker images pass this image to the Docker registry (a private one) log in to the remote server on remote server pull the image from the registry run image on a remote server -
How to deal with .errors for Django API framework
I have the following codes: models.py class Device(models.Model): hostname = models.CharField(max_length=50, unique = True) ipaddr = models.GenericIPAddressField(protocol='ipv4', unique=True, verbose_name='mangement IP') ##Use for mgt_id_addr date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.hostname class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname serializers.py from rest_framework import serializers from .models import Device, DeviceDetail class DeviceSerializers(serializers.ModelSerializer): class Meta: model=Device fields = '__all__' class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = ['mgt_interface', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] views.py @api_view(['POST']) def create_device(request): device = Device() devicedetail = DeviceDetail() deviceserializer = DeviceSerializers(device, data = request.data) devdserializer = DeviceDetailSerializers(devicedetail, data = request.data) if deviceserializer.is_valid() and devdserializer.is_valid(): device_instance = deviceserializer.save() devdserializer.save(DD2DKEY=device_instance) results = { "device":deviceserializer.data, "device_details" : devdserializer.data, } return Response(results, status=status.HTTP_201_CREATED) else: errors = { "device":deviceserializer.errors, "device_details" : devdserializer.errors, } return Response(errors, status=status.HTTP_400_BAD_REQUEST) I am facing the … -
Django get query from queryset. Returning invalid params
When I try to get the query from django queryset, it returns parameters without quotes which makes it an invalid query to run I have a django code as follows: qs = SignalAssetWeightTs.objects.filter(data_date__range=[start_date, end_date]) When I try to get the query so that I can query it using pyodbc (I found django's query taking 5 seconds vs pyodbc taking <1 for 50k+ rows), I try to get the query like this: str(qs.query) However, for the parameters it returns without quotes for example the query returned is SELECT * FROM [mm_signal_asset_weight_ts] WHERE [mm_signal_asset_weight_ts].[data_date] BETWEEN 2019-01-01 00:00:00 AND 2022-01-01 00:00:00 As is evident, the quotes are missing from the 2 datetime variables so when I try to run the query using pd.read_sql_query(query, conn) then I get an error pointing to these parameters. And it's not just date param, if I try to filter using anything else, I get the same issue. I was wondering whether there's any other way to generate the query from django queryset so that I can run it using pyodbc or anything else to get a faster result. I'm using Django 3.2 and sql-server -
Django Do I need to take any step for secure my user password?
I setup an password reset system in my django website. Where user first to need submit his email address then my website sending an password rest code to his email. He need to be enter his verification code and new password in password reset page. If he entered right verification code then his password will be change and redirect to login page. I have few question: is there any security risk in my password reset system? How .set_password() working for save user password? does it using any encryption method? Most important question: can user change his user_id during changing password? if yes then how to stop him to change password password if user_id changed? here is my code: the first function sending verification code to user email: def ForgetPasswordSendCode(request): if request.method == "POST": email = request.POST["email"] User = get_user_model() if not User.objects.filter(email=email).first(): messages.success(request, "Invalid mail") return redirect('members:reset-password') user_obj = User.objects.get(email=email) reset_code = str(rand_number_mail()) profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.forget_password_token = reset_code profile_obj.save() current_site = get_current_site(request) subject = 'Password Reset Code' context = { 'user_first_name': user_obj.first_name , 'user_last_name': user_obj.last_name , 'domain': current_site.domain, 'reset_code': reset_code } html_body = render_to_string('mail/resetpassword-mail.html', context) to_email = request.POST["email"] email = EmailMultiAlternatives(subject=subject,from_email='noreply@farhyn.com',to=[to_email]) email.attach_alternative(html_body, "text/html") email.send(fail_silently=False) messages.success(request, "password reset code sent … -
convert FBV to CBV
I am trying to change all my Function Based View to Class based view, i’ve been fairly successful except for this view, it’s a detail view that contains paystack payment gateway. Any help will be hugely appreciated. def car_rent_detail_view(request, pk): object = get_object_or_404(CarRent, id=pk) paystack = PaystackAccount( settings.PAYSTACK_EMAIL, settings.PAYSTACK_PUBLIC_KEY, object.total_cost ) context = {'object': object, 'pk_public': settings.PAYSTACK_PUBLIC_KEY, 'currency': 'NGN', 'paystack': paystack, } if request.method == 'POST': if paystack.verify_transaction(request.POST['reference']): messages.success(request, "payment successfull") … car_rented.save() … rent_activation.save() messages.success(request, "Rent successfully updated") return render(request, 'app/CarRent_detail.html', context=context) -
Can not add ManyToManyFields using froms.py in django
I am trying to add data in a model using django forms but getting Direct assignment to the forward side of a many-to-many set is prohibited. Use tag.set() instead. Please help me solve this. I am using multiselect field to send data to views.py. models.py class Tags(models.Model): tag = models.CharField(max_length=100) def __str__(self): return self.tag class Meta: verbose_name_plural = 'Tags' class Post(models.Model): ... author = models.ForeignKey(User, verbose_name='Author', on_delete=models.CASCADE) feature_image = models.ImageField(upload_to='blog/', verbose_name='Add Feature Image') tag = models.ManyToManyField(Tags, related_name='post_tags', verbose_name='Add Tags') def __str__(self): return self.title forms.py class PostForm(forms.ModelForm): ... class Meta: model = models.Post fields = [...] views def adminNewPostView(request): form = forms.PostForm() if request.method == 'POST': ... tags = request.POST.getlist('tagName') form = forms.PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.category = cat if subcat: post.sub_categories = subcat if subfil: post.filter_option = subfil add_tags = models.Tags.objects.filter(tag__in=tags) for tl in add_tags: post.tag = tl # Getting Error here post.save() return HttpResponseRedirect(reverse('blog_app:index')) Error Direct assignment to the forward side of a many-to-many set is prohibited. Use tag.set() instead. -
Show captcha after 5 incorrect login attempts with django-axes
I'm a beginner with Django and have a login page and with captcha which works fine, however I would like to only show the captcha within my login page template after a user has entered the incorrect login details after 5 attempts. My template has an include tag for my captcha which I prefer to to display with this method but not sure if it was possible but thought I may be able to implement via creating 2 seperate views/templates as I felt I may be able to pull it off but guess not. Urls from django.urls import path, include from django.contrib.auth import views as auth_views from . import views from .views import RequestPasswordResetEmail, CompletePasswordReset #from .forms import EmailValidationOnForgotPassword urlpatterns = [ path('login/', views.loginpage, name="login"), path('login-captcha/', views.logincaptcha, name="logincaptcha"), path('logout/', views.logoutuser, name="logout"), path('register/', views.registerpage, name="register"), path('verify-email/<uidb64>/<token>', views.verify_email, name="verify_email"), path('activate-account/<uidb64>/<token>', views.activate_account, name="activate_account"), path('set-new-password/<uidb64>/<token>', CompletePasswordReset.as_view(), name="reset-user-password"), path("request-reset-link/", RequestPasswordResetEmail.as_view(), name="request-password"), ] Views from django.conf import settings from .decorators import check_recaptcha from axes.decorators import axes_dispatch from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth import authenticate, login, logout from django.views import View @axes_dispatch def loginpage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user … -
IntegrityError: null value in column "column_id" of relation "table_model" violates not-null constraint DETAIL: Failing row contains
could some one help me i cant find where i did the mistake, my application name is firstapp and i am trying to make an interacting website where people post topics and reply to each other. When i go to a topic and try to reply to a topic after writing my relpy and pressing Post reply this error is shown to me: IntegrityError at /boards/2/topics/19/reply/ null value in column "Topic_id" of relation "firstapp_post" violates not-null constraint DETAIL: Failing row contains (29, my reply, 2021-10-07 07:04:44.068326+00, null, 2, null, null). i am using postgresql urls.py path('boards/<int:board_id>/topics/<int:topic_id>/reply/',views.reply_topic,name='reply_topic'), views.py @login_required def reply_topic(request, board_id,topic_id): topic = get_object_or_404(Topic,board__pk=board_id,pk=topic_id) if request.method == "POST": form =PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.topic = topic post.created_by = request.user post.save() topic.updated_by = request.user topic.updated_dt = timezone.now() topic.save() return redirect('topic_posts',board_id=board_id, topic_id = topic_id) else: form = PostForm() return render(request,'reply_topic.html',{'topic':topic,'form':form}) models.py class Board(models.Model): name = models.CharField(max_length=50,unique=True) description = models.CharField(max_length=150) def __str__(self): return self.name def get_posts_count(self): return Post.objects.filter(Topic__board=self).count() def get_last_post(self): return Post.objects.filter(Topic__board=self).order_by('-created_dt').first() class Topic(models.Model): subject = models.CharField(max_length=255) board = models.ForeignKey(Board,related_name='topics',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='topics',on_delete=models.CASCADE) created_dt = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) updated_by = models.ForeignKey(User,null=True,related_name='+',on_delete=models.CASCADE) updated_dt = models.DateTimeField(null=True) def __str__(self): return self.subject class Post(models.Model): message = models.TextField(max_length=4000) Topic = models.ForeignKey(Topic,related_name='posts',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_dt … -
Triggering Django thread as a background task
I have a Django app that needs to hit an API call towards an external endpoint on every 5 seconds for a check. Since I do not want to use any external tools like django-background-task, Redis, Celery, RQ or anything I built my own solution where I separated a thread for the task. This is the decorator I found here: def start_new_thread(function): def decorator(*args, **kwargs): t = Thread(target = function, args=args, kwargs=kwargs) t.daemon = True t.start() return decorator And this is how I call the function: JOB_IN_THE_QUEUE = False @start_new_thread def check_if_job_in_the_queue_and_enqueue(): """Checks if the job is already in the queue and enqueues it if needed.""" global JOB_IN_THE_QUEUE if JOB_IN_THE_QUEUE: return JOB_IN_THE_QUEUE = True success = print_something() # print_something() is just a dummy function And here is how I print indefinitely (that will later become an API call towards a 3rd party API): def print_something(): a = print_it() if not a: time.sleep(20) print_something() # print_something() is another dummy function with while True loop replacing the actual API calling Now the way I am currently calling the check_if_job_in_the_queue_and_enqueue() is at an endpoint. I am waiting for a get request that I am sending once Django is up to trigger the job … -
why Django filter giving me this error 'QuerySet' object has no attribute 'user_id'?
When I am using this queryset I am not getting any error and it's returning the user id UserProfile.objects.get(forget_password_token=forget_password_token) print(user.user_id) >>>19 But when I am using this queryset UserProfile.objects.filter(forget_password_token=forget_password_token) why I am getting this error QuerySet' object has no attribute 'user_id' what is difference between get and filter in Django ? why not working filter method here? -
Django slug No News matches the given query
I have a django program: Model: from django.db import models from autoslug import AutoSlugField #I installed third party package autoslug class News(models.Model): title = models.CharField(max_length=100, verbose_name='title') slug = AutoSlugField(populate_from='title',null=True, blank=True) def __str__(self): return self.title View: def newsDetailView(request, slug): news = get_object_or_404(News, slug=slug) def newsListView(request): news_list = News.objects.all() #some logic and return news# return render(request, 'news/index.html', { 'news':news }) url: path('<slug:slug>/', views.newsDetailView, name='detail'), template index.html: <a class="news-list text-dark" href="/{{news.slug}}/"> Error: Page not found (404) No News matches the given query. -
Whenever one model is created or updated, I want it to insert/modify its corresponding foreign key
Whenever "Note" is created OR modified, I want it to analyze its content and decide if it needs to either create, update, or delete its corresponding entry in "Review". I'm kind of stumped on how to do this. Should I be overriding the save() function to put that logic in there? Which save() should I be overriding - Models or Serializer or Views? Can someone please show me an example of how to link changes to Note create/modify an entry in Review? Models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class Note(models.Model): title = models.CharField(max_length=1000, blank=True) content = models.TextField() date_created = models.DateTimeField(auto_now=False,auto_now_add=True) date_updated = models.DateTimeField(auto_now=True,auto_now_add=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Review(models.Model): note = models.OneToOneField(Note, on_delete=models.CASCADE, primary_key=True) easiness = models.DecimalField(decimal_places=3,max_digits=6) interval = models.IntegerField() repetitions = models.IntegerField() due_date = models.DateField(auto_now=False,auto_now_add=False) last_reviewed = models.DateField(auto_now=True,auto_now_add=False) class User(AbstractUser): pass # Create your models here. Serializers.py class NoteSerializer(serializers.ModelSerializer): #title = serializers.CharField(max_length=1000, required=False) class Meta: model = models.Note fields = ('id','title','content','date_created','date_updated','author') class ReviewSerializer(serializers.ModelSerializer): note = NoteSerializer(read_only=True) class Meta: model = models.Review fields = ('easiness', 'repetitions', 'interval', 'due_date', 'last_reviewed', 'note') views.py class NoteViewSet(viewsets.ModelViewSet): queryset = models.Note.objects.all() serializer_class = NoteSerializer permission_classes = (IsAuthenticated,) def list(self, request): queryset = self.queryset.filter(author=request.user.id) serial = NoteSerializer(queryset, many=True) return … -
Django: Accessing Custom User Model(created according to Django Docs) to create a new user using new template(signup.html)
Here, I am placing what I have done following others post... I can create user from default admin site logging in and also by logging in using custom user model "MyUser". I want to use 'default' user model to create Admin users and want to use 'MyUser' user model to create all others users. From 3 days, I am trying but nothing works. Advance thanks for helping me. I am new in Django. As, I have found that the problems are in forms.py and views.py signup.html <div class="signup"> <div class="account-login"> <h1><a href="/login">CSP SignUp</a></h1> <form action="" class="login-form" name="signup_form" method="POST" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <input type="text" placeholder="Full Name" class="form-control username"> </div> <div class="form-group"> <input type="password" placeholder="Password" class="form-control username"> </div> <div class="form-group"> <input type="password" placeholder="Re-type Password" class="form-control username"> </div> <div class="form-group"> <input type="email" placeholder="e-Mail Address" class="form-control username"> </div> <div class="form-group"> <input list="gender" placeholder="Gender" class="form-control username"> <datalist id="gender"> <option value="Male"> <option value="Female"> <option value="Common"> </datalist> <input list="country" placeholder="Country" class="form-control username"> <datalist id="country"> <option value="Afghanistan"> <option value="Albania"> <option value="Algeria"> <option value="Andorra"> <option value="Angola"> <option value="Antigua and Barbuda"> <option value="Argentina"> <option value="Armenia"> <option value="Australia"> <option value="Austria"> <option value="Azerbaijan"> <option value="Bahamas"> <option value="Bahrain"> <option value="Bangladesh"> <option value="Barbados"> <option value="Belarus"> <option value="Belgium"> <option value="Belize"> <option value="Benin"> <option … -
Heroku can't import settings, but my computer can do it normally?
I'm deploying a Django application with Heroku. I have to import settings.py to wsgi.py. However, whenever I run WSGI.py on my computer, it runs normally. But heroku can't import this file and I have no idea what's happening. This is what shows up when I run heroku logs --tail: 2021-10-07T03:57:47.989483+00:00 app[web.1]: ModuleNotFoundError: No module named 'settings' This is the folder strucute: This is WSGI.py: import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') application = get_wsgi_application() As I've said before, if I run WSGI.py alone on my computer, it works and it finds settings.py normally. But Heroku can't find it. -
Django Table Data Overlay
I am not sure if this is even possible in Django. I would like to "overlay" the data on one table with data from another based on permissions. Table 1: pk col1 col2 isEditable 0 10 4 True 1 42 1 False 2 12 2 False Table 2 would have exactly the same structure minus the isEditable column. Any attempt to write data to a row where isEditable=False will be redirected to Table 2. I am calling this data overlay, but is there a proper term for doing this and is it possible to do in Django? If so what are the best practices for doing this? I am thinking of something involving signals, but I am very new to this part of Django. If it helps the back end database is MySQL V8.0. -
Problem with installing and integrating LDAp with django
i am having issues with integrating ldap with django and if there is a possibility if you could help. Below is what i get back when i put pip install . and whether there is any alternative way of integrating ldap with django. Thanks in advance. By the way im trying to do this in the virtual enviroment i have created. ERROR: Command errored out with exit status 1: command: 'C:\Users\farza\AppData\Local\Programs\Python\Python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\farza\AppData\Local\Temp\pip-install-9_s78z_y\python-ldap_543b61fd07204c1bae7f83e89bdfea54\setup.py'"'"'; file='"'"'C:\Users\farza\AppData\Local\Temp\pip-install-9_s78z_y\python-ldap_543b61fd07204c1bae7f83e89bdfea54\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\farza\AppData\Local\Temp\pip-record-p6gh3zcu\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\farza\AppData\Local\Programs\Python\Python39\Include\python-ldap' cwd: C:\Users\farza\AppData\Local\Temp\pip-install-9_s78z_y\python-ldap_543b61fd07204c1bae7f83e89bdfea54 Complete output (80 lines): running install running build running build_py creating build\lib.win-amd64-3.9 copying Lib\ldapurl.py -> build\lib.win-amd64-3.9 copying Lib\ldif.py -> build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\ldap copying Lib\ldap\async.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\asyncsearch.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\cidict.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\compat.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\constants.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\dn.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\filter.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\functions.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\ldapobject.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\logger.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\modlist.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\pkginfo.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\resiter.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\sasl.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap\syncrepl.py -> build\lib.win-amd64-3.9\ldap copying Lib\ldap_init_.py -> build\lib.win-amd64-3.9\ldap creating build\lib.win-amd64-3.9\ldap\controls copying Lib\ldap\controls\deref.py -> … -
Django -- Checking input type, display error message if wrong
I'm new to learning Django/Python and hoping for some assistance. This is for an assignment and I'm stumped on the last part. We need to take input from the user (name as string; weight, height inches, and height feet as ints) and calculate the bmi, displaying {{name}}'s bmi is {{bmi}} I have that part working fine, but the second part of what I have to do is check that the input is valid, that is not a string where it should be an int, and not a negative number. I am supposed to put this into the class. I was reading about is_valid() but I haven't used that yet and am not entirely sure how to do it. I am guessing it will have to be an if else statement. views.py class Home(View): def get(self, request): return render(request, 'home.html') def post(self, request): n = str(request.POST["name"]) w = int(request.POST["weight"]) hi = int(request.POST["heightinches"]) hf = int(request.POST["heightfeet"]) h = (hf*12) + hi bmi = (703*w) / (h*h) return render(request, 'response.html',{"name":n,"heightinches":hi,"heightfeet":hf,"weight":w,"height":h,"bmi":bmi} home.html {% load static %} <html> <head><title>Home</title></head> <body> <h1>Hello Repl.it</h1> <form action="" method="post"> {% csrf_token %} name: <input type="text" name="name" id="name"/> <br> weight: <input type="text" name="weight" id="weight"/> pounds<br> height: <input type="text" name="heightinches" id="heightinches"/> … -
Django API Framework for POST not working?
I have the following code: models.py class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname serializers.py class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = ['mgt_interface', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] views.py @api_view(['PUT']) def update_device(request, pk=None): if pk != None: devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk) devdserializer = DeviceDetailSerializers(devicedetail, data = request.data) if devdserializer.is_valid(): devdserializer.save() results = { "device_details" : devdserializer.data, } return Response(results, status=status.HTTP_201_CREATED) return Response(devdserializer.errors, status=status.HTTP_400_BAD_REQUEST) The code seems correct to me but whenever i tried to use Postman to do the PUT, i get error of 500. I dont understand why is this happening. For the code, I am using https://www.youtube.com/watch?v=B65zbFro2pU to guide me on how to code as I am new to this framework. Can anyone advise me on what to do to solve this error? Thank you … -
Django Paypal Integration createOrder curl
I'm trying to implement paypal in Django without any SDK or package. https://developer.paypal.com/docs/business/checkout/server-side-api-calls/create-order/ Want to rewrite this cURL curl -v -X POST https://api-m.sandbox.paypal.com/v2/checkout/orders \ -H "Content-Type: application/json" \ -H "Authorization: Bearer Access-Token" \ -d '{ "intent": "CAPTURE", "purchase_units": [ { "amount": { "currency_code": "USD", "value": "100.00" } } ] }' in pyhton: my current code: t = gettoken() d = {"intent": "CAPTURE","purchase_units": [{"amount": {"currency_code": "USD","value": "100.00"}}]} h = {"Content-Type: application/json", "Authorization: Bearer "+t} r = requests.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', headers=h, data=d).json() My Error: Internal Server Error: /createOrder ..... AttributeError: 'set' object has no attribute 'items' The Bearer Token is fine. Any idea? What i'm missing. -
What to include for Djoser to accept my requests?
I used DRF and Djoser for my authentication in React SPA. My question is why does it says forbidden and CSRF verification failed. what should I include to my request to grant access to my django server. export const addDummy = (data) => apiCallBegan({ url: '/product/dummy/', method: 'post', data: data, onSuccess: dummyAddedSuccess.type, onError: dummyAddedFailed.type, }); Is there a header that I should put or something? Please I'm new to djoser, django and drf.