Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model Query Django
I'm trying to query fields from another model in Django . I'm able to fetch the user information using the following method def student(self, *args, **kwargs): std_name = Attendance.objects.get(roll=self.roll) return std_name.name Now I need to find the student's assigned teacher from a different table, I need to fetch it only using the student name which I got using student() as I don't have any variable in my current table to reference it to fetch that information from the new table. def teacher(self, *args, **kwargs): teacher_name = staff.objects.get(student=self.student) return teacher_name.name But the above method is not working properly and is not populating the fields in my admin.py page . Can someone help me in fixing this issue -
django site shows error and manage.py server not running
I have deployed a python site from one server. python command shows me result. But when I am running it from IIS it shows below error: HTTP 500: The FastCGI process exceeded configured request timeout I tried to run the python manage.py runserver 8080 but it is showing nothing in CMD. Python v 2.7 FastCGI is created and handler mapping done. Please advise. -
Django Cannot resolve keyword 'slug' into field
I want to filter API by building name. models.py from django.shortcuts import render from rest_framework.response import Response from .models import ReviewData from .models import BuildingData from rest_framework.views import APIView from .serializers import ReviewSerializer from .serializers import BuildingSerializer from django.shortcuts import render, get_object_or_404 class BuildingInfoAPI(APIView): def get(self, request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(self, request, slug): queryset = ReviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) views.py # Create your views here. from django.shortcuts import render from rest_framework.response import Response from .models import ReviewData from .models import BuildingData from rest_framework.views import APIView from .serializers import ReviewSerializer from .serializers import BuildingSerializer from django.shortcuts import render, get_object_or_404 class BuildingInfoAPI(APIView): def get(self, request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(self, request, slug): queryset = ReviewData.objects.filter(slug=slug) serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) So my API should look like this api/buildingdata/A_building A_Building-review a A_Building-review b A_Building-review c api/buildingdata/B_building B_Building-review a B_Building-review b But this error occurs. Cannot resolve keyword 'slug' into field. Choices are: building_name, id, review_content, star_num … -
I keep getting this error: (1366, "Incorrect string value: '\\xF0\\x9F\\x8E\\xA5 W...' for column 'content' at row 1")
I've created a model called Post in my Django application which makes use of the Martor markdown editor to collect the post content as markdown syntax and translate/render them on my post template. I keep getting the 1366 error, I've already browsed through several solutions here on stackoverflow but nothing seems to be working... The most common solutions I have seen is altering the content table to change the character set to utf8mb4. When I ran the code: ALTER TABLE myapp_post CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; I get the error: ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes The only way around that was to enter the query: ALTER TABLE myapp_post CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin; Which work but I still get the same error. Here are my codes for the application # models.py class Post(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=180) title_slug = models.SlugField(max_length=900) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) content = MartorField() post_image = models.ImageField(upload_to='images/post_images/') objects = models.Manager() def get_absolute_url(self): return reverse('post', kwargs={'title_slug': self.title_slug}) def __str__(self): return ' by '.join(map(str, [self.title, self.author.user.username])) # forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'content', 'post_image' … -
django return multiple repetetive objects in query set filter template file
I have implemented search bar functionality with autocomplete feature. All is good except the fact that in HTML serach results contain multiple the same object. For instance, when I put 2 in my searchbar I see 4 the same in my HTML file. What I want is to get unique objects. views.py @login_required def search_address_qa(request): query = request.GET.get('title') payload = [] if query: lookups = Q(title__icontains=query) address_objects = Article.objects.filter(lookups) address_objects_qa = QA.objects.filter(lookups) for address_object in address_objects or address_objects_qa: payload.append(address_object.title) return JsonResponse({'status':200, 'data': payload}) @login_required def search_articles(request): query = request.GET.get('q') article = Article.objects.filter(title__icontains=query) qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) | Q(tags__name__icontains=query) article = Article.objects.filter(lookups) qa_list = QA.objects.filter(lookups) context = { 'search_articles': article, 'query_name': query, 'qa_list': qa_list } return render(request, 'search/search_articles.html', context) search_view.html {% extends 'base.html' %} <title>{% block title %}search results{% endblock %}</title> {% block search %} {% include 'main/sidebar.html'%} <link rel="stylesheet" type="text/css" href="/static/search.css"> <div class="d-flex justify-content-end h-100 pb-4"> <div> {% if user.is_authenticated %} <form action="{% url 'search_articles' %}" method="get" id="search"> {% csrf_token %} <div class="searchbar " id="autocomplete"> <input name="q" type="text" placeholder="Search articles" class="search_input"> <a href="{% url 'search_articles' %}" class="search_icon"><i class="fas fa-search"></i></a> <ul class="autocomplete-result-list"></ul> </div> </form> {% endif %}</div> </div> {% endblock search %} {% block … -
should I learn django rest framework and why? [closed]
I am learning Django from code with mosh And there is an another course for learning Django rest framework Should I learn it ? why ? -
ForeignKey Not returning linked data as expected
I have 2 models Project and Fundamentals the fundamentals is linked via FK to Project I have a view that allows me to add data to the fundamentals table and also a view to update the fundamentals when data already exists. But when I try to retrieve the data i pass is the project_id in the request. But what seems to be happening is that if i have 5 projects and from project 5 i add fundamentals data the data in the table has an ID of 1 being that this is the first entry in the fundamentals table. but my project id is 5 being the 5th project If i then go to project 1 and add fundamentals it will return data from project 5. I hope this makes sense? I assume its the way i am requesting the data within these views: def fundamentals_view(request, project_id): check_exist = Fundamentals.objects.filter(project_name_id=project_id) if check_exist: return update_fundamentals_view(request, project_id) else: return add_fundamentals_view(request, project_id) @login_required def add_fundamentals_view(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = FundamentalsForm(request.POST) if form.is_valid(): fundamental = form.save(commit=False) fundamental.project_name = project fundamental.save() return redirect('dashboard.html') else: form = FundamentalsForm() return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form}) def update_fundamentals_view(request, project_id): project … -
how to use email for login in django rest?
this is my serializer for login view when I'm trying to use email for login it returns None (it can't take users' email)! but with the username, everything is ok anyone can help me to find what is the problem? class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): user_email = authenticate(**data) print(user_email) print('this is serializer print') if user_email and user_email.is_active: return user_email raise serializers.ValidationError("Incorrect Credentials") this is my login view class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) print(serializer) serializer.is_valid(raise_exception=True) user = serializer.validated_data print(user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
Transfer Ruby on rails to Python Django
In function Ruby on Rails i see this line: render :text => 'string' What does that mean in function Python Django? -
Django Many-to-many temporary
I do not want to add links, I want to make them temporary, how can I solve this problem? Direct assignment to the forward side of a many-to-many set is prohibited. Use user_permissions.set () instead. def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) if self.container_folder: # setattr(self, "user_permissions", self.container_folder.user_permissions) if permission := self.container_folder.user_permissions.all(): self.user_permissions = [x.pk for x in permission] Not work. -
static files not loading to django project
I have a project, where my partner worked on the Frontend without using any frameworks, just used js, html and css. I wanted to attach that front to the back by using Django. so here are my settting.py STATIC_ROOT = os.path.join('C:/Users/1224095/work/Backend/backend/static') STATIC_URL = '/static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) and I added the {% load static %} in my html header. To not confuse you, I made a static directory named static, and inside I got my assets and plugins from the frontend, plus in every place, I added href= {% static 'path to the file' %} As a result, I am getting an error of 404, does anyone has an idea why ? here's an example of my html: <!doctype html> <html lang="en"> {% load static %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'assets/plugins/simplebar/css/simplebar.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/metismenu/css/metisMenu.min.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/vectormap/jquery-jvectormap-2.0.2.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/highcharts/css/highcharts-white.css' %}" rel="stylesheet" /> -
Django+vue.js restart
djangosite api views.py models.py src main.js componenets assets my project looks like this. And also i'm using gunicorn. So, i use "sudo systemctl restart gunicorn" command when i want to reflect the code that i changed. But when i change the code of vue.js(component) it doesn't reflect. i can't find the reason does anyone know what the problem is? -
How to add password and username pop up for Django Swagger?
I am using drf-yasg library for the Django Swagger. I need to add the authentication on username and password level. There are three security schemes available in this library "basic", "apiKey" or "oauth2". Is there any way I can set my credentials for swagger in my django project settings and authenticate the swagger apidocs based on that? -
Fetch similar Django objects in one query if the objects have no direct relation
Let's say I have the following model: class Book(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=["name", "version"], name="%(app_label)s_%(class)s_unique_name_version", ) ] name = models.CharField(max_length=255) version = models.PositiveIntegerField() For each book, I need to get all higher versions: book_to_future_book_mappings = {} for book in Book.objects.all(): higher_versions = Book.objects.filter(name=name, version__gt=book.version).order_by("version") book_to_future_book_mappings[book] = list(higher_versions) The problem with this approach is that it doesn't scale well. It makes a separate query for every book, which is very slow if I have millions of books in my database. Is there anyway I can get all of this data in just a few queries? Perhaps I can use RawSQL if needed? Note my database is PostgreSQL. -
Parallel sequential celery tasks
I have a long list of queues which should be run sequentially but queues must run in parallel. Example: Tasks(Received by time): A1, B1, C1, D1, A2, C2, B2, A3, D2, D3, B4, A1, D4, C4 Queues: A=[A1,A2,A3,A4] , B=[B1, B2, B3, B4], C=[C1, C2, C3, C4] D=[D1, D2, D3, D4] So I managed to use apply_async(args=..., queue='queue_{}'.format((id % 4) + 1) and the routing looks fine. But there's one problem. I have about 64 threads of CPU and when I create 40 queues, tasks does not exactly run in parallel. queue 1 to 8 start to work in parallel but others wait and at a moment suddenly first 8 tasks freeze and 9 to 16 start to work. CPU load is about 40 to 50%. worker command example(40 times run using supervisord): celery -A bot worker -Q queue_19 -l ERROR --prefetch-multiplier=100 -c 1 As I mentioned before, there's no lack of resources because number of workers are about 70% of CPU threads. And the ram wouldn't fill up Celery broker backend used: Redis -
Django check block content is none or not
Can I code something like this? : // base.html {% block content %} {% if block content is None %} <p> default content </p> {% endif %} {% endblock content %} // child.html {% block content %} <p> child content </p> {% endblock content %} I know I just need to code something like this: // base.html {% block content %} {% endblock content %} // child.html {% block content %} {% if child.content %} <p> child content </p> {% else %} <p> default content </p> {% endif %} {% endblock content %} But I have so many child.html inherit from base.html.. So I just want to change the parent(base.html). Is it possible? -
Change Gunicorn Bin Path
I am using Ubuntu 20.04 and have manually installed Gunicorn with python setup.py install under the activation of virtual environment. However, when I typed which gunicorn, cmd showed /usr/bin/gunicorn. I want the system to use the gunicorn bin at /home/user/project_venv/bin/gunicorn, is there a way to change the path so that which gunicorn will point to the new path? Thanks in advance. -
I can't make query in django to filter out posts from those users that the currently logged in user is following
I am working on a Django project where a user can follow other users, create posts and so on just like Twitter or Instagram. However, I have a problem writing queries in views.py to filter out all the posts from the people that currently logged in user is following. Here, I am sharing my views.py function, model, template and corresponding ER diagram. views.py def followerspost(request): user = request.user profile = Profile.objects.filter(user = user) followings = user.profile.followings.all() for following in followings: posts = NewPost.objects.filter(user = following) return render(request,"network/following.html",{ "user" : user, "profile" : profile, "followings" : followings, "posts" : posts, }) models.py class NewPost(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) post = models.TextField() timestamp = models.DateTimeField(auto_now_add = True) def __str__(self): return f"{self.post}" class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) picture = models.ImageField(blank=True,null=True,upload_to="images/") followers = models.ManyToManyField(User, blank=True, related_name="followers") followings = models.ManyToManyField(User,blank = True, related_name="followings") I have designed my database according to the following ER diagram. urls.py urlpatterns = [ path("profile/<int:id>/following/addfollower",views.followersPeople,name="addfollower"), path("profile/<int:id>/following/removefollower",views.followersRemove,name="removefollower"), path("following",views.followerspost,name="following"),]+ static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) following.html <h1>All Posts</h1> <div id="posts" class="card"> <div class="card-body"> {% for posts in posts %} <ul> <li class="card"> <div class="card-body"> <h5 class="card-title"><a style="text-decoration: none;" href="{% url 'profile' posts.user.id %}">{{ posts.user }}</a></h5> <h6 class="card-subtitle text-muted">{{ posts.timestamp }}</h6> <h3 … -
How to write a login view for my register view in rest frame work?
I'm a beginner in Django and the rest framework and I'm trying to write a class-based login view with the rest framework for my register view please help me for writing a login class-based view what is important is view be class-based with rest this is a registered view of my project and then its serializer at the bottom of that class RegisterView(GenericAPIView): serializer_class = UserSerializer permission_classes = (permissions.AllowAny,) def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain print(current_site) # relativeLink = reverse('verify-email') # print(type(relativeLink)) absurl = 'http://' + current_site + "?token=" + str(token) email_body = 'سلام' + user.username + '\nبرای فعال سازی حساب خود وارد لینک زیر شوید' + '\n' \ + absurl data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify your email'} Util.send_email(data) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) it is a register view serializer in serializer.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=65, min_length=8, write_only=True) confirm_password = serializers.CharField( max_length=65, min_length=8, write_only=True) def validate_email(self, value): lower_email = value.lower() if User.objects.filter(email__iexact=lower_email).exists(): raise serializers.ValidationError("ایمیل تکراری است") return lower_email def validate(self, data): if not data.get('password') or not data.get('confirm_password'): raise serializers.ValidationError("لطفا پسورد را وارد و تایید کنید ") if data.get('password') … -
Django admin: Cropping using ImageRatioField on FilerImageField give errors
When I am doing using ImageField and ImageRatioField it working well for me but I have to do it with FilerImageField than it will not work for me. class FeatureArticle(models.Model): featured_listing_image = models.ImageField( null=True, blank=True, upload_to=featured_listing_image_directory_path, verbose_name=_('Feature listing image'), help_text=_('Feature listing image of article.'), ) featured_listing_image_cropping = ImageRatioField('featured_listing_image', '433x309', allow_fullsize=True, free_crop=False) featured_listing_image_latest = FilerImageField( null=True, blank=True, verbose_name=_('Featured listing image latest'), help_text=_('Featured listing latest image of Article.') ) featured_listing_image_latest_cropping = ImageRatioField('featured_listing_image_latest', '433x309', allow_fullsize=True,free_crop=False) @property def cropped_feature_listing_image(self): if self.featured_listing_image: featured_listing_image = self.featured_listing_image.url image_name = featured_listing_image.split('/')[-1].split('.')[0] featured_listing_image = featured_listing_image.replace(image_name, image_name + '_crop') return featured_listing_image return '' from django.contrib import admin from .model import FeatureArticle from image_cropping import ImageCroppingMixin class FeatureArticleInline(ImageCroppingMixin, admin.StackedInline): model = FeatureArticle max_num = 0 fieldsets = ( (_('Featured Image'), { 'fields': ( 'featured_listing_image', 'featured_listing_image_cropping', 'featured_listing_image_latest', 'featured_listing_image_latest_cropping' ), }), ) But It will give error of when I trying using FilerImageField. Error: There's no widget registered to the class FilerImageField. Please give me a solutions of cropping of image possible with this two field type? Thanks in advance. -
mac 12.0.1 django symbol not found in flat namespace '_mysql_affected_rows'
Traceback (most recent call last): File "/Users/xxx/Library/Python/3.6/lib/python/site-packages/MySQLdb/init.py", line 18, in from . import _mysql ImportError: dlopen(/Users/xxx/Library/Python/3.6/lib/python/site-packages/MySQLdb/_mysql.cpython-36m-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "/Users/xxx/Library/Python/3.6/lib/python/site-packages/MySQLdb/init.py", line 24, in version_info, _mysql.version_info, _mysql.file NameError: name '_mysql' is not defined A reinstallation attempt was made and did not take effect -
Why is my admin not showing up in Django but my site still shows and works?
I am working with Django and as I try to pull up my admin page typing in http://127.0.0.1:8000/admin, I get this DoesNotExist at /admin/login error. But the funny thing is my actual site that I am building is still showing up when I run the server. And the tags work. All was working until I added 'taggit', to the Installed Apps on settings.py and when I added tags to the models.py and made migrations and such. I have no idea why the admin is not showing. -Chris I've attached a screenshot below of what I am seeing. The Error Screen -
pymongo.errors.ServerSelectionTimeoutError while running a docker image of django app
I am trying to run a docker image of my Django app. I am running a mongo image separately from another container. Need help to solve following error: pymongo.errors.ServerSelectionTimeoutError: xxx.xxx.xxx.xxx:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 61aee0f6695286eb954e68ea, topology_type: Single, servers: [<ServerDescription ('xxx.xxx.xxx.xxx', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('xxx.xxx.xxx.xxx:27017: timed out',)>]> I have configured mongo db using djongo, DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'database-name', 'CLIENT':{ 'username': 'username', 'password': 'password', 'host': 'mongodb://xxx.xxx.xxx.xxx:27017/database-name', 'port': 27017, 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1' } } } I have also created a user in mongo db using following command; db = db.getSiblingDB('database-name') db.createUser({ user: 'username', pwd: 'password', roles: [ { role: 'root', db: 'admin', }, ], }); Using the same credentials while configuring Mongo with Django. This is my requirements.txt asgiref==3.4.1 dataclasses==0.8 Django==3.2.9 django-filter==21.1 djangorestframework==3.12.4 djongo==1.3.6 gunicorn==20.0.4 importlib-metadata==4.8.2 Markdown==3.3.6 pymongo==3.12.1 python-dateutil==2.8.2 pytz==2021.3 six==1.16.0 sqlparse==0.2.4 typing_extensions==4.0.0 zipp==3.6.0 The Mongo containers are as follows, CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f479308130bb mongo-express "tini -- /docker-ent…" 16 hours ago Up 16 hours (healthy) 0.0.0.0:9081->8081/tcp, :::9081->8081/tcp mongo-express 4e6e0e60a473 mongo "docker-entrypoint.s…" 16 hours ago Up 16 hours (unhealthy) 0.0.0.0:27017->27017/tcp, :::27017->27017/tcp mongodb If I try to access mongo db from remote server using the user that I … -
Django Summernote Settings
I've installed django-summernote and most of it works fine except for the dropdown buttons for Style, Font Size, Color and Table. The example has them setup as follows: ... 'toolbar': [ ... ['style', ['style'], ['fontsize', ['fontsize']], ['color', ['color']], ['table', ['table']], ... ], I have tried placing a list of possible values, for example, a list of colors in color: ['color', ['black', 'red']], But this clearly isn't correct as the button doesn't show at all if I try entering a list of possible values. I have noticed that if I copy in any formatted text and select it, the fontsize button does display the actual size I copied but gives me no way to change it from the toolbar and my only option for sizing text is to use CTRL+1/2/3/4/5/6 for the relevant format as H1 to 6 whereas the examples shown online clearly have working dropdowns. I am using bs5 SUMMERNOTE_THEME = 'bs5' theme and have tried various config's in settings.py but nothing seems to enable the dropdowns. I have tried copying the scripts from various discussion groups and tutorials discussing summernote to no avail and checked all my settings and they all appear to be fine. It is saving … -
How to solve gateway time-out while connecting to google calendar api?
I am trying to connect to google calendar Api using Documentation . This works on local host and I am able to retrieve events from the user's google calendar. After hosting the website using apache, I can see all the pages live but One of the pages is connecting to the google calendar api and this page says 504 Gateway Time-out. def connect_google_api(): st = time.time() creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('/var/www/FolderName/ProjectName/credentials2.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) I am thinking that there is some problem while reading credentails2.json. Can any one point me where I am making mistake?