Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vue custom delimiters not working in Firefox
I have a django project and I want to start adding Vue.js elements into it, but there is a big overarching issue before I can really start in that custom delimiters (template tags) do not work in the firefox browser only Chrome, I can change them from curly braces to square brackets, but in firefox it just renders the code not the message. The following code is not part of my django project, it is just example code to demonstrate the issue. <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <title>Learning Vue.js</title> </head> <body> <div id="app"> <input type="text" v-model="name" /> <p>Hello [[ message ]]</p> </div> <script> new Vue({ delimiters: ["[[","]]"], el: '#app', data() { return { message: 'Hello World' }; } }); </script> </body> </html> So this code renders the following in Chrome: Hello World! And in Firefox, it renders the code: [[ message ]] I'm assuming there is a fix for this, as I almost never see rendered code in websites and I'm assuming Vue is popular, how do other developers get around this issue? -
Django Rest Framework: PageNumberPagination doesn't work
I've created an APIView to list all posts of a blog: from ..pagination import BlogPagination class BlogPostAPIView(APIView): pagination_class = BlogPagination permission_classes = [IsAdminOrReadOnly] def get(self, request): objects = BlogPost.objects.filter(draft=False, publishing_date__lte=Now()) serializer = BlogPostSerializer(objects, many=True) return Response(serializer.data) def post(self, request): serializer = BlogPostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I've also created a pagination.py: from rest_framework.pagination import PageNumberPagination class BlogPagination(PageNumberPagination): page_size = 5 With this code I see all posts and not five posts for page. I'm using Django 3.1.5 and DRF 3.12.2 I've the same problem if I use the global pagination in settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5 } -
<br> tag dosen't work in <p> tag with ajax
br tag does not work when using ajax It's a Django platform, and I used json to get the data. Chrome developers mode does line changes normally, but not on the screen. Is there a way? And can I optimize my ajax code more? I'm kinda new about Ajax and frontend my ajax $(".title_txt").click(function (e) { e.preventDefault(); var txt = $(this); var tr = txt.parent(); var td = tr.children(); var mail = td.eq(0); var pk = td.eq(8).text(); $.ajax({ type: 'GET', url: "{% url 'get_consul' %}", data: {"pk": pk}, dataType: "json", success: function (response) { var title = $(".title_con"); var content = $(".con_con"); var created_by = $(".con_txt_created_by"); var created_at = $(".con_txt_created_at"); var classification = $(".con_txt_classification"); var status = $(".con_txt_status"); /* modal value changed */ title.text(response[0].fields.title) content.html(response[0].fields.content) created_by.text(response[0].fields.created_by) created_at.text(response[0].fields.created_at) classification.text(response[0].fields.classification) status.text(response[0].fields.status) status.removeClass('imp_01 imp_02 imp_03') status.addClass(response[0].fields.status_css) /* list css changed to read */ td.removeClass('on') td.addClass('read') }, error: function (response) { console.log(response) } }) }) my modal in html <div class="title"> <p class="title_tit">제목</p> <p class="title_con"></p> </div> <div class="con"> <p class="con_tit">내용</p> <p class="con_con"></p> </div> -
passing image url to view from html post method
Good evening everyone! I'm a freshly baked Django user and I have little problem. Do you know how to pass img data to my view? <form method="post"> {% csrf_token %} <label for="input-title"></label> <input name="title" type="text" id="input-title" readonly /> <label for="input-authors"></label> <input name="author" type="text" id="input-authors" /> <p id="form-price">{{ form.price }}</p> <img width="100" height="133" id="modal-image" src="" alt="" > </form> as for inputs I'm using name parameter in html but when i use name for <img> its not passed to request.POST forms.py : class BookOffer(ModelForm): class Meta: model = Product fields = ['title', 'author', 'price', 'condition'] -
How to share files between users with username or email
I have a small django app where users can upload files. I want users to be able to send files to others by name or email. How can I do that? Thanks in advance my exist project--> https://github.com/asimancalil/File_Sharing_DjangoApp -
Integer field changed but still prefix zero not displaying
I'm using an existing django project and I have a problem with displaying prefix zero of some numbers the old models was id_number = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(9999)]) I have changed it to id_number = models.CharField(max_length=5, default="") than migrate it python3 manage.py makemigrations than python3 manage.py migrate but it still removing any prefix zero how can I fix that pleas I'm using postgresql db? -
After submitting form Redirect to home page by using Django, python with vue axiox
When user filled form then after submitting form form needs to redirect to another page. I have tried but I am new to vue so, I am not able to understand how to achieve this please help me to achieve this thank you. html <div id="app"> <form> <input type="text" v-model="username"> <input type="password" v-model="password"> <input v-on:click.prevent="submitForm" type="submit" value="submit"> </form> </div> vue.js <script> const vms = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { username: null, password: null, success_msg: "", err_msg: "", }, /* submiting post Ad form */ methods: { submitForm: function(){ axios({ method : "POST", url:"{% url 'submitform' %}", //django path name headers: {'X-CSRFTOKEN': '{{ csrf_token }}',}, data : {"username":this.username, "password":this.password},//data }).then((response) => { console.log( this.posts.push(response.data); }); }, }, }); Vue.config.productionTip = false </script> This is my view code to save data into databse. views.py from django.shortcuts import render from django.http import JsonResponse from .models import vue_testing import json def submit_form(request): if request.method == "POST": data = json.loads(request.body) username = data['username'] print("username", str(username)) # password = data['password'] # print("password", str(password)) saveform = vue_testing(username=username, ) saveform.save() return redirect("/") # if username and password: # response = f"Welcome {username}" # return JsonResponse({"msg":response}, status=201) # else: # response = "username or password … -
Django UnboundLocalError local variable 'enroll' referenced before assignment
My code is of an enrolment list for a student. It shows subjects a student can enroll and ones the student already has enrolled and can tick as passed, delete or unpass the passed ones. The problem is when I want to add/enroll a new subject I get the following error. If someone can take a look and help, much appreciated. TRACEBACK Environment: Request Method: POST Request URL: http://127.0.0.1:8000/enrolment/ Django Version: 3.1.5 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'crispy_forms'] Installed 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'] Traceback (most recent call last): File "C:\Users\D\Documents\django\project\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\D\Documents\django\project\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\D\Documents\django\project\project\App\decorations.py", line 15, in wrap return function(request, *args, **kwargs) File "C:\Users\D\Documents\django\project\project\App\views.py", line 73, in enrolment_view enroll(request.POST.get('enroll'),student) Exception Type: UnboundLocalError at /enrolment/ Exception Value: local variable 'enroll' referenced before assignment MY VIEW @student_required def enrolment_view(request): if (request.user.is_authenticated): username = request.user.get_username() student = MyUser.objects.get(username=username) if(request.method == 'POST'): if request.POST.get('enroll'): enroll(request.POST.get('enroll'),student) elif request.POST.get('delete'): delete(request.POST.get('delete'),student) elif request.POST.get('passed'): passed(request.POST.get('passed'),student) elif request.POST.get('not_passed'): not_passed(request.POST.get('not_passed'),student) enroll = Enrolment.objects.filter(student_id_id=student.id).order_by('predmet_id') subjects = Subject.objects.exclude(id__in=enroll.values('predmet_id')) subj_all = Subject.objects.all() if student.status == 'REDOVNI': br_sem = 6 else: br_sem = 8 context = { … -
Field 'id' expected a number but got 'Student'
I tried to apply python manage.py migrate I get the error Field 'id' expected a number but got 'Student'. Following are my python files.ValueError: invalid literal for int() with base 10: 'Student' I've set the value of primary key to be id in views.py #----------------------STUDENT OPERATION----------------------------------------------- @login_required() def test_form(request): students = TestModel.objects.all() paginator = Paginator(students,20) page_number = request.GET.get('pages') page_obj = paginator.get_page(page_number) enter code here if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): x = form.instance.student print(x) p = form.save(commit=False) p.save() messages.success(request,'Student "{}" has been succesfully added!'.format(x)) return redirect('testform') else: form = TestForm() return render(request,'testform.html', {'form':form,'students':page_obj}) @login_required() def update_form(request,id): if request.method == 'POST': #defpost obj = TestModel.objects.get(pk = id) form = TestForm(request.POST,instance=obj) if form.is_valid(): form.save() messages.success(request,'Student "{}" was succesfully updated'.format(obj.student)) return redirect('testform') else: #def get() obj = TestModel.objects.get(pk=id) print(obj.student) print('###') form = TestForm(instance=obj) return render(request,'testform_update.html',{'form':form}) @login_required() def del_testform(request,id): if request.method == 'POST': obj = TestModel.objects.get(pk = id) student = obj.student obj.delete() messages.warning(request,'Student "{}" has been deleted succesfully!'.format(student)) return redirect('testform') def home(request): posts = Post.objects.all().order_by('-date_posted')[:8] destinations = Destinations.objects.all().order_by('date_posted')[:6] return render(request,'home.html', {'posts':posts, 'destinations':destinations}) #-------------------STUDENTOPERATION ENDS--------------------------------------------- **in models.py** class TestModel(models.Model): GENDER_CHOICES = (('Male','Male'),('Female','Female')) student = models.CharField(max_length=100,null=True) address = models.CharField(max_length=100) gender = models.CharField(choices=GENDER_CHOICES,max_length=50) email = models.EmailField(null=True) def __str__(self): return self.student **in testform.html** {% extends … -
How can I add an action to the Django User admin page?
I'm using Django 3.0. I want to add an action to the User ChangeList in the admin. The documentation for admin actions indicates that to add an action to an admin page, I need to add either the method or a reference to it to the Model's admin.ModelAdmin subclass in admin.py: # admin.py from django.contrib import admin def make_published(modeladmin, request, queryset): queryset.update(status='p') make_published.short_description = "Mark selected stories as published" class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'status'] ordering = ['title'] actions = [make_published] or # admin.py from django.contrib import admin class ArticleAdmin(admin.ModelAdmin): ... actions = ['make_published'] def make_published(self, request, queryset): queryset.update(status='p') make_published.short_description = "Mark selected stories as published" Since the User Model's admin.ModelAdmin subclass is in the auth system and not in my admin.py, though, I don't know where to put the code for this case. I tried following user Davor Lucic's answer to a much older but similar question from django.contrib.auth.models import User class UserAdmin(admin.ModelAdmin): actions = ['activate_user','deactivate_user'] def activate_user(self, request, queryset): queryset.update(status=True) def deactivate_user(self, request, queryset): queryset.update(status=False) activate_user.short_description = "Activate user(s)" deactivate_user.short_description = "Deactivate user(s)" admin.site.unregister(User) admin.site.register(User, UserAdmin) When I try this, the server halts with the error File "Project/env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 144, in unregister raise NotRegistered('The model %s is not … -
Django: Load information from file and edit before saving
I have a bib tex file with a lot of sources, which I want to import within the django admin and edit them before saving. At the moment I have an uploader, where all resources get saved, when I click save. Afterwards I can go to the resources, open each and edit them manually. Does somebody know how to load the information into the admin page from the file, so I can edit them before I save the information? Should look like this. Question would be my file uploader and each Choice (Resource) would be prefilled with information. There should not be a foreign key between the file and the resources.: Thanks in advance. -
Programatically setting a Model's Fields in Django
Say I have a model Food class Food(models.Model): description = models.TextField() toppings = models.TextField() scheme = models.ForeignKey(FoodScheme, models.CASCADE) And I want to have another class, a FoodScheme which describes which of the fields must be set in a specific Food class. class FoodScheme(models.Model): scheme_name = models.TextField() requires_description = models.BooleanField(default=False) requires_toppings = models.BooleanField(default=False) But instead of hard coding this, I want to programmatically set these fields up, so any change in Food will change the FoodScheme class too. An example implementation (that doesn't work, for several reasons, but I think gets my point across): class FoodScheme(models.Model): scheme_name = models.TextField() for f in Food.get_fields(): setattr(self, f"requires_{f.name}", models.BooleanField(default=False)) Any ideas would be greatly appreciated. -
How do i redirect one html to another html page in django, tried that works for other but it is not working for mine. Help Appricated?
I have created views.py and define a function that renders the HTML and also in URL pattern defined. likewise href="{% url 'amrit' %} but failed to get the output and getting error like mention below. Error statement: Error : <a href="{% url 'amrit' %}">Modern Layout</a> NoReverseMatch at / Reverse for 'amrit' not found. 'amrit' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'amrit' not found. 'amrit' is not a valid view function or pattern name. Exception Location: /home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/venv/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/venv/bin/python3 Python Version: 3.8.5 Python Path: ['/home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/main_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/venv/lib/python3.8/site-packages'] Server time: Mon, 25 Jan 2021 13:19:57 +0000 views.py from django.shortcuts import render from .models import * from django.shortcuts import HttpResponse # Create your views here. def homepage(request): return render(request, 'index.html') def page2(request): return render(request, 'modern-layout.html') urls.py from django.urls import path from .views import * from . import views from django.conf import settings from django.conf.urls.static import static from django.urls import include, path from django.template import loader app_name = 'main_project' urlpatterns = [ path('', views.homepage, name='home'), path('page2', views.page2, name='amrit'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
i want to understand how the below question can be achive [closed]
suppose i have one ecomerce website with 6 products in it .i want to track the number of clicks on the perticular product. and i want to store details of the same in a database after viewing in it. please share the solution for this. -
Django ManyToManyField getting Field 'id' expected a number but got b'\x89PNG\r\n
I want to upload multiple files in Django. The code below getting Error Field 'id' expected a number but got b'\x89PNG\r\n'. i want to use ManyToManyField as FileField. please i need the solution. I would be grateful for any help. models.py class FileModel(models.Model): filename = models.FileField(upload_to='files/') class FileUploadModel(models.Model): file = models.ManyToManyField(FileModel) froms.py class FileUploadingForm(forms.ModelForm): file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) def __init__(self, *args, **kwargs): super(FileUploadingForm, self).__init__(*args, **kwargs) class Meta: model = FileUploadModel fields = ['file'] views.py def uploading_view(request): if request.method == "POST": form = FileUploadingForm(request.POST, request.FILES) if form.is_valid(): # post = form.save(commit=False) for files in request.FILES.getlist("filename"): f = FileModel(filename=files) f.save() form.save() return HttpResponse('success') else: form = FileUploadingForm() return render(request, 'uploading.html', {'form': form}) -
'Tribe' object has no attribute 'tribe_id'
I have a view which should redirect the user to the new tribe that he created. but I don't know how to get the tribe_id for it to work. views.py def tribeview(request, tribe_id): tribe = get_object_or_404(Tribe,pk=tribe_id) playlist = tribe.playlist_set.all() context = { 'tribe': tribe, 'playlists':playlist } return render(request, 'app/tribe.html', context) class create_tribe(CreateView): model = Tribe form_class = TribeForm template_name = 'app/create_tribe.html' def form_valid(self, form): tribe = form.save(commit=False) tribe.chieftain = self.request.user tribe.save() return super().form_valid(form) def get_success_url(self): return reverse('app:tribe-view', args={'tribe': self.object.tribe_id}) urls.py app_name = 'app' urlpatterns = [ path('', views.index, name='index'), path('tribe/<int:tribe_id>',views.tribeview,name='tribe-view'), path('tribe/<int:tribe_id>/playlist/<int:playlist_id>',views.playlistview,name='playlist-view'), path('new_tribe', login_required(create_tribe.as_view()), name="new-tribe"), ] models.py class Tribe(TimeStamped): name = models.CharField(max_length=200,unique=True) chieftain = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) tribe_members = models.ManyToManyField(Member) def __str__(self): return self.name[:80] -
my project is based on multi-image. it is not showing images on front-end
My project is basically based on the multi-image there is problem with html file. In this project i can uplaod multiple images at single time and see them together. I am able to upload the images but they are not able to show on the frontend. help me regarding this!! my html files are thus: base.html <!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous"> <title>Multi Image Tutorial</title> </head> <body> <div class="container py-4"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> blog.html {% extends 'base.html' %} {% block content %} <div class="row row-cols-1 row-cols-md-2"> {% for post in posts %} <div class="col mb-4"> <div class="card"> <div class="view overlay"> <img class="card-img-top" src="{{post.image.url}}" alt="Card image cap" > <a href="#"> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body"> <h4 class="card-title">{{post.title}}</h4> <p class="card-text">{{post.description}}</p> <a href="{% url 'detail' post.id %}" class="btn btn-primary btn-md">Read More</a> </div> </div> </div> {% endfor %} </div> {% endblock %} detail.html {% extends 'base.html' %} {% block content %} <div id="carouselExampleIndicators" class="carousel slide" data-mdb-ride="carousel"> <ol class="carousel-indicators"> {% for p in photos %} <li data-mdb-target="#carouselExampleIndicators" data-mdb-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 %} … -
How do I filter out the friends of current user from a search_users function (Django)
I'm trying to filter out the friends of a user also the user themselves from a search users function, I've tried using the exclude() parameter but I'm not sure what I'm doing wrong, as you can see from my views.py the search_users function has a exclude on the end of object_list, but this didn't work. I also wanted to add a "add friend" button next to the users, which I think I've done correctly on 'search_users.html . I hope I've put as much info as you need to understand the issue. views.py from .models import Profile from feed.models import Post from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.conf import settings from django.http import HttpResponseRedirect from .models import Profile, FriendRequest from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm import random from django.core.mail import send_mail from django.urls import reverse User = get_user_model() def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) sent_to = [] friends = [] for user … -
Django Admin exclude model from index and app page
I want to hide some models from admin index page and app page. For example, these that I have visible in inlines as related objects. One more point, I want to keep the ability to work with change_view and add_view, but not list_view of that model. Tried to find any hints in admin/templates/admin/*.html files, but haven't found anything helpful. Is it possible without "hacks", monkey-patching and external libraries? -
Git-bash cannot detect "django-widget-tweaks" on active virtualenv
I have an issue regarding django-widget-tweaks on the active virtualenv using Windows 10. I have django project and I when I add widget_tweaks to INSTALLED_APPS on settings.py, it keeps give me an error like this when i run the project. But when I am using command prompt the project actually could be run. Any idea how to fix the below issue on git bash? Thank you for your time. $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module … -
Django reverse ORM join queries
I want all the rows of my (MovieMaster table) for which (SetMovie table) exists. These are my models class MovieMaster(models.Model): m_name = models.CharField('Movie Name',max_length=50) m_desc = models.CharField('Movie Description', max_length=50) m_image = models.ImageField('Movie Image',upload_to="pics/") def get_absolute_url(self): return reverse("admin_side:addmovie") def __str__(self): return self.m_name class SetMovie(models.Model): active = models.ForeignKey(MovieMaster, on_delete=models.CASCADE) show = models.CharField('Show Time', max_length=50) start_time = models.DateField() end_time = models.DateField() def get_absolute_url(self): return reverse("admin_side:setmovie") Basically I want to execute this sql query (SELECT * from MovieMaster INNER JOIN SetMovie ON MovieMaster.id = SetMovie.id). I am new at this. I am able to get all SetMovie row for MovieMaster by using models.SetMovie.objects.select_related('active') But I am not able to get all values of MovieMaster table for SetMovie table. -
How do I make the makemessages command detect default django translations (like form validation error messages)?
The site I'm developing is multilingual and the secondary language is not supported by default. I have added it in the settings file like so. EXTRA_LANG_INFO = { 'am': { 'bidi': False, # right-to-left 'code': 'am', 'name': 'Amharic', 'name_local': u'አማርኛ', #unicode codepoints here }, } The error_messages that I overwrite and use are correctly translated and detected by the makemessages command. error_messages = { 'password_mismatch': _('The two password fields didn’t match.'), } But the default validation exception error_messages that I did not overwrite do not appear in the .po translation file. It would be much easier to find out a way to make the command also render translations for those strings, as opposed to me overriding on every time it appears. Thanks. -
How would you model these database relationships? (User, Competence, Interest)
I'm working with a Django system and the thing is pretty simple actually, but one thing got me bothered and I thought that must be a better way to do it. Basically it's an internal tool for searching the developers the company has available to allocate them in projects based on their skills and interests. So let's say Employee John can add a Topic React to his list of competence and select his skills levels from 1 to 5 stars, meaning 1 = total beginner and 5 = expert. He can also select his level of interest from 1 to 5. So you can have a list like below The way this is designed at DB is like this: Table user with all relevant user information Table knowledge_topic with columns [id, label], where label is just the name of the language/tech Table knowledge_level with columns[id, knowledge_level, interest_level, topic_id, user_id] where topic_id makes the relationship to knowledge_topic table and user_id to user table The competence list endpoint can give a result like this for example: [ { "id": 2, "topic": { "id": 8, "label": "Docker" }, "interest_level": 4, "knowledge_level": 2, "user": 2 }, { "id": 5, "topic": { "id": 9, "label": … -
Error while using pghistory.BeforeDelete() of django-pghistory
I am using django-pghistory 1.2.0 to keep my changes using postgres triggers. For insert or update, it saves data to event table for both ORM and raw queries. But while using delete, it throws errors. My model: @pghistory.track( pghistory.AfterInsert('after_insert'), pghistory.AfterUpdate('after_update'), pghistory.BeforeDelete('before_delete') ) class TestModel(models.Model): int_field = models.IntegerField() char_field = models.CharField(max_length=16) Test API for CRUD operation: class TestModelAPI(APIView): def post(self, request, *args, **kwargs): obj = TestModel.objects.create(int_field=1, char_field='c1') obj.int_field = 2 obj.char_field = 'c2' obj.save() obj.delete() return JsonResponse( data={'message': 'success'}, status=200, ) My INSTALLED_APPS: INSTALLED_APPS = [ ............., 'pgtrigger', 'pgconnection', 'pghistory', ] My database settings: DATABASES = pgconnection.configure({ "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "<some-value>", "USER": "<some-value>", "PASSWORD": "<some-value>", "HOST": "<some-value>", "PORT": "<some-value>", }, }) My error: Traceback (most recent call last): File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/media/arif/74809FD62472EDA3/SourceCode/tkdc/venv/lib/python3.6/site-packages/pgconnection/core.py", line 85, in execute return super().execute(sql, args) psycopg2.errors.ObjectNotInPrerequisiteState: record "new" is not assigned yet DETAIL: The tuple structure of a not-yet-assigned record is indeterminate. CONTEXT: SQL statement "INSERT INTO "loan_mngmt_app_testmodelevent" ("int_field", "char_field", "id", "pgh_created_at", "pgh_label", "pgh_obj_id", "pgh_context_id") VALUES (OLD."int_field", OLD."char_field", OLD."id", NOW(), 'before_delete', NEW."id", _pgh_attach_context())" PL/pgSQL function pgtrigger_before_delete_f0f49() line 14 at SQL statement The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Add buyitnow functionality to django auction website
I'm new to django and to programming and I want to add buy it new functionality to an auction website. Like ebay, so you can both bid and buyitnow(for a specific price defined for seller) an item. Can you help me with the logic? How these two think can combined? Thank you in advance.