Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Unable to Redirect to Update Form and Update Values
I've prepared a django app that would take input from user after the user logs in. Once the user logs in they can input values to form and post it to db. However, I need to provide user the capability to update the already existing entry based on conjugate primary key Station and Date. I've added a update button on page form to update entry in case if user inputs values for already existing primary key. I need to achieve two things Enable update button only if user inputs values for already existing primary key. Though update button is enabled but I am unable to redirect to update_form page. Currently I am unable to figure out why can't I redirect to update_form page. I am getting following error django.urls.exceptions.NoReverseMatch: Reverse for 'update_form' with arguments '('',)' not found. 1 pattern(s) tried: ['\\^\\(\\?P(?P<pk>[^/]+)\\[0\\-9\\]\\+\\)/update_form/\\$$'] Following are all relevant scripts being used: Models.py from django.db import models from django import forms from django.db import models from django.conf import settings from django.contrib.auth.models import User # Create your models here. class ManHour(models.Model): class Meta: unique_together = (('date', 'station'),) station_choices = ( ('KHI','Karachi'), ('ISB', 'Islamabad'), ('LHE','Lahore'), ) station = models.CharField( max_length=3, choices=station_choices, ) date = models.DateField() date_time … -
upload a test file using moto and boto3
I want to test conduct testing on imported files from aws. I mock s3 using moto, in order to not mess with actual data. However, now the aws seems to be empty, thus I decided to upload some test file on mocked s3. How can I do so? This is my setup, Conftest.py: @pytest.fixture(scope='function') def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ['AWS_ACCESS_KEY_ID'] = 'testing' os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing' os.environ['AWS_SECURITY_TOKEN'] = 'testing' os.environ['AWS_SESSION_TOKEN'] = 'testing' @pytest.fixture(scope='function') def s3(aws_credentials): with mock_s3(): yield boto3.client('s3', region_name='us-east-1') Test file: class TestLoadRecommendations: @pytest.fixture(autouse=True) def _setup(self, s3): self.bucket = s3.create_bucket(Bucket=settings.SERVER_DATA_S3_BUCKET) self.bucket.upload_file("tmp/recommendations-2021-04-13T17_28_06.csv", "tmp/recommendations-2021-04-13T17_28_06.csv") However, instead uploading it throws an error TypeError: expected string or bytes-like object but I am sure that I use incorrect command for file upload. Could anybody help? Thanks! -
Django: Camera does not work when in production, 500 Internal Server Error
!!First, to say that I am aware there are similar issues here, but I was not able to find a solution!! I have deployed my Django app and it works fine except for the camera function. It works fine locally but not on the server. The relevant code is: views.py . . from .camera import VideoCamera def display_camera_frame(request): camera = VideoCamera() response = StreamingHttpResponse(start_camera(camera), content_type='multipart/x-mixed-replace; boundary=frame') return response def start_camera(camera): frame_index = 0 while True: frame = camera.get_frame() if frame_index%10 == 0: with open(f"{settings.STATICFILES_DIRS[0]}/images/face", "wb+") as f: f.write(frame) f.close() frame_index+=1 yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') Django HTML Page <img id="face_image" width="510" height="360" src="{% url 'app:display_camera_frame'%}"> And when on browser (in production), it displays the code in the Inspect tab like this: <img id="face_image" width="510" height="360" src="/display_camera_frame/"> I would really appreciate any help :) -
How do i check for duplicates in django sqlite database
I'm working on a django website for movie site, which uses an api to fetch relevant data about specific movies and saves them to django sqlite3 database. However it seems each time i refresh the page the request to the api gets sent again and the data keeps on adding itself to the database. How can i validate the parameters so anytime i make a request it checks if it exists in the database and if it does it just renders directly from the database? This is the home view function def home(request): query = request.GET.get("title") all_movies = None if query: name = request.GET['title'] # url = 'http://www.omdbapi.com/?apikey=7531b4db&s='+name+'' url = 'https://api.themoviedb.org/3/search/movie?api_key=73b26cd6e71f57e195d7a253e3911b74&language=en-US&query='+name+'&page=1&include_adult=false' response = requests.get(url) data = response.json() movies = data['results'] poster_link = 'https://image.tmdb.org/t/p/w500' for i in movies: movie_data = MovieClass( title = i['original_title'], year = i['release_date'], rating = i['vote_average'], poster = poster_link + str(i['poster_path']), description = i['overview'] ) movie_data.save() all_movies = MovieClass.objects.all().order_by('-id') all_movies = MovieClass.objects.filter(title__icontains=query) else: url_display = 'https://api.themoviedb.org/3/movie/popular?api_key=73b26cd6e71f57e195d7a253e3911b74&language=en-US&page=1&' response = requests.get(url_display) data = response.json() movies = data['results'] poster_link = 'https://image.tmdb.org/t/p/w500' for i in movies: movie_data = MovieClass( title = i['original_title'], year = i['release_date'], rating = i['vote_average'], poster = poster_link + str(i['poster_path']), description = i['overview'] ) movie_data.save() all_movies = MovieClass.objects.all().order_by('-id') … -
How to make a sidebar sticky?
I have a site that has a bootstrap 4 navbar on top, which has the class "sticky-top". It does not have a fixed height, as far as I know. Below that I have a container-fuid div and in it a sidebar on the left and a main div to the right. I would like to have that sidebar on the full height, meaning from the bottom of the navbar to the bottom of the page and at the same time I would like it to remain sticky, when I am scrolling down in the main window. I have tried a lot with "position: sticky" and so on, but until now I did not find the right class or properties to get this working. Do you have advice for me? -
Django - How to sort Post model by votes?
I'm trying to sort posts in views.py with the greatest number of votes at the very top to the least at the bottom. Here's what I have so far: Post model in models.py class Post(models.Model): title = models.CharField("HeadLine", max_length=256, unique=True) creator = models.ForeignKey(User, on_delete= models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) url = models.URLField("URL", max_length=256,blank=True) description = models.TextField("Description", blank=True) votes = models.IntegerField(null=True) comments = models.IntegerField(null=True) def __unicode__(self): return self.title def count_votes(self): self.votes = Vote.objects.filter(post = self).count() @property def sort_by_votes(self): return Vote.objects.filter(post = self).count() def count_comments(self): self.comments = Comment.objects.filter(post = self).count() list of posts in views.py def NewPostListView(request): posts = sorted(Post.objects.all(), key=lambda p: p.sort_by_votes, reverse = True) for post in posts: post.count_votes() print(post) post.count_comments() context = { 'posts': posts, } return render(request,'postlist.html', context) I'm trying to do the equivalent of posts = Post.objects.all().order_by('count_votes'), but I get a "Cannot resolve keyword" error. So far, using the sorted() seems to work, but then after upvoting a post, the list gets out of order. How can I get a QuerySet to sort posts by votes? -
Add a field to serializer context
I have a retrieveAPIView and I have to set one of its field to the serializer_context class FoodRetrieveAPIView(RetrieveAPIView): serializer_class = serializers.FoodRetrieveSerializer permission_classes = [IsAuthenticated] queryset = models.Food.objects.all() def get_serializer_context(self): context = super().get_serializer_context() delivery_date = self.get("delivery_date") context["delivery_date"] = delivery_date And in my serializer, I have to access the context class FoodRetrieveSerializer(serializers.ModelSerializer): items = FoodItemSerializer(many=True) class FoodItemSerializer(serializers.ModelSerializer): item = serializers.SerializerMethodField() def get_item(self, obj): return ItemValueRetrieveSerializer( instance=obj.get_item(), many=False, context=self.context ).data class ItemValueRetrieveSerializer(serializer.ModelSerializer): value = serializers.SerializerMethodField() def get_value(self, obj): delivery_date = self.context.get("delivery_date") food_value = obj.get_food_value(delivery_date=delivery_date) I've been trying this way a couple of times but i can't still get the value of delivery_date in context. How can i do this? Thanks! -
Django REST filter backend exclude
I am trying to use django-filter in rest framework. Following django rest framework. this is my views. import django_filters.rest_framework from django.contrib.auth.models import User from myapp.serializers import UserSerializer from rest_framework import generics class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filterset_fields = ['name'] it's currently filter with name. Now i am trying to exclude in filter. like if a user in particular city, they will not appear in search. I am not getting how to add exclude method. like we can add User.objects.exclude(city='nyc') Can anyone help? -
Call Django Rest Framework Pagination API URL in Frontend
I wanted to implement pagination using Django Rest Framework API URL. I know how to implement Django Pagination without Django Rest Framework, but now I wanted to do it with Django Rest Framework. Furthermore, I have created an API URL that include next and previous page links, I don't know how to use those links when the next page button was clicked. I don't want to extend the result to the same page I wanted to display the data that presented in each page. models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f'{self.title}' class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey( Todo, on_delete=models.CASCADE, related_name='tasks') date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f'{self.heading}' serializers.py from django.contrib.auth.models import User from rest_framework import serializers from drf_writable_nested.serializers import WritableNestedModelSerializer from .models import Todo, Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username'] class TodoSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): tasks = TaskSerializer(many=True, allow_null=True, required=False) class Meta: model = Todo fields = ['id', 'title', 'date_created', 'completed', 'user_id', 'tasks'] views.py @login_required def list(request): return render(request, 'todo/main.html') class IncompleteTodoPagination(PageNumberPagination): page_size … -
how to take xml file as input in angular with backend in django
I m working on a project. it has frontend in angular and backend in Django. I need to take xml file as input and display it in a table formate. and also save it in database that is in Django. Can you help with that? or show me how to do so. -
python how to sort a list
i have to display a list shift wise like have to first show all day shift results then afternoon then night but now it shows afternoon first then night then day here is my code views.py: def get_queryset(self): getall = self.request.GET.get("getall") if self.request.user: versions = LogVersion.objects.filter( form__airport__id=self.request.user.aerosimple_user.airport_id ).exclude(status=DRAFT) filters = self.request.GET.get("filters") tags = self.request.GET.get("tags") logs = Log.objects.none() result = Log.objects.none() for v in versions: if len(v.operation_logs.order_by('-id').all())>0: result = result | v.operation_logs.order_by('-id').all() result = result.exclude(shift_name = None).exclude(shift_name='') # if getall: if getall: return Log.objects.filter( form__form__airport__id=self.request.user.aerosimple_user.airport.id) if filters is not None: filters = filters[:-2] if filters[-2:] == ',,' else filters filters_list = filters.split(',,') for filters in filters_list: log = result.filter(Q(type = filters) | Q(subtype = filters)) if filters == 'Inspection Completed': log = result.filter(Q(description = filters)) elif log != []: for r in result: if r.tags is not None and filters in r.tags: log =result.filter(id=r.id) else: log = result.filter(Q(type = filters) | Q(subtype = filters)) logs = logs | log return logs.all() return result how to sort it correctly -
Erro in reset password heroku app, why resolve?
This is image my error for reset password in app heroku. My application not reset password for clients, this application in stack heroku-16: enter image description here This is Traceback error: Environment: Request Method: POST Request URL: http://envio.canalcurta.tv.br/recover/ Django Version: 1.8.3 Python Version: 3.6.4 Installed Applications: ('adminactions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'raven.contrib.django.raven_compat', 'compressor', 'widget_tweaks', 'import_export', 'submission.account', 'submission.frontend', 'submission.content', 'submission.location', 'password_reset', 'django_object_actions') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py" in post 215. return self.form_valid(form) File "/app/.heroku/python/lib/python3.6/site-packages/password_reset/views.py" in form_valid 90. self.send_notification() File "/app/.heroku/python/lib/python3.6/site-packages/password_reset/views.py" in send_notification 86. [self.user.email]) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/init.py" in send_mail 62. return mail.send() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/message.py" in send 303. return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py" in send_messages 100. new_conn_created = self.open() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py" in open 67. self.connection.login(self.username, self.password) File "/app/.heroku/python/lib/python3.6/smtplib.py" in login 721. initial_response_ok=initial_response_ok) File "/app/.heroku/python/lib/python3.6/smtplib.py" in auth 631. (code, resp) = self.docmd("AUTH", mechanism + " " + response) File "/app/.heroku/python/lib/python3.6/smtplib.py" in docmd 421. return self.getreply() File "/app/.heroku/python/lib/python3.6/smtplib.py" in getreply 394. raise SMTPServerDisconnected("Connection unexpectedly closed") Exception Type: SMTPServerDisconnected at /recover/ Exception Value: Connection unexpectedly closed -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.CustomUser'
I am trying to change the user email and password from template. But normally signup is worked for new user. But while i tried to change email or password, it's shows AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.CustomUser' I looked few solutions in stackoverflown where asked to add User = get_user_model() But it shows another error AUTH_USER_MODEL refers to model 'user.CustomUser' that has not been installed , evenhought user is registered in my settings.py user/models.py: from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) extra_fields.setdefault('is_active', False) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser … -
Store friend request after accept ( In Database )
I am building a Social Media App and I am trying to store friend requests in Database after accept or Reject. What i am trying to do :- When user_1 send friend request to user_2 then in Admin it stores sent or received friend requests until accept or Reject. AND after accept or Reject it deleted from the DataBase. BUT i want to store requests permanently. So i can see all the requests sent or received by request.user. models.py class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='to_user',on_delete=models.CASCADE) from_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='from_user',on_delete=models.CASCADE) views.py def send_friend_request(request,user_id): user = get_object_or_404(User,id=user_id) frequest, created = FriendRequest.objects.get_or_create(from_user=request.user,to_user=user) return redirect('friends',user_id=user_id) def accept_friend_request(request,user_id): user1 = frequest.to_user user2 = from_user from_user = get_object_or_404(User,id=user_id) frequest = FriendRequest.objects.filter(from_user=from_user,to_user=request.user).first() user1.profile.friends.add(user2.profile) user2.profile.friends.add(user1.profile) if(FriendRequest.objects.filter(from_user=request.user,to_user=from_user).first()): request_rev = FriendRequest.objects.filter(from_user=request.user,to_user=from_user).first() request_rev.delete() frequest.delete() return redirect('mains:friendsq',user_id=user_id) What have i tried :- I have also tried by adding another instance in FriendRequest Model BUT it is not saving in the Admin. I have no idea, How can i do it. Any help would be Appreciated. Thank You in Advance. -
html , django - I want to show sum of subtotal in my template
I want to show sum of subtotal in my template. </head> <body> <table bordercolor="white" width ="800" height="150" align = "center" > <p><td align = "center" style="color:gray">user</td></p> <tr align = "center" > <td bgcolor="#d3d3d3" style="color:black">user total</td> <td style="color:black">{{??????}}</td> ## User.objects.count() </tr> </table> </body> </html> I want to put the total number of members in the template({{??????}}), what should I do? -
Is request.session a best practice to pass data between views?
I want to pass data from one form to another using redirect The first view - is an initial form The second view - is a preview form the third view will record data in a database. I read here that I can use request.session Django: How do I redirect a post and pass on the post data but is it secure or a best practice? -
how can I correct and improve one or more python-coded programs with django as a professional [closed]
my internship is to improve and correct a program coded in python and django, so I would like to know what are the best documentations I can consult in order to complete my internship and have more knowledge. certainly I already have a notion of python and django, I followed some self-training like elephorm, I know the concept poo etc..., but the fact of making a code easy and improve escapes me and I do not know what to do. a little snippet of what I was able to improve # avant log elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.XPATH, "/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[1]/td[2]/select/option[2]")) ) elem.click() elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.XPATH, "/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td/button/span")) ) elem.click() # entering credentials elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.ID, "gwt-debug-InputLoginUsername")) ) elem.clear() elem.send_keys(log) elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.ID, "gwt-debug-InputLoginPassword")) ) elem.clear() elem.send_keys(pwd) elem.click() elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.XPATH, "/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[4]/td[2]/select/option[2]")) ) elem.click() elem.click() elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.XPATH, "/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[6]/td/table/tbody/tr/td[1]/button/span")) ) elem.click() # miditra ao am rapport elem.click() elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.XPATH, "/html/body/table[3]/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr/td[6]/table/tbody/tr[2]/td[2]/div/div/div")) ) elem.click() # misafidy option campaign activation details elem.click() elem = WebDriverWait(driver, 15).until( EC.presence_of_element_located( (By.XPATH, "/html/body/table[3]/tbody/tr/td/table/tbody/tr[2]/td/div/div[5]/table/tbody/tr[2]/td/div/div[1]/div/div/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[4]/td[1]/select/option[11]")) ) elem.click() after correction by_xpath_lst =["/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[1]/td[2]/select/option[2]","/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[2]/td/button/span", "/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[4]/td[2]/select/option[2]","/html/body/div[2]/div/table/tbody/tr[2]/td[2]/div/table/tbody/tr[6]/td/table/tbody/tr/td[1]/button/span", "/html/body/table[3]/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr/td[6]/table/tbody/tr[2]/td[2]/div/div/div","/html/body/table[3]/tbody/tr/td/table/tbody/tr[2]/td/div/div[5]/table/tbody/tr[2]/td/div/div[1]/div/div/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[4]/td[1]/select/option[11]"] by_id_lst = ["gwt-debug-InputLoginUsername","gwt-debug-InputLoginPassword"] def by_xpath(i=0, bid=0): if i < … -
Django form set form local variable 'Itemformset' referenced before assignment
the form is rendering fine, but if I click on save I got this error: local variable 'Itemformset' referenced before assignment I using the same syntax as I uses in the other form views, and it makes no differences if I use it with the if else loop in the end: views: Itemform = modelformset_factory(OrderItems, form=OrderItemsForm, extra=ProductsCount) # if this is a POST request we need to process the form data if request.method == 'POST': Orderform = EditOrderForm(request.user.id, choosen_customer_int, request.POST) Formset = Itemform(request.POST) print(Formset.errors) if Orderform.is_valid() and Formset.is_valid(): edit_form = Orderform.save() Formset.save() edit_order_id = edit_form.pk request.session['edit_order_id'] = edit_order_id ... else: Orderform = EditOrderForm(request.user.id, choosen_customer_int, initial={'OrderNo': order_no_int, 'Customer': choosen_customer_int, 'PaymentMethod': choosen_payment_methode, 'ShippingMethod': choosen_delivery_methode, 'ShippingAddress': choosen_shipping_address, 'BillingAddress': choosen_billing_address}) if choosen_products: Itemformset = Itemform(form_kwargs={'user': request.user.id}, initial=[{ 'Item': product.ID, 'Quantity': choosen_quantity, 'Price': product.Price, 'OrderNo': order_no_int} for product in choosen_products ]) else: Itemformset = Itemform(form_kwargs={'user': request.user.id}) return render( request, 'backend/add_order.html', { 'title': 'WestcoastShop - Backend', 'Orderform': Orderform, 'Itemformset': Itemformset, -
What is the command line to install djoser on anaconda
What is the command line to install djoser library on anaconda? I have tried conda install djoser but no library found -
How to use JS webSocket.onmessage with Django Channels
I am attempting to us JS websockets with Django Channels. Data is sending from JS to channels just fine, but receiving is not working. When I attempt to receive (using wSocket.onmessage) the location where I call onmessage() shows an error (e.data is undefined) but the alert(e.data) inside onmessage() shows that the data is present. How do I get the data from wSocket.onmessage() ? const wSocket = new WebSocket( 'ws://127.0.0.1:8000/SCRUM' ); function on_drag_start(e){ e.dataTransfer.setData('text/plain', e.target.id); e.currentTarget.style.backgroundColor = 'white'; e.currentTarget.style.border = 'thick solid aqua'; } function on_dragover(e){ e.preventDefault(); } function on_drop(e){ const id = e.dataTransfer.getData('text'); const draggableElement = document.getElementById(id); draggableElement.style.border = ''; const dropzone = e.target; console.log(e.dataTransfer.getData('text')); wSocket.send(JSON.stringify({ 'column': dropzone.id, 'task': id, 'new': false, })); dropzone.appendChild(draggableElement); e.dataTransfer.clearData(); } wSocket.onmessage = function(e){ alert(e.data); return(e.data); } wSocket.onclose = function(e){ console.error('Web Socket Closed'); console.error(e); } window.onload = function(){ var list = document.getElementsByClassName('add'); function add_item(id, button){ let item = document.createElement("textarea"); button.style.display = "none"; item.setAttribute('id', "t-area") let parent = document.getElementById(id); item.innerHTML = "added item"; parent.appendChild(item); let input = document.getElementById('t-area'); input.addEventListener('keypress', function(e){ if(e.key === 'Enter' && !e.shiftKey){ e.preventDefault(); var div = document.createElement('div'); div.innerHTML = input.value; div.setAttribute('class', 'task'); div.setAttribute('draggable', 'true'); div.setAttribute('ondragstart', 'on_drag_start(event)'); input.replaceWith(div); button.style.display = "inline"; wSocket.send(JSON.stringify({ 'column': backlog, 'name': input.value, 'new': true, })) var rec = wSocket.onmessage() div.setAttribute('id', … -
Django Check is a Model Field has chocies defined or not
I have a model class StudentEfficacy(models.Model): class FatherEducation(models.IntegerChoices): NoEducation = 0, _("No Education") PrimaryEducation = 1, _("Primary Education") SecondaryEducation = 2, _("Secondary Education") GraduateStudy = 3, _("Graduate Study") PostGraduateStudy = 4, _("Post Graduate Study") DoctorOfPhilosophy = 5, _("Doctor of Philosophy") student_efficacy_id = models.AutoField(primary_key=True) father_education = models.IntegerField(choices=FatherEducation.choices) study_time = models.IntegerField("Study Time in mins") I want to dynamically check if the field has choices defined. for example I want to do something like below: stud = StudentEfficacy.objects.get(pk=1) if stud.father_education has choices defined: print(stud.father_education) elif not stud.study_time has choices defined: print(stud.study_time) Actually in the example above I have given fixed models and fields but actual use would be like below: for model_inst in models_list: for field in model_field_list[model_inst._meta.verbose_name] if model_inst.getattr(field) has choices defined: print("Something") else: print("Something else") -
Return live search results in order of keystrokes - Django and JavaScript
I am trying to build a search bar that allows user to search database for the names of stored venues. I want it to be a live search that returns results as the user types. Similar to google. I have gotten the feature almost complete, it dynamically returns venues as the user types and returns venues that contain the letters being typed. Problem: I can't figure out how to return venues that contain letters IN ORDER of typing. Example from google. How mine shows up. Here is my JS Function: const search = function() { let searchTerm = document.getElementById("search-box").value; $.ajax({ type: 'GET', url: '/electra/search/', data: { 'search_term': searchTerm }, success: function(data) { data.forEach(([cafeName]) => { var cafeName = cafeName; var searchList = $( `<div> <ul class="list-item border-top" data-idtext="${cafeName}" id="${cafeName}">${cafeName}</ul> </div>` ); searchList.appendTo('#search-results'); }); $("ul").click(function(event) { var selectedVenue = event.target.id; $("#search-results").empty() getVenueDetails(selectedVenue) }); } }); }; And here is the views.py function: def search(request): template_name = 'testingland/write_image.html' search_term = request.GET.get('search_term', None) print(search_term) qs = mapCafes.objects.filter(cafe_name__icontains = search_term)[0:5] return JsonResponse([ [cafe.cafe_name] for cafe in qs ], safe=False) -
how to subtract two DateTime field in django model and keep the subtracted value in another field in same model?
class Attendance(EmployeFields): employee_id = models.IntegerField(blank=True, null=True) login_date = models.DateTimeField(blank=True, null=True) logoff_date = models.DateTimeField(blank=True, null=True) hours_per_day = models.FloatField(blank=True, null=True) i need to subtract logoff_date and login_date and put the value to hours_per_day while importing the date to this model. i am importing the data for this model which have entries for both login_date and logoff_date . i have tried to do like this but the function itself was not calling. def save(self, force_insert=False, force_update=False, using=None,update_fields=None): if self.login_date and self.logoff_date: logger.info(self.logoff_date) self.hours_per_day = (self.logoff_date - self.login_date).seconds // 3600 else: self.hours_per_day = 0 return super(Attendance, self).save(force_insert, force_update, using, update_fields) -
which mehtod i should use , While saving comments as shown below?
I am beginner and i am using django to build ecommerce site , Considering the security, Please check my code and do let me know which mehtod i should use while saving User Reviews, Here i am trying to save Reviews using two case , please go through the code , your support will be appriciated //MOdels.py class Review(models.Model): comment = models.CharField(max_length=500) Ratings = models.IntegerField() course = models.ForeignKey(Course,on_delete=models.CASCADE) datePublished=models.DateTimeField(default=datetime.datetime.today) //***method for case 01*** def Check_comment(self): if Review.objects.filter(comment=self.comment): return 'comment allready exists' else: return 'comment does not exists' //***method for case 02*** def check_comment(self): if Review.objects.filter(comment = self.comment): return True return False **case(01)** // view.py def review(request,slug): if request.method =='POST': comment = request.POST['comment'] rating = request.POST['rating'] review = Review (comment = comment, Ratings = rating, course = Course.objects.get(slug = slug)) if review.Check_comment() == 'comment allready exists': return HttpResponse ("simillar comment exists") if review.Check_comment() == 'comment does not exists': review.save() return HttpResponse ('comment added sucessfully') else: newcourse = Review.objects.filter(course=Course.objects.get(slug=slug)).order_by('- datePublished') return JsonResponse (serializers.serialize('json',newcourse),safe=False) **case(02)** //view.py def review(request,slug): if request.method =='POST': comment = request.POST['comment'] rating = request.POST['rating'] review = Review (comment = comment, Ratings = rating, course = Course.objects.get(slug = slug)) if review.Check_comment() : return HttpResponse ('simillar comment all ready exists') else: review.save() … -
Django Allauth sign up event with Google analytics
Trigger events on successful sign up & sign in Trying to track a user that successfully signs up with a social account, using Google analytics and Google tag manager. Have you achieved this using these tools? So far I am thinking something along these lines, and then passing the login success as a url parameter. This doesn't seem like the most elegant solution and does not solve the issue of identifying a new user vs an existing user. Any help appreciated.