Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django relation "accounts_pies" does not exist, after chaning a model class name
I created a new model and ran makemigration, and then decided the edit the name by removing and 's'. class Pies(models.Model): pihostname = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.name to class Pie(models.Model): I reran makemigrations again and it noted the class name update, but I am still pulling an error from some sql query somewhere I can't find. ProgrammingError at /admin/accounts/pies/ relation "accounts_pies" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_pies" ^ Request Method: GET Request URL: http://192.168.42.13:8082/admin/accounts/pies/ Django Version: 3.0.6 Exception Type: ProgrammingError Exception Value: relation "accounts_pies" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_pies" ^ Exception Location: /home/bubba/Env/trader/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 86 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.3 Python Path: ['.', '', '/home/bubba/Env/trader/lib/python37.zip', '/home/bubba/Env/trader/lib/python3.7', '/home/bubba/Env/trader/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/bubba/Env/trader/lib/python3.7/site-packages'] Server time: Sat, 13 Jun 2020 00:42:34 +0000 Traceback Switch to copy-and-paste view /home/bubba/Env/trader/lib/python3.7/site-packages/django/db/backends/utils.py in _execute return self.cursor.execute(sql, params) … ▶ Local vars The above exception (relation "accounts_pies" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_pies" ^ ) was the direct cause of the following exception: /home/bubba/Env/trader/lib/python3.7/site-packages/django/core/handlers/exception.py in inner How do I fully update django to my new class name assignment? -
In the process of categorising my blogs but keep hitting the wall "Page not found 404"
I am a complete beginner so I apologies for my noobiness explanation. I am in the process of categorising my blogs. I created a model -> migrated it -> imported in view.py -> Imported the view that I created into urls.py -> and created URL for my new page but when I add the href to other pages (home) it takes me to the error. My codes: models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content=models.TextField() date_posted=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=100, default='Engineering') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Views.py: from .models import Post, Category class CategoryListView(ListView): model = Post template_name= 'blog/category_posts.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 3 urls.py: from django.urls import path from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, CategoryListView) path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'), home.html <a href="{% url 'category-posts' %}">{{ post.category }}</a> -
How to relate 3 models and link them for each specific page in Django
In my cartoon page, I can't display the voice actors with matching characters. And in my people page, the cartoons they voiced in isn't linked to the characters they voiced. How I want my cartoon page to look: https://myanimelist.net/anime/20/Naruto [This is what I want to achieve on my cartoon page][1] How I want my people page to look: https://myanimelist.net/people/15/Junko_Takeuchi How would I achieve this relationship with my models, views or templates? How does MyAnimeList choose which voice actor goes with the character in every entry, when they could have multiple voice actors? How are they labeling each voice actor as Japanese or English and only displaying the Japanese ones on every anime page? models.py: class Cartoons:(models.Model): name = models.CharField(max_length=100, blank=False) desc = models.TextField(default='There is currently no description available for this entry.', blank=False) img = models.ImageField(upload_to='pics/cartoons', blank=False) characters = models.ManyToManyField('Characters', blank='True') voice_actors = models.ManyToManyField('People', blank='True') class Characters(models.Model): name = models.CharField(max_length=100, blank=False) img = models.ImageField(upload_to='pics/characters', blank=False) #set default image desc = models.TextField(default='There is currently no description available for this character.', blank=False) cartoons = models.ManyToManyField(Cartoons, blank=False) voice_actor = models.ManyToManyField('People', blank=False) class People(models.Model): class Meta: verbose_name_plural = 'people' name = models.CharField(max_length=50, blank=False) img = models.ImageField(upload_to='pics/people', blank=False) character = models.ManyToManyField(Characters, blank=False) cartoons = models.ManyToManyField(Cartoons, blank=False) … -
Upload Videos into Django Model FileField with Python Script
I am trying to upload a small video file (10mb) to a Django model FileField with the python script below. I have a form setup but want to bypass this with the script going forward. When I run the script I get http response 200 but the video file does not appear in the relevant folder. What is the problem? pythonscript.py # uplaod video file to django model f = open('/path/to/video.mp4', 'rb') urls='http://127.0.0.1:8000/showvideo' r=requests.post(urls, files= {'videofile':f}) print(r.status_code) models.py from django.db import models class VideoUpload(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) forms.py from django import forms from .models import VideoUpload class VideoForm(forms.ModelForm): class Meta: model = VideoUpload fields = ["name", "videofile"] views.py from django.shortcuts import render from .models import VideoUpload from .forms import VideoForm from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def showvideo(request): lastvideo= VideoUpload.objects.last() videofile = lastvideo.videofile if lastvideo else None form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'videofile': videofile, 'form': form } return render(request, 'video.html', context) -
Auth0 Universal Login redirect not working as expected
I have two auth0 applications: App 1 and App 2 - both using different connections: Connection1 and Connection2. I have two types of users: User1 and User 2. I have set it up so that User 1 with connection 1 and user 2 with connection 2. In this case, how would I set up an app that when user 1 logs in they’re redirected to App 1 and if they’re user 2 they’re redirected to App 2. Right now I used the Django Quickstart (for App 1) to setup universal login with client ID and secret of App 1. But currently, it works only if connection 1 user logs in and if connection 2 user logs in then it says access denied. I want it to redirect to App 2 since I’m using Universal login. I have followed the Django quickstart step by step. So I don’t know if I'm missing something. Any help is appreciated! -
Submitting a contact form via Django
So, I'm trying to submit a contact form that gets sent to an admins email address, when submitted. This process works perfectly via the console and I can see the email all fine in the console, however it's getting it to go to the admin email address that's causing issues. The page will load for a few minutes, and then throw up a 405 error page after a few minutes. In the terminal - I'm getting this OSError: [Errno 101] Network is unreachable I created a dummy gmail account to test this in gmail, but I just can't figure out where I'm going wrong. Here's my code for the form, does anyone have any idea where the issue might lie? The form HTML is taken from MDB - https://mdbootstrap.com/docs/jquery/forms/contact/#ajax (without the AJAX stuff, just hte first HTML form that's there) VIEWS.PY from django.core.mail import send_mail from django.conf import settings def contact(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] message = request.POST['message'] # send an email send_mail( "New Message from" + name , #subject message, #message itself email, #from email address ['waggyboxmain@gmail.com'], #to email address ) return render(request, 'main/contact.html', {"name" : name}) SETTINGS.PY EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = … -
Change Default Homepage When Adding Wagtail to an Existing Django Project
I followed the instructions from the Wagtail site for adding Wagtail to an existing Django project. At the end of the instructions, it said: Note that there’s one small difference when not using the Wagtail project template: Wagtail creates an initial homepage of the basic type Page, which does not include any content fields beyond the title. You’ll probably want to replace this with your own HomePage class - when you do so, ensure that you set up a site record (under Settings / Sites in the Wagtail admin) to point to the new homepage. I would like to change the 'basic type Page' to my model class BlogIndex. I know I can add the BlogIndex as a subpage of the default one and then point to it as described in the instructions. Instead, I would like to change the existing page. It bugs me having an unused page at the root. It would be a cleaner approach just to use it. After adding my new class and migrating it, the django_content_type table looked like this: 1,admin,logentry 2,auth,permission 3,auth,group 4,auth,user 5,contenttypes,contenttype 6,sessions,session 7,wagtailcore,page 8,wagtailadmin,admin 9,wagtaildocs,document 10,wagtailimages,image 11,wagtailforms,formsubmission 12,wagtailredirects,redirect 13,wagtailembeds,embed 14,wagtailusers,userprofile 15,wagtailimages,rendition 16,wagtailimages,uploadedimage 17,wagtailsearch,query 18,wagtailsearch,querydailyhits 19,wagtailcore,grouppagepermission 20,wagtailcore,pagerevision 21,wagtailcore,pageviewrestriction 22,wagtailcore,site 23,wagtailcore,collection 24,wagtailcore,groupcollectionpermission … -
Is there a way to pass data from a python list into particular fields of an sqlite database using a django command?
I have data that has been scraped from a website, parsed, and cleaned into the pieces I need. The data is stored in a two dimensional list as such [[address1, name1, ip1],[address2, name2, ip2]]. The scraping and storing of the aforementioned data is done through a django command, and I would like to update my model with the same command as it validates the data. I also have a model with the following fields and attributes: class MonitoredData(models.Model): external_id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) mac_address = models.CharField(max_length=12) ipv4_address = models.CharField(max_length=200) interface_name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) address 1 needs to go in the mac_address field, name needs to go into the interface name field, and address2 needs to go into ipv4_address field. The other fields need to auto-fill according to their attributes. Any help with this would be greatly appreciated, I am using Python 3.7.5 and Django 3.0.5 -
Impacting Pseudo CSS Styles using Django Forloops in Templates
This question is due to a very particular scenario. I am trying to accomplish a parallax effect using the codepen below. https://codepen.io/CarlosVieira/pen/RyZraN header::before { bottom: 0; content: ""; left: 0; position: absolute; right: 0; top: 0; display: block; background-image: url(https://images.wallpaperscraft.com/image/fog_trees_path_120732_1600x1200.jpg); background-size: cover; /*x y z */ transform-origin: center center 0; transform: translateZ(-1px) scale(2); z-index: -1; min-height: 100vh; } As you can see there is a ::before pseudo css with a background image. I've been told I can't impact pseudo css inline. I have a user model where multiple images can be images added and I loop through these in a template using a forloop to display them. Is there anyway I can create a loop where I can change the background image url in the as I add these images on the template. Is there any alternative to this while using a ::before function. -
Django project on Heroku initial data fixture integrityerror
I have deployed my project to Heroku and currently trying to load the data dump from local sqlite database to the Heroku database. The remote database is clean and untouched other than the initial migrate command. I have tried the following combinations of dump but all of them returned an error python manage.py dumpdata --exclude contenttypes --> data.json python manage.py dumpdata --exclude auth.permission --exclude contenttypes --indent 2 > data.json python manage.py dumpdata --exclude auth.permission --exclude contenttypes --exclude auth.user --indent 2 > data.json and the error is: django.db.utils.IntegrityError: Problem installing fixture '/app/data.json': Could not load wellsurfer.Profile(pk=6): duplicate key value violates unique constraint "wellsurfer_profile_user_id_key" DETAIL: Key (user_id)=(1) already exists. i would like to post the json file here but it is about 120,000 lines. But i can provide specific portions if needed. The error clearly says the key exists but the database is clean in the beginning. Obviously, i am doing something very basic thing wrong and i hope you can point me in the right direction. I have tried recommendations that i found on Stackoverflow with no success. How to manage.py loaddata in Django -
Bootstrap 4.5.0 responsive grid failing
Following a Django tutorial I've come to bootstrap cards, with css styling. I used the latest version (bootstrap 4.5.0) and my grid is responsive (increasing the screen size, the cards move accordingly), but they are overlapping each other. Then I saw that on the tutorial, the bootstrap version being used was 4.1, and changing the href on the base.html file made it work (with the exact same code for index.html). Then I opened both versions on the browser and found that deactivating the min-width: 0 for the class="col" solved the error on the 4.5.0 version of the link. I download the 4.5 css, added to the project files, removed the min-width style and it worked beautifully. The question is: Am I using it wrong in the index.html or it's some kind of bug? (problem occurred both on Opera 68.0.3618.125 and Chrome 83.0.4103.97) The version that works as it is: https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css index.html: {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ product.image_url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">${{ product.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div> … -
Why my Django3 project created with regex code?
I am very new to Django. I am using Django 3 and when I create a new Django project, the urls.py file is showing the below code. from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] I thought this regex code is for older version of Django. The newer Django 3 should use path. Am I doing anything incorrectly? -
Django 405 template not loading
I'm using the view decorator @require_http_methods(["POST"]). When a 405 error is raised (anything but post is sent), it should redirect the user to a 405.html template under folder templates in the main directory. The default page is displayed, however, when an error occurs. All other error templates (404.html, 500.html) work. Why is this? -
by django from python
The bus has 28 seats, arranged in 7 rows and 4 columns Create an (OOP Class) in the Python language that organizes reservations for the bus, a search through which to reserve a seat or Show reserved and unreserved seats, as the program deals with a text file that expresses the status Seats, the number 0 indicates that the seat is not reserved and that the number 1 indicates that the seat is reserved, as well Explained:1001 0000 0000 0010 0000 0000 1001 The bus object creates a text file (txt.Seats,) and displays the following list: 1.Display status of all seats. 2.Reserve seats. 3.Exit. Please select your choice [1,2 or 3] : The program does not stop after choosing any of the options except option 3, in which case the program stops Work, if the entry is wrong displays the error message and the program pauses with the message pressed Press any key to complete the program. 1.Display status of all seats. 2.Reserve seats. 3.Exit. Please select your choice [1,2 or3]: Please enter a number according to the given list Press any key to continue… Option 1: View status for all seats: This option displays the status of each seat … -
if statement in Django template not working
I can't find out why this is not working. It always goes to {% else %} block. The text in machine_model is something like "Lidl - Food Market" or "Kaufland - Buy Here" or something other without those two words. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django import forms from django.urls import reverse class MyName(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class MyModel(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class MySide(models.Model): name = models.CharField(max_length=50, unique=True) class MyMachine(models.Model): date_delivery = models.DateTimeField(null=True) machine_name = models.ForeignKey(MyName, on_delete=models.PROTECT) machine_model = models.ForeignKey(MyModel, on_delete=models.PROTECT) machine_serial = models.CharField(max_length=15, default='0') use_side = models.ForeignKey(MySide, on_delete=models.PROTECT) views.py from django.views.generic import ListView from .models import MyMachine class MyMachineListView(ListView): model = MyMachine template_name = 'site/home.html' context_object_name = 'machines' ordering = ['date_delivery'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) site_title = 'Home' context["site_title"] = site_title return context home.html {% extends "site/base.html" %} {% load static %} {% block content %} {% for machine in machines %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ machine.date_delivery|date:"d.F Y" }} </small> </div> <h2><a class="article-title" href="">{{ machine.machine_name }} - {{ machine.machine_serial }}</a></h2> {% if 'Lidl' in machines.machine_model %} <p class="article-content">{{ machine.use_side }} - Lidl</p> {% … -
How to show django filter form elements seperately
I am new to django and using the material online I was able to build a filtering form using django-filter. I am able to show the filter on the html page using a format as below: {{filtergroup.form}} This does show the filter correctly and worked well on the page however I wanted to check if there is a way to show individual elements / filters in the form separately so that I can arrange the filters and format easily. Please advise. Thank you! -
How to edit user's profile page on django?
My django project has multiple functions, one of them lets the user update its profile(User model"first_name, username and email" Profile model" bio and profile picture") this used to perfectly work until I added a follow sistem, it is like the whole Profile model that lets the user edit the biography and profile picture doesnt exist anymore so when trying to edit those fields, the code returns a AttributeError: 'User' object has no attribute 'profile' error, saying this line of code on the views.py file is wrong form1 = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile), I think I am missing something on there or there is probably there is something wrong. views.py def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) user = User.objects.get(username=username) if username: post_owner = get_object_or_404(User, username=username) user_posts = Profile.objects.filter(user_id=post_owner) is_following = Following.objects.filter(user=request.user, followed=user) following_obj = Following.objects.get(user=user) follower = following_obj.follower.count() following = following_obj.followed.count() else: post_owner = request.user user_posts = Profile.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, 'follower': follower, 'following': following, 'connection': is_following, } return render(request, 'profile.html', args1) def follow(request, username): main_user = request.user to_follow = User.objects.get(username=username) following = Following.objects.filter(user = main_user, followed = to_follow) is_following = True if following else False if is_following: Following.unfollow(main_user, to_follow) is_following = False else: Following.follow(main_user, to_follow) is_following … -
Custom UserRegistrationForm not displaying fields listed in Meta
I am following a book and am trying to register a user. forms.py: from django import forms from django.contrib.auth.models import User class UserRegistrationForm(forms.Form): password = forms.CharField(label = 'Password', widget = forms.PasswordInput) password2 = forms.CharField(label = 'Repeat Password', widget = forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'email'] # clean_<fieldname> methods automatically run when you validate the from calling the is_valid() method def clean_password2(self): """Check the second password against the first one and don't let the form validate if the passwords don't match""" cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match') return cd['password2'] views.py: from django.shortcuts import render from .forms import UserRegistrationForm def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # create a new user object but avoid saving yet new_user = user_form.save(commit=False) # Set the chosen password. Instead of saving the raw password entered by the user, we use the set_password() method of the user model that handles encyrption to save for safety reasons new_user.set_password(user_form.cleaned_data['password']) #Save the user object new_user.save() return render(request, 'account/register_done.html', {'new_user':new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form':user_form}) account/register.html: <h1>Sign up</h1> <p>Please use the following form to sign up:</p> <div class = 'login-form'> <form class="" action="{% url … -
ImportError: Couldn't import Django after running " heroku python manage.py migrate" in CMD
I have a following error after running " heroku python manage.py migrate " in CMD. C:\Users\ky2001\Desktop\my_app>heroku run python manage.py migrate Running python3 manage.py migrate on ⬢ leadersbooks... up, run.6589 (Free) Traceback (most recent call last): File "manage.py", line 10, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 16, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have tried 1. removing "Pipfile" and run again 2. running "heroku python manage.py makemigrations" first 3. changing python to python3 4. re-deployment of the app 5.(my requirements.txt file, Procfile and Pipdile are in roots directly) but non of them worked. and I do have django in my requirements.txt Please help me if you have any solution.. My codes are as follows. Procfile web: gunicorn personal_portfolio.wsgi --log-file - Pipfile [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] [dev-packages] pytest = "*" django = "*" dj-database-url = "*" whitenoise = "*" gunicorn = "*" twine = "*" manage.py #!/usr/bin/env … -
Django Bootstrap Modal Form Not Rendering
I'm trying to create a simple popup with Django Bootstrap Modal. I can't get the form to render on screen. I've been following the official Documentation with no luck. I would like to be able to activate the popup from a reference link on my base.html. How do I make this modal form popup when a link is clicked from my base.html? Any help is greatly appreciated. Views: from django.shortcuts import render from django.http import HttpResponse from django.urls import reverse_lazy from bootstrap_modal_forms.generic import BSModalCreateView from .forms import CustomUserCreationForm class SignUpView(BSModalCreateView): form_class = CustomUserCreationForm template_name = 'blog/signup.html' success_message = 'Success: Sign up succeeded. You can now Log in.' success_url = reverse_lazy('index') posts = [ { 'author': 'ShanePa', 'title': 'Blog Post', 'content': 'First post conent', 'date_posted': 'August 27, 2018' }, { 'author': 'ColePa', 'title': 'Blog Post 2', 'content': 'Second post conent', 'date_posted': 'August 28, 2018' } ] artists = [ { 'artist': 'Cole', 'pic1': 'Blog Post', 'pic2': 'First post conent', 'pic3': 'August 27, 2018', 'pic4': 'August 27, 2018' }, { 'artist': 'Mikey', 'pic1': 'Blog Post', 'pic2': 'First post conent', 'pic3': 'August 27, 2018', 'pic4': 'August 27, 2018' }, { 'artist': 'Josh', 'pic1': 'Blog Post', 'pic2': 'First post conent', 'pic3': 'August 27, 2018', … -
Is it possible to conditionally Count in Django?
For the following schema I would like to GROUP BY user_id and COUNT(isPinned=True). Table STORY ------------------- user_id isPinned 0 True 0 True 0 False 1 True 1 False I would like the following ouput: [{'user_id': 0, 'isPinnedCount': 2}, {'user_id': 1, 'isPinnedCount': 1}] I have tried the following queries: Story.objects.values('user_id').annotate(isPinnedCount=Count('isPinned'=True)) Story.objects.values('user_id').annotate(isPinnedCount=Count('isPinned'), filter=Q(isPinned=True)) Both failed give errors : "invalid syntax" and "AttributeError: 'WhereNode' object has no attribute 'select_format'" respectively. Is grouping by id and then counting conditionally possible in Django? -
Problem in Django with Bootstrap datetimepicker widget: Date sometimes resets itself to current date on page load
I have an odd problem with the Bootstrap datetimepicker widget in my Django application. In a form in which the user can enter a date range by means of two linked datetimepicker widgets, the start date sometimes (only sometimes!) resets itself to the current date, even if I pass a different date as initialization value. This reset happens around 50% of the time when the page is loaded, and always a few fractions of a second after the page is initially rendered. I'm trying to follow the recommended placement of CSS (top) and JS (bottom) of the page. But it very much looks like that when the JS for that widget is finally loaded and runs, it occasionally decides to do the wrong thing and resets the date in the widget. This reset only happens in the start date, never in the end date. Here's the page HTML (sorry for those weird, long lines with the quoted JSON, that's how options are passed to the datepicker widget): <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <link rel="stylesheet" href="/static/ext/css/bootstrap.min.css"> <link rel="stylesheet" href="/static/ext/css/bootstrap-datetimepicker.css"> <link rel="stylesheet" href="/static/bootstrap_datepicker_plus/css/datepicker-widget.css"> ... </head> <body> ... <form method="post"> ... <div class="form-group"> <div class="input-group date"> … -
Django project requirements.txt installation ERROR
SPECS macOS 10.12.6 Python virtual environment GitHub project COMMAND pip install -r requirements.txt ERROR Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/rk/cd2m2z5s3cdfx12h9ltqk3500000gn/T/pip-install-e01ltqev/psycopg2/ TRIED SOLUTIONS https://www.codingforentrepreneurs.com/comments/13241 "python setup.py egg_info" failed with error code 1 MACOS Command python setup.py egg_info failed with error code 1 https://github.com/palantir/python-language-server/issues/370 -
DRF, filter_queryset with boolean field
I have the following view: class MessagesViewSet(ModelViewSet): """ A simple ViewSet for viewing and editing the messages associated with the user. """ authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated] serializer_class = MessageSerializer filter_backends = [DjangoFilterBackend] filterset_fields = [MessageFields.MARK_READ] def get_user(self): user = self.request.user return user def get_queryset(self): return Message.objects.filter(sent_to=self.get_user()) def perform_create(self, serializer): serializer.save(sender=self.get_user()) @action(detail=True, ) def unread_messages(self, request, pk): """ Return all of the user's unread messages. """ data = self.filter_queryset(self.get_queryset()) serialized_data = MessageSerializer(data, many=True) return Response(serialized_data.data, status=HTTP_200_OK) in unread_messages I want to return only the object that has mark_read = True (It's a boolean field). right now it returns all objects because there's no restriction in the method about being True or False. So how can I set some sort of a flag in the method? -
Deploy two django app with nginx but the second app is directed on the first
I am using nginx server to realise 2 servers block. My apps is made with django and gunicorn. What happen is that the first project working well but the second link or is directed to the second like if the second server block redirect in the first. I have the same name for my django project but in 2 differents virtualenv my first conf for the first project upstream prod_app_server { server unix:/webapps/projet1/run/gunicorn.sock fail_timeout=0; } server { server_name app.exemple.com; client_max_body_size 4G; location /static/ { root /webapps/projet1/django_project; } location /media/ { root /webapps/projet1/django_project; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; if (!-f $request_filename) { proxy_pass http://prod_app_server; break; } } } my second conf for the second project upstream prod2_app_server { server unix:/webapps/projet2/run/gunicorn.sock fail_timeout=0; } server { server_name app2.exemple.com; client_max_body_size 4G; location /static/ { root /webapps/projet2/django_project; } location /media/ { root /webapps/projet2/django_project; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; if (!-f $request_filename) { proxy_pass http://prod2_app_server; break; } } } my gunicorn conf for the project 1 NAME="projet1" DJANGODIR=/webapps/projet1/django_project SOCKFILE=/webapps/projet1/run/gunicorn.sock USER=axit GROUP=webapps NUM_WORKERS=15 DJANGO_SETTINGS_MODULE=django_project.settings DJANGO_WSGI_MODULE=django_project.wsgi my gunicorn conf for the project 2 NAME="projet2" DJANGODIR=/webapps/projet2/django_project SOCKFILE=/webapps/projet2/run/gunicorn.sock USER=axit GROUP=webapps NUM_WORKERS=15 DJANGO_SETTINGS_MODULE=django_project.settings DJANGO_WSGI_MODULE=django_project.wsgi