Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
make a new object in django restframework
i have this model class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField() i want make a new object using post method in restframework in django but i dont know what should i do please help me @api_view(['POST']) def create_product(request): ******* return Response({ ******* }, status=status.HTTP_201_CREATED) i should replace django code by **** please help me -
Querying the avg of a decimal field and doing top 10, issue on the amount of decimals
So my issue is that i made the following query, and i am trying to display it on a table. The query is supposed to bring the average of the margem_de_lucro (profit) field per type of vehicle therefore marca(brand), modelo (model) and ano (year of the car) need to be ordered by too or else, the table simply doesnt adjust, unfurtunately i am having trouble getting the average part to display correctly the number doesnt limit itself on the decimal fields and for what i can see it doesnt actually display the average. I am not sure what the problem is and i dont know how to limit it, would appreciate any help! Here is the query, query4= DataDB.objects.values('marca','modelo','ano','margem_de_lucro').annotate(medias=Avg('margem_de_lucro')).order_by('-medias')[:10] Here is the modal, of the called parts marca=models.CharField(max_length = 30,error_messages={'required':'Favor inserir uma marca'}) modelo=models.CharField(max_length = 60,error_messages={'required':'Favor inserir um modelo'}) ano=models.IntegerField( validators=[MinValueValidator(1960,'Favor inserir acima 1960.'), MaxValueValidator(2023,'Favor inserir abaixo 2023.')], error_messages={'required':'Favor inserir uma ano'}) margem_de_lucro=models.DecimalField(max_digits= 12,decimal_places=3,max_length= 12) And here is the table <table class="table table-striped table-dark" width="100%"> <thead> <th>Marca</th> <th>Modelo</th> <th>Ano</th> <th>Média de lucro</th> </thead> {%for q in query4 %} <tr> <td>{{q.marca}}</td> <td>{{q.modelo}}</td> <td>{{q.ano}}</td> <td>{{q.medias}}</td> </tr> {% endfor%} </table> The end result is as follows, -
500 internal server error on Heroku, while webapp runs locally
I successfully deployed a personal Django+React project built on Heroku but when I load the URL to my Heroku app I immediately get a 500 internal server error. From the console in Chrome it looks like this: Failed to load resource: the server responded with a status of 500 (Internal Server Error) and is caused by calling the endpoint /spotify/is-authenticated. This is called in a useEffect-hook (React) to check if the user is already logged in when a user enters the web page. The code in the App component looks as follows: useEffect(() => { fetch('/spotify/is-authenticated') .then(response => response.json()) .then(data => { console.log(`authentication status: ${data.status}`) setAuthenticated(data.status) hideLoading() }) // eslint-disable-next-line react-hooks/exhaustive-deps }, []) From the Heroku logs, the error looks as follows: 2021-05-01T16:46:31.825334+00:00 heroku[router]: at=info method=GET path="/spotify/is-authenticated" host=nameless-taiga-02413.herokuapp.com request_id=f334e22d-26d3-4fe8-8252-8e2810e8c19f fwd="77.164.173.60" dyno=web.1 connect=0ms service=37ms status=500 bytes=411 protocol=https As instructed by Django's security warning comment, debug mode in settings.py is DEBUG = False When I run the project with heroku local everything is fine and I can't find out why the app can't seem to reach the /spotify/is-authenticated endpoint... -
How to write a paginator which would set a default page depending on the current date?
I have a huge list of lessons ordered by the date. I want to include paginator so it would always set default page on a current date(if such lessons exists, and if not the nearest future lessons).Is it even possible to do? from django.contrib.auth.models import Lesson from django.core.paginator import Paginator lesson_list = Lesson.objects.all().order_by('datetime') paginator = Paginator(user_list, 10) -
Choose the correct option. Your option is not among the valid values. Django python
when entering the correct value into input, it outputs: Choose the correct option. Your option is not among the valid values. the error is that when entering, you must specify the pk field for the Service model and then the model is saved. And how to make the comparison by the name field take into account when writing the form? models class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) used = models.IntegerField(default=0) def __str__(self): return self.name -
Django save a series of question and its corresponding answer set to database
I am a newbie in Django and I am working on a quiz functionality. I give the user an interface to create a quiz. It is based on a multi-step form. I input a certain number of questions and hit next. It displays that amount of fields for me to set the questions. Each question has 4 answers and I use radio buttons to select the right answer. The problem is I don't know how to retrieve them in my views when I hit the submit button. Like I want each question and its corresponding answers to be properly stored in the respective models. Can you guys please? It's lengthy but easy to grasp and some details can be overlooked as they are just fields :) Here is my code: models.py class PsychometricTest(models.Model): DIFF_CHOICES = ( ('easy', 'easy'), ('medium', 'medium'), ('hard', 'hard'), ) internship = models.ForeignKey(Internship, on_delete=models.CASCADE) name = models.CharField(max_length=120) description = models.TextField() number_of_questions = models.IntegerField() time = models.IntegerField(help_text="Duration of the quiz in minutes") required_score_to_pass = models.IntegerField(help_text="required score in %") difficulty = models.CharField(max_length=6, choices=DIFF_CHOICES) created = models.DateTimeField(auto_now_add=True) scheduled_date_time = models.DateTimeField() def __str__(self): return self.name+" - "+self.topic def get_questions(self): return self.question_set.all() class Question(models.Model): text = models.CharField(max_length=200) psychometric_test = models.ForeignKey(PsychometricTest, on_delete=models.CASCADE) created … -
Django Rest Framework - Efficient API Design
In any rest API, Data comes in request body We perform some Logic on data and perform some queries 3.finally API responds serialized data. My question is :- Where to put data processing Logic? And what is the efficient way of designing any REST API? -
Real time notification system with django and pyrebase
I built a django app for user and file management system which uses firebase as it's database via pyrebase. I want to build a notification system which will show events for each file upload, user changes and file changes. How can I assign these change events and show them in my html files? The notifications does not have to be real time but be a timestamp based event similar to all user. -
How to ORDER BY max no of same records in DJANGO
I want to order by movies in the Movies model according to the max number of occurrences of a tuple in the MyMovies model. models.py class Movies(models.Model): mid = models.CharField(max_length=255, primary_key=True) title = models.CharField(max_length=255, null=True, blank=True) rating = models.CharField(max_length=5, null=True, blank=True) type = models.CharField(max_length=255, null=True, blank=True) genre = models.CharField(max_length=255, null=True, blank=True) rdate = models.CharField(max_length=255, null=True, blank=True) language = models.CharField(max_length=255, null=True, blank=True) cover = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) sequal = models.CharField(max_length=255, null=True, blank=True) trailer = models.CharField(max_length=255, null=True, blank=True) year = models.CharField(max_length=5, null=True, blank=True) objects = models.Manager() def __str__(self) -> str: return self.title class MyMovies(models.Model): mid = models.ForeignKey(Movies, on_delete=CASCADE) uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True) watched = models.BooleanField() date = models.DateTimeField(auto_now_add=True) objects = models.Manager() view.py def showIndexPage(request): trending = list(MyMovies.objects.all().annotate(max_mid=Max(COUNT(mid))).order_by('-max_mid')) return render(request, 'index.html', {'trending': trending}) In the above code, MyMovies is my model with a foreign key mid referencing the Movie model. So, if in MyMovies there are 2 movies with mid 1, 4 movies with mid 2 and 1 movie with mid 3 Then the result should be a list (trending) of attributes of Movies which is ordered by no. of occurrences of a particular movie id: trending = [2, 1, 3] -
Following a tutorial I got a view retuning None instead because is_ajax is not working
I just started with ajax but can't seem to find the fix for this. I think it might have to do with the comment_id vs the blog_id. (followed this tutorial: https://www.youtube.com/watch?v=VoWw1Y5qqt8&list=PLKILtxhEt4-RT-GkrDkJDLuRPQfSK-6Yi&index=39&ab_channel=AbhishekVerma). This is what my views.py looks like def like_comment(request): comment = get_object_or_404(Comment, id=request.POST.get("comment_id")) blog = get_object_or_404(BlogPost, id=request.POST.get("blog_id")) comments = Comment.objects.filter(post=blog, reply=None) if request.user in comment.likers.all(): comment.likers.remove(request.user) else: comment.likers.add(request.user) context = { "comments": comments, "blog_post": blog, "body": markdown2.markdown(blog.body), "comment_form": CommentForm(), } if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) This is a snippet of my HTML {% if request.user.is_authenticated %} <form action={% url 'like_comment' %} method="POST"> {% csrf_token %} {% if user in comment.likers.all %} <input type="hidden" name="blog_id" value=" {{ blog_post.id }}"> <button type="submit" id="like" name="comment_id" value="{{ comment.id }}">Like</button> {% else %} <input type="hidden" name="blog_id" value=" {{ blog_post.id }}"> <button type="submit" id="like" name="comment_id" value="{{ comment.id }}">Dislike</button> {% endif %} {% else %} <div><small class="comment_time">Login to Like</small></div> {% endif %} </form> </div> <small class="comment_time">{{ comment.total_likes }} Likes</small> And this is the javascript: $(document).ready(function (event) { $(document).on('click', '#like', function (event) { event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: "POST", url: '{% url "like_comment" %}', data: { 'blog_id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function (response) { $('#like_section').html(response['form']) … -
How to I return JsonResponse from Paginator's page? Object of type Page is not JSON serializable
(this is my first stackoverflow question ever) I want to return JsonResponse from the dictionary "context" (seems to be a paginator Page) as coded below: myposts = userposts.all().values() myfollowers = userfollowers.ffollowers.all() myfollowings = userfollowers.ffollowings.all() context = {"posts": page_obj, "loops": range(1, totalpages + 1), "user": uprofile.username, "myposts": list(myposts), "mypostsnum": len(userposts.all()), "myfollowers": list(myfollowers), "myfollowersnum": len(userfollowers.ffollowers.all()), "myfollowings": list(myfollowings), "myfollowingsnum": len(userfollowers.ffollowings.all()) } this is the return I use: return JsonResponse(context, safe=False) Result I get: Object of type Page is not JSON serializable My question is how do I get JsonResponse from 'context'? -
Refused to apply style because its MIME type ('text/html') in django and next js
hello i did everything with integration but nothing seems working,its again saying the same error all next js files are default no changes settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'frontend/.next/static/css') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') pls help me find a solution to this problem i have done everything that i can do with this integration -
docker django django.db.utils.OperationalError: could not translate host name "thinkcentre" to address: No address associated with hostname
I am trying to create a docker, that run a django app which uses a Postgresql database on the same computer where I will be running the App . The database runs in current OS (Windows 10 Pro on that computer) and the docker accesses it but do not contains it. When I create my docker file and run it from another computer it works. When I create this same docker file on the computer that host the database I get thssi error: django django.db.utils.OperationalError: could not translate host name "thinkcentre" to address: No address associated with hostname My docker file is as followed: # For more information, please refer to https://aka.ms/vscode-docker-python # FROM python:3.7.10-slim-buster => couldn't install psygo2 dependencies FROM python:3.7.10 EXPOSE 7000 EXPOSE 5432 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # set up a venv ENV VIRTUAL_ENV=/opt/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" # install psycopg2 dependencies # RUN apk update # RUN apk add postgresql-dev gcc python3-dev musl-dev RUN apt update # \ # && apt add postgresql-dev gcc python3-dev musl-dev # Install pip requirements RUN pip install --upgrade pip … -
Django: Calculate avrage recipe rating
I am creating a website that lets users post recipes. When the user clicks on a recipe they can see more details about it and they can also comment and give a rating. My question is how can I calculate the average recipe rating**enter code here Models.py class Recept(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset() naslov = models.CharField(max_length=100) sestavine = models.CharField(max_length=100) priprava = models.TextField() rec_img = models.ImageField(upload_to='rec_pics', default='default2.jpg') datum = models.DateTimeField(default=timezone.now) avtor = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) likes = models.ManyToManyField( User, related_name="blog_recept", blank=True) favorites = models.ManyToManyField( User, related_name='favorite', default=None, blank=True) newmanager = NewManager() CHOICES = ( (1, '1 stars'), (2, '2 stars'), (3, '3 stars'), (4, '4 stars'), (5, '5 stars'), ) class Reviews(models.Model): recept = models.ForeignKey( Recept, related_name="reviews", on_delete=models.CASCADE) user = models.ForeignKey( User, related_name="reviews", on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) stars = models.IntegerField(choices=CHOICES) datum = models.DateTimeField(default=timezone.now) Views.py class PostDetailView(FormMixin, DetailView): model = Recept form_class = CommentForm def get_success_url(self): return reverse('recept-detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) get_recept = get_object_or_404(Recept, id=self.kwargs['pk']) fav = bool if get_recept.favorites.filter(id=self.request.user.id).exists(): fav = True total_sestavine = get_recept.vejice() total_likes = get_recept.total_likes() total_likes2 = get_recept.total_likes2() # pokliče functions liked = False if get_recept.likes.filter(id=self.request.user.id).exists(): liked = True if get_recept.likes.exists(): last_like = get_recept.last_like() context['last_like'] … -
Django and Css Link
I have Made A Project of website Django I want To Link It With css & html How I can Do That? I Want To Use Django Just Like Search Engine For Front-End -
django_crontab is adding my jobs, but they don't seem to execute. Anu solution?
I got a django project running with django-crontab (github) on Ubuntu 20. in <my_django_app> directory I added a cron.py file: from .models import <my_model> from datetime import datetime def remove_stamps(): for stamp in <my_model>.objects.order_by('-stop_date'): if stamp.can_be_removed(): stamp.delete() else: break def close_stamps(): for stamp in <my_model>.objects.filter(stop_date=None): stamp.stop_date = datetime.now() stamp.save() in settings: CRONJOBS = [ ('*/4 * * * *', '<my_django_app>.cron.remove_stamps'), ... ] CRONTAB_LOCK_JOBS = True I deployed the project as follows: First created a <new_user> in the command line with @root like this: adduser --system --home=/var/opt/<project_name> --no-create-home --disabled-password --group --shell=/bin/bash <new_user> Using Nginx I ran the virtual environment with this <new_user> using gunicorn like this: [Unit] Description=<project_name> [Service] User=<new_user> Group=<new_user> Environment="PYTHONPATH=/etc/opt/<project_name>:/opt/<project_name>" Environment="DJANGO_SETTINGS_MODULE=settings" ExecStart=/opt/<project_name>/venv/bin/gunicorn \ --workers=4 \ --log-file=/var/log/<project_name>/gunicorn.log \ --bind=127.0.0.1:8000 --bind=[::1]:8000 \ <project_name>.wsgi:application [Install] WantedBy=multi-user.target Next I added the django_crontab jobs using: PYTHONPATH=/etc/opt/<project_name>:/opt/<project_name> DJANGO_SETTINGS_MODULE=settings su <new_user> -c "/opt/<project_name>/venv/bin/python3 /opt/<project_name>/manage.py crontab add" Checking the crontab jobs with .... crontab show gives: <HASH KEY> -> ('*/4 * * * *', '<my_django_app>.cron.remove_stamps') <HASH KEY> -> ('*/5 * * * *', '<my_django_app>.cron.close_stamps') Using journalctl _COMM=cron --since="2021-5-1 14:00" to check if the job runs, gives following: May 01 17:00:01 ubuntu-2gb-hel1-2 CRON[276942]: pam_unix(cron:session): session opened for user <new_user> by (uid=0) May 01 17:00:01 ubuntu-2gb-hel1-2 CRON[276940]: pam_unix(cron:session): session … -
django CreateView forms not loading in html
I have found a lots of similar problems on this topics. None of them has proper solution. CreateView form from models not loading. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author: models.ForeignKey( User, on_delete=models.CASCADE, related_name='post_author') blog_title: models.CharField(max_length=264, verbose_name="Title") slug: models.SlugField(max_length=264, unique=True) blog_content: models.TextField(verbose_name="What is on your mind?") blog_image: models.ImageField( upload_to='blog_images', verbose_name='images') publish_date: models.DateField(auto_now_add=True) updated_date: models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title views.py from django.shortcuts import render, HttpResponseRedirect from django.views.generic import CreateView, DeleteView, UpdateView, ListView, DetailView, View, TemplateView from App_Blog.models import Blog, Comment, Likes from django.urls import reverse, reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. def blog_list(request): return render(request, 'App_Blog/blog_list.html', context={}) class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'App_Blog/create_blog.html' fields = '__all__' urls.py from django.urls import path from App_Blog import views app_name = 'App_Blog' urlpatterns = [ path('', views.blog_list, name='blog_list'), path('write/', views.CreateBlog.as_view(), name='create_blog'), ] I am trying to load the form in this html page: create_blog.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title_block %} Write a Blog {% endblock title_block %} {% block body_block %} <h2>Start Writing:</h2> <form method="POST" enctype="multipart/form-data"> {{ form | crispy }} {% csrf_token %} <button type="button" class="btn btn-success … -
AttributeError after POST request in Django
I am making a post request to a Django server I am running locally. I am sending the request to http://127.0.0.1/login/. Here is the view @csrf_exempt def login(request): json_data = json.loads(request.body.decode('utf-8')) print(json_data) return request.body I have @csrf_exempt for now only just so that I won't have to make a view to get the csrf token. When I send the POST request it works and prints out the json I sent with the request yet it also prints out this error. Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\Moham\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Moham\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "C:\Users\Moham\AppData\Local\Programs\Python\Python37\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'bytes' object has no attribute 'get' The reason this is confusing me is because I have made no reference to any object called "bytes" or any attribute called "get". Anyone know what is going on here? -
Can't see custom field in Django Admin page
I'm trying to create my own User class called Customer which extends the AbstractUser model and has an additional field called address. When I register, I see the user has been created in Django admin and all the fields (username,first name, last name and email) are seen in the django admin scrren but I see no value in the "address" field. How do I know if the address is being saved and how can I display it in the admin site? Below is my code for the models.py class Customer(AbstractUser): username = models.CharField(unique=True, max_length=20) deladdress = models.CharField(max_length=100) views.py def signupPage(request): signForm = CreateCustomer() if request.method=='POST': signForm = CreateCustomer(request.POST) if signForm.is_valid(): signForm.save() return render(request, 'trial_app/signup.html', {'signForm':signForm}) forms.py class CreateCustomer(UserCreationForm): address = forms.CharField(widget=forms.Textarea) class Meta: model = Customer fields = ['username','first_name','last_name','email','address','password1','password2'] def save(self, commit=True): user = super(CreateCustomer, self).save(commit=False) user.address = self.cleaned_data["address"] if commit: user.save() return user Here are some pictures that are the input to my html form and the value in the admin site -
How can i get username insted of userid?
model.py class Review(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) review = models.CharField(max_length=500) date_reviewed = models.DateTimeField(auto_now_add=True) views.py def review(request): if request.method=="POST": if request.user.is_authenticated: sender = request.user review=request.POST['review'] pid = request.POST['pid'] product=Product.objects.get(id=pid) print(user) rev = Review(user=sender,product=product,review=review) rev.save() reviews = Review.objects.filter(product=pid).values() da=list(reviews) print(da) return JsonResponse({'reviews':da}) Expected output: [{'id': 6, 'user_name': sandeep, 'product_id': 2, 'review': 'lknkk', 'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}] I am trying send this data to my frontend using jsonresponse to create a product review table but in the output i am getting user_id insted of user_name .is there any way to pass user_name? Here is actual output: [{'id': 6, 'user_id': 2, 'product_id': 2, 'review': 'lknkk', 'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}] -
Django:django.db.utils.IntegrityError: FOREIGN KEY constraint failed
What I m trying to do is when a user return cylinder then the record of that user in the issue cylinder will be deleted and if the availability of the return cylinder is yes then update the cylinder Availability will be updated as "available" else the cylinder entry will be deleted. But when I try to do so it displays the following error : Traceback (most recent call last): File "C:\python3.9\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\python3.9\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed It was working fine until unless I have set the return Availability "no". here is models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId class IssueCylinder(models.Model): cylinder=models.OneToOneField('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName class ReturnCylinder(models.Model): rechoice=[ ('fill','Fill'), ('empty','Empty') ] reav=[ ('Yes','yes'), ('No','no') ] Cylinder=models.OneToOneField('CylinderEntry',on_delete=models.CASCADE) user=models.ForeignKey('IssueCylinder',on_delete=models.CASCADE) status=models.CharField(max_length=20,choices=rechoice) returnDate=models.DateTimeField(default=timezone.now) Availability=models.CharField(max_length=5,choices=reav) def save(self,*args,**kwargs): if not self.pk: IssueCylinder.objects.filter(userName=self.user.userName).delete() if self.status=='yes'or self.status=='Yes': CylinderEntry.objects.filter(cylinderId=self.Cylinder.cylinderId).update(Availability=('available')) else: CylinderEntry.objects.filter(cylinderId=self.Cylinder.cylinderId).delete() super().save(*args,**kwargs) def __str__(self): return self.user.userName+" returned "+self.cylinder.cylinderId … -
How to write Case query in raw sql
I want to write a view using raw sql(I know that it's better to use ORM, I just need to use only SQL in my work). However, CASE does not work in a query. Does RAW support case or no? Here is my view: def profile(request): cursor = connection.cursor() cursor.execute('SELECT * from Lesson ' 'WHERE CASE WHEN(LName = %s) THEN (LName = %s) END', ['Algebra', 'English']) objects = dictfetchall(cursor) return render(request,'personal.html', {'objects':objects}) It returns the following error Invalid syntax around '=' -
Django: extra_content for class based view not displaying any data
I am trying to make a site that displays all of the items in a "case", and at the top I want to display the total value of all of the items in the "case". To get this number you would get all of the items in the case, multiply their value and quantity and add them all up. However when I pass this to my extra_content nothing is displayed.Any help would be awesome! My View: class CaseHome(ListView): model = CaseItem template_name = 'mycase/casehome.html' total = CaseItem.objects.all().aggregate(total=Sum(F('Item_Price')*F('Item_Quantity')))['total'] extra_content = {'my_total': total} My Model: class CaseItem(models.Model): Item_Title = models.CharField(max_length=200) Item_Price = models.DecimalField(default=0, max_digits=10, decimal_places=2) Item_Quantity = models.DecimalField(default=0, max_digits=10, decimal_places=2) def __str__(self): return self.Item_Title + ' | ' + str(self.Item_Quantity) + ' * $' + str(self.Item_Price) def get_absolute_url(self): return reverse('home') My Template: {% block content %} <p>{{my_total}}</p> {% for item in object_list %} <div class="container"> <div class="item" style="border: 2px solid black; margin: 3px; padding: 3px"> <a href="{% url 'item-editor' item.pk %} "><h3 style="display: inline-block">{{ item.Item_Title }}</h3><h5 style="float: right"><span class="badge bg-info text-dark">Quantity:{{ item.Item_Quantity}}</span> <span class="badge bg-info text-dark" style="margin-left: 15px;"> Price: ${{item.Item_Price}} </span> </div> </h5></a> <hr> </div> {% endfor %} {% endblock %} -
which of the framework is good for a dating website?
I want to find out which of this frame work is good for a dating website, Node.js, Laravel ,flask and Django. This adult dating does not have video feature for now but will be added in the feature. Note, I will start in a shared hosting before dedicated IP -
Django Channels: How to pass incoming messages to external script which is running outside of django?
I have started a private project with Django and Channels to build a web-based UI to control the music player daemon (mpd) on raspberry pi. I know that there are other projects like Volumio or moode audio etc. out of the box that is doing the same, but my intension is to learn something new! Up to now I have managed to setup a nginx server on the pi that communicates with my devices like mobile phone or pc. In the background nginx communicates with an uWSGI server for http requests to Django and a daphne server as asgi for ws connection to Django Channels. As well there is a redis server installed as backend because the Channels Layer needs this. So, on client request a simple html page as UI is served and a websocket connection is established so far. In parallel I have a separate script as a mpd handler which is wrapped in a while loop to keep it alive, and which does all the stuff with mpd using the python module python-mpd2. The mpd handler shall get its commands via websocket from the clients/consumers like play, stop etc. and reacts on that. At the same time, …