Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding categories to a django blog
I made a simple django blog and I wanted it to display posts according to the category the post is assigned to. But it doesn't work as intended when I filtere it instead of filtering the posts according to the category it shows the html code in the base.html file. My polls/urls.py file from django.urls import path from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView from .views import DeletePostView, AddCategoryView, CategoryView urlpatterns = [ path('', HomeView.as_view(), name='home'), path('article/<int:pk>/', ArticleDetailView.as_view(), name='article-view'), path('add_post/', AddPostView.as_view(), name='add_post'), path('add_category/', AddCategoryView.as_view(), name='add_category'), path('article/edit/<int:pk>/', UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove/', DeletePostView.as_view(), name='delete_post'), path('category/<str:categories>/', CategoryView, name='category') ] My views.py file from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy from django.shortcuts import render class HomeView(ListView): model = Post template_name = "home.html" # ordering = ["-post_date"] ordering = ["-id"] class ArticleDetailView(DetailView): model = Post template_name = "detail_view.html" class AddPostView(CreateView): model = Post form_class = PostForm template_name = "add_post.html" # fields = "__all__" class AddCategoryView(CreateView): model = Category fields = "__all__" template_name = "add_category.html" def CategoryView(request, categories): category_posts = Post.objects.filter(category=categories) return render(request, "categories.html", {"categories": categories}, {'category_posts': category_posts}) class UpdatePostView(UpdateView): model = Post form_class = EditForm template_name = "update_post.html" # fields = … -
Deploy Django Channels with Apache
I have a django app deployed on the internet using apache in which I would like to add one-to-one chat feature for users. I have developed the chat system using django channels but looking at the documentation isn't helping me a lot. So my question is how can I deploy it? Following is the link to the already deployed app: https://www.SearchOPal.com Thanks in advance. -
Different IP addresses in production and test environment how to handle it automaticaly
I have an app with django backend and react frontend. When testing and coding i run my django app on local server 127.0.0.1:8000 and connecting all my react requests to those endpoints. However in production my django app run on a different ip address and everytime i changed my code and push my reactjs app to production server i have to change all the endpoints ip's. What is the best way to handle it? (as a source control i use git i do not know if it makes any differences) -
Too many templates in Django
I am learning Django and I programming a CRUD for various objects. Currently I need to generate three templates per object: one for creation, one for update and one for a list. Look at how many templates I got in the picture. The process is becoming painful. What I am doing wrong and how to correct it? Thanks. -
How to show local time accorfing to the end user's local time in django?
I have to show the local time according to the endUser's timezone in Django template. I cannot get the current timezone of the end user in Django. I am using {%load tz %} but it shows error me "encountered unknown tag 'load'". What to do in this condition? how can I solve this thing? Thanks in advance. -
Got an offer as integration engineer, confused whether it is good to advance myself in data science?
I am a bit confused with job opportunities. I have been an SQL developer and have also worked on projects in python (developed a web app with flask), and occasionally with ASP.NET. My focus has been to enter the field of Machine learning and i have done courses on ML and done a few projects in kaggle and stuff. All in all i have 9 months experience with programming. My domain has been aeronautics. I got interviewed by an AI firm recently for the position of integration solutions developer with python django and flask. They deal with AI products in logistics domain. I am told that i would get a good exposure of ML as well with the team as i expressed my interests in the same field. I am a 2015 Aeronautics graduate with 3 years in production management and 9 months in SQL development (long story - production was not moving had to change jobs, hit by COVID, took up any SQL job coming my way, wanted to go for ML after leaving production.) Now i want to know whether the new job offered to me i.e. of an integration solutions developer - would that be a step … -
Why does h18 error occur when sending the wrong token to the django server hosted in heroku?
I used djangoreostframework-simplejwt to use jwt as the authentication method of my API server, and even when I hosted it to my local server and Pythonanywhere, I was able to confirm that my authentication method was working properly. But after I moved my server to heroku, when I put an expired token or an incorrect token, 503 error occurred, not a response that the token was wrong. So I took a log and got an error message like this. 2020-11-19T12:23:08.806190+00:00 heroku[router]: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/feed/post" host="our domain" request_id=f716d063-ff6a-4be7-a93c-c296909c3a9a fwd="221.168.22.204" dyno=web.1 connect=1ms service=191ms status=503 bytes=408 protocol=https I wonder if there are such bugs in heroku, django, django-rest-framework or djangoreostframework-simplejwt. If not, is there something wrong with my authentication method? Here's my code. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema', } views.py class customLoginView (GenericAPIView) : serializer_class = customLoginSerializer def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try : user = User.objects.get(email=serializer.data['email']) except User.DoesNotExist : return Response({'message': ['이메일 또는 비밀번호를 확인해주세요.']}, status=401) if user.check_password(raw_password=serializer.data['password']) == False : up = serializer.data['password'].upper() if user.check_password(raw_password=up) == False : down=serializer.data['password'].lower() if user.check_password(raw_password=down) == False : return Response({'message': ['이메일 또는 비밀번호를 확인해주세요.']}, status=401) if not user.is_verified : return Response({'message': ['이메일 … -
Django Ratelimit Not Working with UWSGI + NGINX but works with manage.py runserver
I used django-ratelimit to prevent brute-force attack to the admin login page. When I used python manage.py runserver and browsed using 127.0.0.1:8000, django-ratelimit works flawlessly. But when I started uwsgi and nginx and logined with my server IP, 192.168.31.70:8080 in my case, django-ratelimit doesn't work: there's no login limit on admin login page. I guess it's a CACHING problem, maybe I misconfigured something on uwsgi or nginx... Please help! Thanks in advance. Part of settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'import_export', 'ckeditor', 'ckeditor_uploader', 'easy_thumbnails', 'filer', #新闻管理用到了 'gbzt_coms', 'newspage', 'accounts', 'omsystem', #'config', 'administration', 'notifications', # 待办提醒功能 'statistic', 'debug_toolbar', 'rangefilter', #'django_extensions', 'ratelimit', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'ratelimit-tests', }, } # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 'LOCATION': '192.168.31.70:9090', # } # } # RATELIMIT_USE_CACHE = 'default' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'ratelimit.middleware.RatelimitMiddleware', ] uwsgi.ini: ;static-map = /static=var/www/static # clear environment on exit vacuum = true # ... with appropriate permissions - may be needed chmod-socket = 666 # stat server stats = 127.0.0.1:9191 #vhost = true #multi-site mode #no-site = true #no entry module/file when multi-site mode #workers = 2 #sub process … -
Customize only one column admin template
I have simple model like this class Result(models.Model): detail = models.TextField(blank=True) in_file = models.TextField(blank=True) out_file = models.CharField(max_length=2000,blank=True) pub_date = models.DateTimeField('date published',default=datetime.datetime.now()) Now I want to us <audio> tag in admin template For the first try class ResultAdmin(admin.ModelAdmin): list_display = ["in_file","show_out_file","detail","pub_date"] def show_out_file(self,obj): return "<audio>test</audio>" #return "<audio>" +obj.out_file +"</audio>" ## it doesn't work though. It shows <audio>test</autio> directly to the page, tag is parsed. Next, I think I should override the admin template. So I made this file templates/admin/base_site.html and edit. It works, I can customize the main page of admin. However how can I edit model(Result) admin page or only can I change only out_file column??? -
Running npm run build everytime before i can see the changes on my react App
I have a frontend using React and a Backend using Django. Everything was working perfectly after setting up. But I noticed after that if I didn't run npm run build I wouldn't see the changes implemented. Someone to help me with this please as it's very frustrating. -
Django: UpdateView, creating another previous image
If I change something but not imagefield in template and send it, django creating same image with another name. f.e previous_imagename_{random_generated_letters}.jpg... . Django takes previous imagename and creating same imagefile with adding some generated shortcode to previous image. If delete def save() in models it's working (not creating another one) but I need change image size before saving to database. views.py class Edit(UpdateView): model = User_data form_class = EditProfileFormExtra template_name = 'account/edit.html' slug_field = "slug" def get_success_url(self): return reverse('accounts:edit', kwargs={'slug': self.kwargs['slug']}) models.py class User_data(models.Model): username = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(upload_to = get_upload_path, default='default/profile_photo_default.jpg') def save(self,*args, **kwargs): if self.image: #Opening the uploaded image im = Image.open(self.image) if im.mode in ("RGBA", "P"): im = im.convert("RGB") output = BytesIO() w, h = im.size #Resize/modify the image if w > 1000 or h > 1000: d = w//1000 if w >= h else h//1000 else: d = 1 #Resizing im = im.resize((w//d, h//d)) #after modifications, save it to the output im.save(output, format='JPEG', quality=100) output.seek(0) #change the imagefield value to be the newley modifed image value self.image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(User_data,self).save(*args, **kwargs) -
Override Export maximum recursion depth exceeded
When i override my method EXPORT have an recursionError. I need Break Columns and Lines in EXPORT CSV in django-import-export. Each new object on a new line. I need resolve that problem: problem_image ''' class PlanoResource(resources.ModelResource): quantidade = fields.Field(column_name='quantidade', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='quantidade')) comp = fields.Field(column_name='comp', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='comp')) larg = fields.Field(column_name='larg', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='larg')) lam_comp1 = fields.Field(column_name='lam_comp1', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_comp1')) lam_comp2 = fields.Field(column_name='lam_comp2', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_comp2')) lam_larg1 = fields.Field(column_name='lam_larg1', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_larg1')) lam_larg2 = fields.Field(column_name='lam_larg2', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='lam_larg2')) description = fields.Field(column_name='descricao', attribute='pecas', widget=widgets.ManyToManyWidget(Pecas, field='description')) class Meta: model = Plano fields = ('quantidade', 'comp', 'larg', 'lam_comp1', 'lam_comp2', 'lam_larg1', 'lam_larg2', 'description',) def export(self, queryset=None, *args, **kwargs): dataset = self.export(queryset) output = [] for row in dataset: for col in row: output.append(col) # now you have a flattened list of all output return output ''' -
Apply current user filter to django-filter ListView
I'm learning how to use django-filter and ListView but I'm stuck on how to filter by current user. This my initial view: @login_required def view_techniques(request): """Show all techniques.""" techniques = Technique.objects.filter(owner=request.user).order_by('-date_added') context = {'techniques': techniques} return render(request, 'bjj_log/view_techniques.html', context) and this is my new view: @method_decorator(login_required, name='dispatch') class TechniqueListView(ListView): model = Technique template_name = 'bjj_log/view_techniques.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = TechniqueFilter(self.request.GET, queryset=self.get_queryset()) return context I'm trying to figure out how to apply something like: ".objects.filter(owner=request.user)" to my new version of the view. I will provide more information if needed but I'm assuming this should be enough. Any help will be greatly appreciated, thanks! -
error while add new record The current path, blog_app/android/add/, didn't match any of these. - django
error while add new record in admin panel it say : The current path, blog_app/android/add/, didn't match any of these. i use namecheap hosting how to fix this when i add new record and press save it show this error ... -
Optimization Django ORM
I'm running my own smart house project, using django backend with MySql on raspberry Pi.I've got SensorsData table in DB with thousands records with data from sensors. In my REST API I'm using view which looks like this: @api_view(['GET']) @permission_classes([IsAuthenticated]) def list_of_sensors_data(request, format=None): """ Get list of all sensors data, only for authenticated users :param request: GET :return: list of all sensors data if ok http 200 response """ sensors_data = SensorsData.objects.all() serializer = SensorsDataSerializer(sensors_data, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I've run perfomance test with locust simulating 10 users trying to use my endpoints. After some time, Django keeps returning 504 Timeout using this particular endpoint. My quest is, how can I optimize this queryset? I need to make it faster. -
Extract information from an Excel file and normalize it in a database
I have a question, I'm trying to create in Django an application that extracts info from a Google Spreadsheet file (An Excel on Google drive) and normalizes it into a database with PostgreSQL, and I want that every so often or every time there is a change in the Google Spreadsheet file the data in that database is also updated. I don't know if there is a package or library in Django to do for data extraction, and I have a hard time understanding how to make them update the database data when the Excel file is updated. -
How to render form with errors in generic detail view
I am trying to render a generic detail view page with a form with errors My post method in my generic detail view is def post(self, request, slug): if 'submit-edit-roster' in request.POST: edit_roster_form = EditRosterForm(request.POST, team=self.request.user.playerprofile.team) if edit_roster_form.is_valid(): edit_roster_form.save() return redirect ('tcl-team', slug=self.request.user.playerprofile.team.urlslug) my edit roster form is class EditRosterForm(forms.Form): members = 0 team = None sublist = [] playerlist = [] def __init__(self, *args, **kwargs): self.team = kwargs.pop('team', None) self.members = 0 self.sublist = [] self.playerlist = [] super(EditRosterForm, self).__init__(*args, **kwargs) currentroster = Roster.objects.filter(team=self.team)[0] for member in Playerprofile.objects.filter(team=self.team).order_by('name'): if member in currentroster.players.all(): self.fields[str(member.name)] = forms.ChoiceField(choices=ROSTER_CHOICES) self.initial[str(member.name)] = '1' elif member in currentroster.subs.all(): self.fields[str(member.name)] = forms.ChoiceField(choices=ROSTER_CHOICES) self.initial[str(member.name)] = '2' self.members += 1 def clean(self): cleaned_data = super().clean() i = 0 for member in Playerprofile.objects.filter(team=self.team): if cleaned_data[member.name] == '1': self.playerlist.append(member) elif cleaned_data[member.name] == '2': self.sublist.append(member) i += 1 print(len(self.sublist)) if len(self.sublist) > 2: raise ValidationError("Maximum of 2 subs allowed") if len(self.playerlist) > 5: raise ValidationError("Maximum of 5 players allowed") if len(self.playerlist) + len(self.sublist) > i: raise ValidationError("Team members must be a sub or a player") return cleaned_data def save(self): cleaned_data = self.cleaned_data print(cleaned_data) UpdateRoster(roster=self.team.GetCurrentRoster(), players=self.playerlist, subs=self.sublist) When my form has errors I get The view team.views.TeamEditView didn't return an HttpResponse object. … -
Override the automatic generated view_name in Django Rest Framework
I'm creating a Restful API with Django REST Framework. What I have is a project with two different apps. One app is called project/catalog and one is called project/environment. Both of the apps have a model called Device and their own url.py file, which will be included in the project/url.py file. The urls from the apps are included with a namespace in project/url.py: # project/url.py urlpatterns = [ path(r'api/', include(('environment.urls', 'environment'))), path(r'api/', include(('catalog.urls', 'catalog'))) ] The basename for the urls are automatic generated because in the viewSet I have a attribute queryset My question is: Is it possible to override the automatic view_name generation to use the pattern with a namespace? What it says in the documentation is that the view_name is generated like this (model_name)-detail for example. What I want is that the view_name will be generated like this (app_name):(model_name)-detail I can use the namespace when I create the HyperlinkedIdentityField by my self and add the view_name attribute, like below: # project/catalog/serializer.py class DeviceSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='catalog:device-detail') class Meta: model = models.Device fields = [ 'url', ... # project/environment/serializer.py class DeviceSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='environment:device-detail') class Meta: model = models.Device fields = [ 'url', ... But once I remove the … -
How to explicitly set default language in wagtail?
I have a website which has 2 languages. Everything works perfect but i just need to set the default language for every user. Users can change the language if they want but i want to serve the website in default language. I've made some search and found that maybe i can do it with django.views.i18n.set_language() but couldn't find how. Any help would be great. Thanks. -
Heroku: Django backend is not working, getting error GET http://localhost:8000/api/todos/ net::ERR_CONNECTION_REFUSED
I actually created a fullstack todo app with django as backend and react as frontend. The frontend is working perfectly fine, you can that here -> https://ym-todo-application.herokuapp.com. But somehow my application cannot connect to the django backend, also on inspecting on browser i saw this error -> GET http://localhost:8000/api/todos/ net::ERR_CONNECTION_REFUSED. Containing lot of files and code so i pushed them on bitbucket to make it easier to debug. here's the link https://bitbucket.org/Yash-Marmat/todo-app-fullstack/src/master/. Thanks in advance. -
Get the first 3 records from database with django
I have a problem. I want to get with a django query the first 3 records from my database and I really don't have any idea how can I do that. I didn't find nothing for this. -
Help_text under input description, Django forms
I have: street = models.CharField('Street', max_length=100, blank=True, help_text="(optional field)") Help_text displays under input, but i want help_text "(optional field)" under label "Street". Maybe I should do it another way? -
How To make fields of different model unique in django
I have a url field in 3 different models is there any pre defined way in rest framework or django so that they will be unique?? or i have to write the whole unique thing logic manually?? class A(models.Model): url = models.CharField() class B(models.Model): url = models.CharField() class C(models.Model): url = models.CharField() -
How can I prefetch nested data in Django?
I have the following models: class Contract: products = models.ManyToManyField( to="Product", through="ContractProductThroughModel", related_name="contracts" ) class Product: garage = models.ForeignKey( to="Garage", on_delete=models.CASCADE ) class Garage: ... Is there a way to prefetch all contracts for all garages? I tried it like this answer: garages = Garage.objects.all().prefetch_related("product_set").prefetch_related(Prefetch("product_set__contracts", to_attr="cached_contracts")) but I want to access the cached contracts for each garage object like this garage.cached_contracts. Is that possible? -
Getting "Module 'myproject' has no attribute 'celery'" when executing Celery in top root
Small Django & Celery question here. I'm trying to execute celery in the root level of my Django project. I have the following structure: ./myproject// dir |-- ./myproject/db.sqlite3 // dir |-- ./myproject/manage.py |-- ./myproject/myproject// dir |-- ./myproject/tasks.py `-- ./myproject/users // dir In my ./management/tasks.py file I have: app = Celery('myproject', broker=settings.CELERY_BROKER) I run from root level: python3 -m celery -A myproject worker --loglevel=INFO But get: Unable to load celery application. Module 'myproject' has no attribute 'celery'