Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django paginator issue
I am currently working on a django blog and I've coded a search bar where you type something and, if there's any post that contains what you've typed in the title, it should appear all the posts. This part is perfectly well-written. However, there's an error with the pagination. As you'll see in the views.py. The maximum num of posts per page is 3. However, you can see there's four. However, the paginator detects there should be another page for the fourth posts. Here's an image that shows that. Here's the views.py: class ElementSearchView(View): elements_list = Element.objects.all() def get(self, request, *args, **kwargs): paginator = Paginator(self.elements_list, 3) page_request_var = 'page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) queryset = Element.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) ).distinct() context = { 'query': queryset, 'queryset': paginated_queryset, 'page_request_var': page_request_var, } return render(request, 'periodic/search_results_table.html', context) And here's the html template: The pagination is at the end of the template. {% load static %} <html> {% include 'periodic/head_search.html' %} <body> {% include 'periodic/header.html' %} <br> <br> <div class="container"> <div class="row"> <!-- Latest Posts --> <main class="posts-listing col-lg-8"> <div class="container"> <div class="row"> <!-- post … -
Using Django REST framework with TCP Server socket
I am developing a web api using the Django REST Framework. At the same time, I am receiving stream data from IoT devices as an HTTP Post message. In this, I use tcp socket server in python. When I try to use these two things together, Django REST Framework does not work for HTTP requests, only the TCP socket works. How can I run Django REST Framework and TCP socket together? TCP Server Socket code here: class RFIDServer(Thread): def __init__(self, address="", port=8000): super().__init__() self.gateways = dict() self.tag_list = {} self.rfidData = dict() self.rfidDataLocker = Lock() self.address=address self.port=port self.socket_setup=False self.setup_socket() def setup_socket(self): try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except: exit("Couldn't create a socket") try: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except: exit("Couldn't set socket options") try: self.sock.bind((self.address, self.port)) except: print("Couldn't bind socket to server address") self.socket_setup=True def listen(self): if self.socket_setup!=True: print("Socket hasn't been setup. Do that first!") return self.sock.listen(1) while True: c, addr = self.sock.accept() threading.Thread(target = self.listenToClient, args = (c,addr)).start() self.sock.close() def listenToClient(self, c, addr): print('Got connection from', addr) opt = { "received_from": "client request", "body_required": True, "normalize_newlines": True } while True: data = c.recv(8196).decode("utf-8") try: parsed_data = python_http_parser.parse(data, opt) print(parsed_data['body']) except: print("Parsed Errors") print(data) c.close() -
Error when trying to use through table for many to many relationships in Django models
from django.db import models class Category(models.Model) : name = models.CharField(max_length=128) def __str__(self) : return self.name class State(models.Model) : name = models.CharField(max_length=128) iso = models.CharField(max_length=2) def __str__(self) : return self.name class Site(models.Model): name = models.CharField(max_length=128) year = models.IntegerField(null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField(max_length=3000) justification = models.CharField(max_length=3000) longitude = models.DecimalField(max_digits=15, decimal_places=10) latitude = models.DecimalField(max_digits=15, decimal_places=10) area_hectares = models.DecimalField(max_digits=15, decimal_places=5) state = models.ForeignKey(State, on_delete=models.CASCADE) def __str__(self) : return self.name class Region(models.Model): name = models.CharField(max_length=128) sites = models.ManyToManyField(Site, through='Site_Region_Junction') def __str__(self) : return self.name class Site_Region_Junction: site = models.ForeignKey(Site, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) The above code is my models.py for an app called unesco inside a django project. One site can have many regions and one region can have many sites. I have tried implementing this manytomany relationship with the through table just in case I have to add more attributes to the junction table. But I get an error when I run python manage.py check. The errors shown are : SystemCheckError: System check identified some issues: ERRORS: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x7f9ba5dee950>: (models.E022) <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x7f9ba5dee950> contains a lazy reference to unesco.site_region_junction, but app 'unesco' doesn't provide model 'site_region_junction'. unesco.Region.sites: (fields.E331) Field specifies a many-to-many relation through model 'Site_Region_Junction', which … -
1048, "Column 'last_name' cannot be null" Django AbstractUser
I'm trying to create a registration for each new account using the UserCreationForm in CreateView class-base view generics from my customize auth model using AbstractUser but everytime submit the form it gives me this error: 1048, "Column 'last_name' cannot be null" But I already fill in the last_name input here is my views for creating account: class AccountCreateView(LoginRequiredMixin, CreateView): template_name = 'components/crud/form.html' form_class = AccountForm def get_context_data(self, **kwargs): kwargs['context_title'] = 'New Account' kwargs['context_icon'] = '<em class="fa fa-plus"></em>' kwargs['context_button_title'] = 'Create Account' return super().get_context_data(**kwargs) def form_valid(self, form): print(self.request.POST.get('last_name')) try: self.object = form.save() messages.success(self.request, '<em class="fa fa-check"></em> Account created!') except IntegrityError as e: messages.error(self.request, f'<em class="fa fa-exclamation"></em> {e}') return self.form_invalid(form) return super().form_valid(form) def form_invalid(self, form): return super().form_invalid(form) def get_success_url(self): return reverse_lazy('apps:newaccount') Here is the form: class AccountForm(UserCreationForm): def clean_first_name(self): data = self.cleaned_data.get('first_name') if data == '': raise forms.ValidationError(_('What\'s your name?')) return data def clean_last_name(self): data = self.cleaned_data.get('last_name') if data == '': raise forms.ValidationError(_('What\'s your last name?')) def clean_email(self): data = self.cleaned_data.get('email') if data == '': raise forms.ValidationError(_('What\'s was the email address for this account?')) return data def clean_username(self): data = self.cleaned_data.get('username') if data == '': raise forms.ValidationError(_('Provide your username.')) return data def __init__(self, *args, **kwargs): super(AccountForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.pop('autofocus', None) self.fields['first_name'].widget.attrs.update({ 'autofocus': … -
How to improve automated (every 3 sec) calls in celery-beat, celery-worker with Redis?
I use celery-beat, worker, and Redis as a broker to schedule tasks and call a specific function in the background. The interval for the call is 3 seconds, and I may have multiple calls every 3 seconds. def theFunction(arg1, arg2): obj = Model.objects.get(id=arg1) # call to a Modbus server result = Modbus.call(ip=obj.ip, obj.port) # just an example Data.objects.create(value=result) I have set from the Django administration with celery-beat-schedule, all the tasks to call this function with a different id. I use supervisor to automate the commands separately: celery -A project worker --log-level=info celery -A project beat --log-level=info The server is 16GB of RAM, when Redis is running it consumes up to 14GB of the RAM and the server becomes slow. When I use celery purge to kill all tasks, I sometimes see more than 1 million tasks in the queue. How to improve that, to have a result every 3 seconds to display live data in a graph. In case there is another technology that I can use, let me know. -
directory issue using aws s3 bucket as media and static files storage for my django webapp
I am just trying to add my django webapp media and static files to aws s3 bucket. All the things are working fine but the directory tree changed.how do I upload static files to s3 bucket's static/ directory. like ├───media │ └───profile_pics ├───static │ ├───css │ └───img my settings.py file settings are STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_S3_PATH = 'media/' DEFAULT_S3_PATH = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' my current folder structure in s3 bucket how do I get like this project structure in aws s3 bucket -
Check if user is logged in or not django by username
in django login, we can type if request.user.is_authenticated to check if the user is logged in... but if we want to check the login status of a particular user by entering the username... eg: #Python def checkLoginStatus(username): #do some checks here.... return True or False -
Django models and managers circular import error
so In my project I have two directories: managers and models. here's my code: how I've imported objects around. I also use objects as typehints, for example: @classmethod def get_overwrite_objects(cls, parent_object: DataSheetsCluster): return parent_object.roles models/data_sheets.py from django.db import models from django import dispatch from api_backend.managers import (FieldDataManager, RolesManager) ... managers/positions.py from django.db import (models, transaction) from api_backend.models import (Role, DataSheetsCluster, DataSheet, DataSheetField, DataSheetsCategory) ... I need these models, however I cannot import them due to django's circular import error. File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\__init__.py", line 4, in <module> from .positions import (PositionalManager, RolesPositionManager, DataSheetFieldPositionManager, File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\positions.py", line 2, in <module> from api_backend.models import (Role, DataSheetsCluster, DataSheet, DataSheetField, DataSheetsCategory) ImportError: cannot import name 'Role' from partially initialized module 'api_backend.models' (most likely due to a circular import) (C:\Users\iyapp\OneDr ive\Desktop\python projects\DataSheet-ledger\api_backend\models\__init__.py) Is there a way around this? please help me! thanks a lot! -
CRITICAL WORKER TIMEOUT Error on gunicorn for Dockerized Django Application while Calling from Angular Application as Client on Nginx
Docker File Command: CMD gunicorn app.wsgi:application --bind :8000 --workers 3 --timeout 120 --keep-alive 120 --threads 3 --worker-class gthread Stil its giving me same Error while calling an API which usually takes more than 30 secs because I'm running Objects.all() Query set to retrieve data from Database. -
Rendering markdown inside of <textarea> adds newline
I am implementing a Wikipedia-like webapp with Django. Data for the different entries is stored in Markdown files on the server. I use markdown2 for the conversions. Everything works just fine but I run into a problem when I try to edit an existing entry. The server serves "edit.html" to the client, passing a django form populated with the existing data. views.py class EditPageForm(forms.Form): title = forms.CharField(widget=forms.HiddenInput, label="title") content = forms.CharField(widget=forms.Textarea, label="content" def edit(request): if request.method == "POST": form = SearchForm(request.POST) ## a form with only a "title" input if form.is_valid(): title = form.cleaned_data["title"] content = util.get_entry(title) ## read the existing file.md form = EditPageForm(initial={ "title": title, "content": content }) return render(request, "encyclopedia/edit.html", { "title": title, "form": form }) edit.html <h1>Edit content for "{{ title }}"</h1> <form action="{% url 'save' %}" method="post"> {% csrf_token %} {{ form }} ## undesired newlines added here <input type="submit" value="Save"> </form> When the browser renders the textarea which includes the data to be edited, newlines are inserted without my consent. This behaviour loops everytime I edit a text so that more and more newlines are added. I don't really understand what is going on. Does anyone have an idea? -
Use modern GET parameters with DRF Router
The goal is to accept GET parameters after the question mark, for example api/items?name=apple?starting=10_10_2020 Strange but simple router path('api/items) is not working Should I add something? Thank you -
I got Google SMTPAuthenticationError when I send email via django with NON-gmail smtp server, even though I don't use smtp.gmail.com
I'm running a website made with django. This website has a contact form, and when you submit, you and administrator will receive an email. message = render_to_string('email/contact_us_message.txt', context) send_async_mail.delay(_('subject'), message, settings.DEFAULT_FROM_EMAIL, [contact.email]) message_for_admin = render_to_string('email/contact_us_message_for_admin.txt', context) send_async_mail.delay(_('subject'), message_for_admin, settings.DEFAULT_FROM_EMAIL, [settings.ADMIN_EMAIL]) I used to subscribe to gsuite and use that smtp server. There was no problem sending and receiving emails. I decided to use another email hosting service two days ago, so I modified my dns record, canceled gsuite and deleted my account. The new email hosting service worked fine in the local environment. However, in production, email can't be sent sometimes. When I check the task results of celery results, it says 535, "b'5.7.8 Username and Password not accepted." I understand that this error message is displayed when connecting to the google service. For example, the app password is not set. But I don't use smtp.gmail.com or services related to google anymore. EMAIL_URL=smtp+tls://no-reply@mydomain.com:password@new-smtp-server.com:587 so I don't understand why I get this error message. Since I changed the dns record and it's been a little while, do I get this error related smtp.gmail.com? If I wait and the dns cache will be updated, will the error disappear? -
django common templates for apps with variables
I want to make project-wide templates, but with app variables and app base subtemplates: /home/project/ templates/document.html app1/templates/app1/base.html app2/templates/app2/base.html And app1/views.py: def page1(request): document = get_document('title',app_email='test@example.com') context = { 'document' : document, 'app_title_header' : document.header } return render(request,'document.html', context) templates/document.html {% extends app_name|add:'/base.html' %} {% load static %} {% block content %} {% autoescape off %} {{ document.body }} {% endautoescape %} {% endblock %} (app_name is set by context_processors.py registered in settings.py) def appname(request): return {'app_name': request.host.name, 'app_base' : '{}/base.html'.format(request.host.name) } app1/templates/app1/base.html (almost identical like app2) {% load static app1 %} <--- difference with app2 <!doctype html> <html lang="pl"> <head> <meta charset="utf-8"> {% block head %} {% endblock %} <title>{% app_title %} - {{ app_title_header }}</title> {% include "app1/google.html" %} </head> app1/templates/app1/google.html {% load app1 %} <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id={% g_tag %}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '{% g_tag %}'); </script> and now: render takes document.html from project/templates. First it extends app_name/base.html - so it is including google.html (Google Analytics ). And it works. But now I want to move google.html and fb.html to project templates, but theres unique G_TAG, so it has to be … -
DJango React Not found
I am new to DJango and React. I created a DJango project in Pycharm and then a React app using npm create-react-app frontend. I added to folder "src" some JavaScript file and edited a created automaticly index.css. I built React app and then launched DJango server. Console printed: Not Found: /src/index.css Not Found: /src/seigaiha.js [25/Dec/2020 14:23:31] "GET /src/index.css HTTP/1.1" 404 2201 [25/Dec/2020 14:23:31] "GET /src/seigaiha.js HTTP/1.1" 404 2207 But .css fle is visibale on launched site. .js isn't. Order in folder: - frontend/ - - build/ - - - static/ - - - - css/ #here .css file after build has the same structure as index.css, so it buil - - - - js/ - - - - media/ - - node-modules/ - - public/ - - src/ - - - index.css - - - seigaiha.js In settings.py: 'DIRS': [ os.path.join(BASE_DIR / 'frontend/build') ] In public/index.html: ***some code*** <link rel="stylesheet" type="text/css" href="./src/index.css"> ***some code*** <div class="pattern"> <canvas id="canvas">Canvas not supported.</canvas> <script src="src/seigaiha.js"></script> </div> ***some code*** What I am doing wrong? Maybe I need to place this files in another folder? Or maybe a path is wrong? .js file name? When I have just .html, .css and js files (not in … -
Crash after transition from SQLite3 to PostgresSQL in my django progect
I've use SQLite3 in my django project and after transition to PostgesSQL was crash: ** ProgrammingError at / ОШИБКА: функция lower(timestamp with time zone) не существует LINE 1: ..., "blog_post"."updated" FROM "blog_post" ORDER BY LOWER("blo... ^ HINT: Функция с данными именем и типами аргументов не найдена. Возможно, вам следует добавить явные приведения типов. ProgrammingError at / ERROR: function lower (timestamp with time zone) does not exist LINE 1: ..., "blog_post". "Updated" FROM "blog_post" ORDER BY LOWER ("blo ... ^ HINT: Function with given name and argument types was not found. Perhaps you should add explicit casts. ** #views.py from django.shortcuts import render, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.utils import timezone from django.db.models.functions import Lower, Now from .models import Post from .forms import PostForm def post_list(request): order_by = request.GET.get('order_by') direction = request.GET.get('direction') ordering = Lower(order_by) if direction == 'desc': ordering = '-{}'.format(ordering) elif order_by == None: order_by = 'publish' post = Post.objects.all().order_by(ordering) paginator = Paginator(post, 3) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts': posts, 'order_by': order_by, 'direction': direction, 'page': page } return render(request, 'blog/post/list.html', context) def post_detail(request, year, month, day, post): post = … -
How I merge different two project in django?
I designed a website in django. I want to add this chat which someone else did ..to my website. However, I could not combine the two projects. I share here my code... please help me. How can I combine both? projectname --> lubdub appname --> accounts My codes; https://hizliresim.com/LZ60vp --> views.py https://hizliresim.com/IstSCI --> account/urls.py and lubdub/ urls.py https://hizliresim.com/PhWdr3 --> models.py And, my setting.py; INSTALLED_APPS = [ 'accounts', ] STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') The project I want to add is this https://github.com/Joetib/djangoajaxchat This is different project and inside different app from me.. Different models here and different urls.. What I want to do is; when someone goes to "/chat" a joint chat will be opened. İn my models , I have a model that keeps the registered user.. And I want, same user, sent message a chat. But I can't make it. Would anyone help me please? -
Django rest Framework Endpoint
I need to get this endpoint /comments/int:post_id/ I can GET and POST comments and posts but I need to show all comments to specific post. I don´t know how to connect it. My code look like comment urls urlpatterns = [ path('', views.CommentsView.as_view()), path('<int:post_id>/', views.CreateCommentsView.as_view()), ] comment view.py # I get all comments/ class CommentsView(ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer # Comments to specific post class CreateCommentsView(ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer lookup_url_kwarg = 'post_id' def perform_create(self,serializer): post = self.kwargs.get('post_id') post =set.get_queryset().filter(id = 'post_id') post.comments.add(comment) post = Post.objects.filter(id=self.kwargs.get('post_id')) serializer.save(user=self.request.user, post=post) comment serializer from rest_framework import serializers from .models import Comment from django.contrib.auth import get_user_model User = get_user_model() class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'post', 'content', 'created'] class UserSimpleSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class CommentSimpleSerializer(serializers.ModelSerializer): user = UserSimpleSerializer() class Meta: model = Comment fields = ['user', 'content', 'created'] post.view.py class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class LikePost(generics.UpdateAPIView): permission_classes = [IsNotPostUser] queryset = Post.objects.all() serializer_class = PostSerializer -
'DatabaseOperations' object has no attribute 'geo_db_type
So I am currently new to Django and developing a GeoDjango application where I need users to be able to upload Shapefiles and Point Features into the database. I am currently using PostgreSQL as my database. Running: python manage.py makemigrations is not a problem at all. The problems comes when I try to migrate using: python manage.py migrate I get the 'DatabaseOperations' object has no attribute 'geo_db_type Error. My models.py file likes like this class Beacon(models.Model): land_id = models.OneToOneField(Land, on_delete=models.CASCADE) lon = models.FloatField() lat = models.FloatField() mpoly = models.MultiPolygonField() beacons = models.MultiPointField() and also the Database configuration part in my settings.py file looks like so, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'LIMS', 'USER': 'postgres', 'PASSWORD': '<my_password_is_here>', 'HOST': 'localhost' } } I have searched all over the internet but all solutions are not working out for me and seems like most of them are using PostGIS as the database. If anyone could help regarding this issue it would be greatly appreciated. Below I've also included the full summary of the error (LIMS) C:\Users\Surveyor Jr\Desktop\Projects\Django\LIMS\LIMS>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, farm_inventory, sessions, users Running migrations: Applying farm_inventory.0023_auto_20201225_1304...Traceback (most recent call last): File "C:\Users\Surveyor Jr\Desktop\Projects\Django\LIMS\LIMS\manage.py", … -
How can fix the generic DetailView for my product variation
I am new to Django and having hard time completing product variation for my product detail page. I am using generic view DetailView. I get the failure notification Exception has occurred: NameError name 'self' is not defined class ProductDetailView(DetailView): model = Item template_name = 'product.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['image_gallery'] = Images.objects.filter(item=self.object) context['item_variant'] = Variants.objects.filter(item=self.object) return context if self.object.variant is not None: if request.method == POST: variant_id = request.POST.get('variantid') variant = Variants.objects.get(id = variant_id) colors = Variants.objects.filter(item_id = id, size_id = variant.size_id) sizes = Variants.objects.raw('SELECT * FROM product_variants WHERE product_id = %s GROUPBY size_id', [id]) query += variant.title + ' Size:' + str(variant.size) + ' Color:' +str(variant.color) else: pass -
I can't get accurate value in dictionaries in django
Whenever i try to print the dictionaries in Django i can't get what I need The views models are given below Geeks Help to solve this begginner question Views.py def home(request): roomCate=dict(Room_Type.ROOM_CATEGORIES) roomUrl=Room_Type.objects.all() print(roomCate) print(roomUrl) return render(request,'index.html') Whenever I print roomCate and roomUrl,I got what I need in roomUrl but, In roomCate i changing while print the dictionaries of value, <QuerySet [<Room_Type: Sig>, <Room_Type: Lux>, <Room_Type: Elt>]> The value is Not changing while print the value BUT In {'Lux': 'Luxury', 'Sig': 'Signature', 'Elt': 'Elite'} the value changing Here is my models.py class Room_Type(models.Model): """Django data model Room_Type""" ROOM_CATEGORIES={ ('Elt','Elite'), ('Lux','Luxury'), ('Sig','Signature') } image = models.ImageField(upload_to="pics") roomtype = models.CharField(choices=ROOM_CATEGORIES,max_length=20) price = models.CharField(blank=True, max_length=100) def __str__(self): return f'{self.roomtype}' I want the method print result same as roomUrl but I cant get value same as roomUrl please geeks help me solve this Thank You -
Seeing posts next to each other
I am currently working on a django blog and I'd like to know if there's something that can make me see posts next to each other instead of one under another like the image: Here's the css code: <style> body { background-size: cover; background-position: center; background-image: url("{% static 'img/periodic_table.jpg' %}"); justify-content: center; align-items: center; background-repeat: no-repeat; background-attachment: fixed; } div.container { align-items: center !important; text-align: center !important; } .navbar-default { background-color: transparent !important; border-color: transparent !important; } p{ color: white; } .wrap-login100 { margin-top: 70px; background: #fff; border-radius: 10px; min-height: 20vh; justify-content: center; align-items: center; padding: 15px; background-position: center; background-size: cover; background-repeat: no-repeat;; } h3 { padding-top: 20px } </style> And here's the template: <html> {% include 'periodic/head_search.html' %} <body> {% include 'periodic/header.html' %} <br> <br> <div class="container"> <div class="row"> <!-- Latest Posts --> <main class="posts-listing col-lg-8 "> <div class="container"> <div class="row "> <!-- post --> {% for element in query %} <div class= "wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33 six wide post col-xl-6 post col-xl-6"> <div class="post-thumbnail"><a href="{{ element.get_absolute_url }}"><img src="{{ element.thumbnail.url }}" alt="..." class="img-fluid"></a></div> <div class="post-details"> </div><a href="{{ element.get_absolute_url }}"> <h3 class="h4"> {{ element.title }}</h3></a> </div> </div> {% endfor %} </div> </div> </main> </div> </div> </div> </body> {% include … -
Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84)
I am trying to get data from api using axios but i am getting this error. I am using django api. my api seems to be working fine on postman but with react it is giving me the error: getStudentById(id) { const url = `${API_URL}/api/student/student-detail/${id}`; return axios.get(url); } componentDidMount() { let urlId = this.props.match.params.id; let thisComponent = this; studentService.getStudentById(urlId) .then(function (response) { console.log(response.data.Name) thisComponent.setState({ id: response.data.id, name: response.data.Name, enrollment_no: response.data.Enrollment_No, registration_no:response.data.Registration_No, semester: response.data.Semester, year: response.data.Year, course_nam: response.data.Course_Name, course_code: response.data.Course_Code, images: response.data.images }); }).catch(error=>console.log(error)) } -
What are the most important basics to have a strong and stable django knowledge?
i want to learn Django but i feel overwhelmed by all the things i can learn. Can some of you guys help me out and give me a guideline for the most important things to know as a django beginner in order to be better for the long term? I am relatively knew to python but getting better really fast. I would like to start with Django. Thank you guys xoxo -
Query elasticsearch using django-elasticsearch-dsl without PostgreSQL connection
I've a first django project with PostgeSQL and elasticsearch 7 running and indexes updated automatically thanks to the django-elasticsearch-dsl library. Now I would like to query (GET search only) the elasticsearch indexes from another django project. I copied the models and the documents.py. It works only if I connect to this new project the original PostgreSQL db, otherwise, with another db (empty but with migration of the models done) I've a zero matching as result (not an error, but no data). -
allDRF regex search on all fields
I need DRF '$'- regex search on all("__all__") fields of a model in Django Rest API Framework. I can specify like search_fields = ['$username', '$first_name', '$email', '$last_name'] this on all fields explicitly. but I need $-regex search on all fields of a model something like search_fields = '$__all__' Please anybody giude me on this , Thanks in advance.