Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. How to send non english word in url?
The project is a dictionary of Russian terms that can be translated into any other language. Here are a few Django models to be aware of. class Term_rus(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) name = models.CharField(max_length=128) definition = models.TextField() image = models.ImageField(default='', blank=True) class Term_foreign(models.Model): term_rus = ForeignKey(Term_rus, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) name = models.CharField(max_length=128) definition = models.TextField() image = models.ImageField(default='', blank=True) The hosting I use is provided by MySQL 5.7. Here is the database setup in the settings.py file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dictionary_db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES';", 'charset': 'utf8', 'use_unicode': True, }, } } I also configured Server connection collation and Database collation to utf8_general_ci in the database settings on the server. The site should be able to search for terms in any language. Here is the URL path to redirect to when searching. urlpatterns = [ ... path(r'<str:language>/search/<str:search_string>', views.search_results, name='search_results'), ] And here is a method search_results. def search_results(request, language, search_string): if request.method == 'POST': search_string = request.POST.get('search_string') return redirect('search_results', language, search_string) else: ... terms search ... Also, if you need a search form and html code: class SearchForm(forms.Form): search_string = forms.CharField(label='', widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'Найти'})) … -
How to set the language for the whole session after login in Django
I'm stuck, trying to set the language for an entire session, so that the menus, forms, etc. are displayed according to the language entered during login. For this I have defined the following: In the settings.py file add the middleware: 'django.middleware.locale.LocaleMiddleware', MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Also add the context renderer: 'django.template.context_processors.i18n' And I defined my 3 languages: LANGUAGE_CODE = 'es' LANGUAGES = [ ('es' _('Spanish')), ('en', _ ('English')), ('it', _ ('Italian')), ] This is my view: class LoginFormView(FormView): form_class = UserLoginForm template_name = 'login.html' success_url = reverse_lazy('index') def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return HttpResponseRedirect(self.success_url) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): login(self.request, form.get_user()) user_language = self.request.POST.get('language', None) translation.activate(user_language) self.request.session['django_language'] = user_language self.request.session[translation.LANGUAGE_SESSION_KEY] = user_language return HttpResponseRedirect(self.success_url) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Iniciar sesión' return context Despite this, the language after login does not change and always remains in Spanish. All templates have the tag: {% load i18n %} I also tried to force the language change by placing a button in the navigation bar, in order to test if the translation works and is indeed working well: <button type="button" class="btn-shadow p-1 btn btn-primary btn-sm"> {% include 'change_language.html' … -
How to fix it Django, Jquery, AJAX and JSON HTTP 500
I am creating the app which books a vizit time. I am trying to show if the time is reserved in my template. I take this code from a working project. But it doesnt work in my project. When I choose any date I have this error Failed to load resource: the server responded with a status of 500 () html {% block content %} <div class="container"> <h3>{{service.name|safe}}</h3> <div align="center"> <form action="" class="form-inline" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <table class="table table-borderless"> <tr><th>{{form.date.label}}</th><td>{{form.date}}{{form.date.errors}}<br><br></td></tr> <tr><th>{{form.time.label}}</th> <td> <table class="table table-bordered"> <tr> <td align="center" valign="center" class="time">9:00</td> <td align="center" valign="center" class="time">10:00</td> <td align="center" valign="center" class="time">11:00</td> </tr> <tr> <td align="center" valign="center" class="time">12:00</td> <td align="center" valign="center" class="time">13:00</td> <td align="center" valign="center" class="time">14:00</td> </tr> <tr> <td align="center" valign="center" class="time">15:00</td> <td align="center" valign="center" class="time">16:00</td> <td align="center" valign="center" class="time">17:00</td> </tr> </table> {{form.time.errors}} </td></tr> <tr><th> {{form.name.label}}</th><td>{{form.name}}{{form.name.errors}}<br><br></td></tr> <tr><th>{{form.info.label}}</th><td>{{form.info}}{{form.info.errors}}<br><br></td></tr> </table> {{form.time}} <div style="padding-left:20%;"><button id="submit" class="btn btn-success">Запись</button></div> </div> </form> </div> </div> <script type = "text/javascript"> $("#id_date").datepicker({ dateFormat: 'yy-mm-dd', }); $(document).ready(function() { //the date is sent via Ajax to the server for comparison // a list with the reserved time for receiving is returned, for comparison with the table var checkUnavailableTime = function() { var date_data = { service_id: {{service.id}}, date_from_ajax: $("input[name=date]").val(), csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").attr('value') … -
how can store ForienKey from get method in django
I am trying to assign the product and category id to vendor, but after creating vendor successfully. When i select category and products for vendor and submit button nothing happened. It just redirect the menu after submit. Even after submit no error shown.When i debug the code and use break points it just only execute the get function and skip the post View.py class Vendor(TemplateView): template_name = 'purchase/vendor.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): try: data = self.request.POST.get vendor = VendorModel( name=data('name'), email=data('email'), Contact_No=data('Contact_No'), address=data('address') ) vendor.save() request.session['Vendor_id'] = vendor.id return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'products': products} return render(request, self.template_name, args) def post(self, request): if 'Vendor_id' in request.session: categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.GET.get('SelectProduct') try: vendor = VendorCategory( vendor_id=request.session['Vendor_id'], category_id=categoryobj, product_id=productobj, ) vendor.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% extends 'auth/home.html' %} {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value="{{ category.id }}"> {{ category.name }} </option> {% endfor … -
ajax returns information that are removed from database
I have created a live chart by chart.js and Django. when I remove chart data from the MySQL database, my chart still shows the old data! I don't know how this is possible. I use AJAX to update the chart every 3 seconds. thanks -
Python Django Beginner: can't open manage.py
Trying to get started with Django on pycharm. (venv) C:\Users\Vince\PycharmProjects\assignment>python manage.py runserver But I get this error message whenever i run manage.py: C:\Users\Vince\AppData\Local\Programs\Python\Python37-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory I do have a django directory opened with a manage.py file in it. Can anyone assist me on what to do? I have tried other solutions, like: python -vvvvv manage.py runserver python manage.py migrate -
How to upload using post in Django?
I am trying to make an API that enables to upload using multipart in Django. I have two files to upload. I can see the data in the Viewset: 'file': [<InMemoryUploadedFile: file.jpg (image/jpg)>], 'thumbnail': [<InMemoryUploadedFile: thumbnail.jpg (image/jpg)>]} However it does not pass or it fails from the serializer. I get an error since the serializer is not valid. I am getting this error: {'thumbnail': [ErrorDetail(string='The submitted file is empty.', code='empty')]} class Product(models.Model): name = models.CharField() file = models.FileField( upload_to=settings.PRODUCT_PATH, null=True, blank=True, max_length=500) thumbnail = models.FileField( upload_to=settings.PRODUCT_PATH, null=True, blank=True, max_length=500) class ProductSerializer(serializers.ModelSerializer): file = serializers.FileField() thumbnail = serializers.FileField() class Meta: model = Product fields = ('__all__') class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer parser_classes = (MultiPartParser, FormParser,) def create(self, request): data = request.data.copy() data['file'] = self.request.FILES.get('file') data['thumbnail'] = self.request.FILES.get('thumbnail') serializer = ProductSerializer(data=data) print('validity', serializer.is_valid(), serializer.errors) 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) class ProductPost(APITestCase): fixtures = ['fixtures/initial', 'fixtures/test_capture_groups'] def setUp(self): self.file = open('file.jpg', 'rb') self.thumbnail = open('thumbnail.jpg', 'rb') self.data = { 'name': 'new product', 'file': self.file, 'thumbnail': self.thumbnail, } def test_post_product(self): response = self.client.post( '/admin/login/', {'username': 'username', 'password': 'password'}) response = self.client.post('/data_management/products/', data=self.data, format='multipart') -
Nuxt js (vue js) post to django rest error
When u try post data ftom my app created in Nuxt js (vue js) post to django rest i have error [error][1] [1]: https://i.stack.imgur.com/UgxFH.png I use axios var params = { message: this.emial_name, name: this.emial_email, email: this.emial_message } const config = { headers: { 'Content-Type': 'application/json', 'Authorization': 'Token XXX', 'Access-Control-Allow-Origin': '*', } } let res = await this.$axios.$post(`/email/`, params, config) -
Mocking cleaned_data Django Form
How I mocking django cleaned data? with mock.patch('ReporteForm.is_valid') as mock_form: mock_form.return_value = True mock_form.return_value.cleaned_data = {} -
I'm having a problem with getting this webs crawler to initiate on django. There is an error in terminal when I enter "python manage.py runserver"
Error: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is the code for: settings.py INSTALLED_APPS = [ 'news.apps.NewsConfig', 'news.models.Headline.NewsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Here is the code for: apps.py from django.apps import AppConfig class NewsConfig(AppConfig): name = 'news' Here is the code for: models.py from django.db import models from django.db import models class Headline(models.Model): title = models.CharField(max_length=200) image = models.URLField(null=True, blank=True) url = models.TextField() def __str__(self): return self.title This one finally is for: views.py from django.shortcuts import render import requests from django.shortcuts import render, redirect from bs4 import BeautifulSoup as BSoup from news.models import Headline def scrape(request): session = requests.Session() session.headers = {"User-Agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"} url = "https://www.theonion.com/" content = session.get(url, verify=False).content soup = BSoup(content, "html.parser") News = soup.find_all('div', {"class":"curation-module__item"}) for artcile in News: main = artcile.find_all('a')[0] link = main['href'] image_src = str(main.find('img')['srcset']).split(" ")[-4] title = main['title'] new_headline = Headline() new_headline.title = title new_headline.url = link new_headline.image = image_src new_headline.save() return redirect("../") def news_list(request): headlines = Headline.objects.all()[::-1] context = { 'object_list': headlines, } return render(request, "news/home.html", context) -
Setup React/DRF without using CORS or CSRF tokens
I have seen a great tutorial on YouTube where react was manually setup with DRF. Throughout the tutorial csrf tokens and django-cors-headers were not used at all. I am trying to achieve the same using npx create-react-app however csrf tokens and cors become an issue doing it this way. How am I able to avoid CSRF and CORS with my drf/react app! This is the tutorial: https://www.youtube.com/watch?v=6c2NqDyxppU&t=1s -
Django Like mechanism. Database performance question
I have CustomUser model and Post model. I consider adding a lightweight like mechanism to the posts. What comes to my mind is defining a Like model in such fashion to connect the models to each other: class LikeFeedback(models.Model): likingUser = models.ForeignKey(CustomUser) note_liked = models.ManyToManyField(Post) But this design produces a new row in the database with each like. Another option is to define CustomUser and Post models in a way that: class Post(models.Model): ... users_liked = models.ManyToManyField(CustomUser) class CustomUser(models.Model): ... posts_liked = models.ManyToManyField(Post) I am not sure if this approach creates a new row or a different indexing mechanism, but it looks tidier. In terms of DB performance what approach is the fastest? Do I need to define the ManyToMany connection in both models to speed up DB processes? Because 15 posts are to be displayed on the webpage at once and and with every post it is necessary to check if the visitor already liked the note. Also, with each like and takeback a write operation is to be performed on the DB. -
Django passing variables to Jquery
I am struggling to understand this. I have a dictionary titled alldicts that I am passing from Views in Django into the HTML. How do I then reference that dictionary to Jquery to autofill in input values in my HTML? My code in Views: mydict1 = { 'one' : 1 'two' : 2 'three' : 3 } mydict2 = { 'one' : 4 'two' : 5 'three' : 6 } mydict3 = { 'one' : 7 'two' : 8 'three' : 9 } alldicts={ 'mydict1': mydict1, 'mydict2': mydict2, 'mydict3': mydict3 } return render(request, self.template_name, alldicts) In the HTML section of my code, I have a select dropdown with the options "mydict1","mydict2", and "mydict3". Below it I have three inputs (number of inputs will be dynamic, but wanted to give a simple example) that I want to auto fill to match the selected option. (IE if I select mydict2 in the dropdown, the inputs (#one, #two, and #three) will fill to be 4,5, and 6 respectively). In html, if I try something like this, it doesn't work: $("#hselect").change(function() { var a = "{{alldicts}}"; var selectedValue = $(this).val(); $.each( a, function(idx, obj) { $.each( obj, function(key, value){ if (selectedValue == idx) { … -
Injecting Python Inside Include Tag in Django
I have urls saved in a db and I want to inject the urls into an include tag. What is the work around for this? {% include {{ graphs.file.url }} %} -
No Blog matches the given query. DB is not removing deleted objects query number
DB is not automatically removing query of deleted objects and the question is how to make it work correctly so then when I do http://127.0.0.1:8000/blog/1/ it automatically shows 1st post (now it shows as if there is no post due to history of deleted objects. And if I do http://127.0.0.1:8000/blog/6/ it works fine Here is views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def allblogs(request): blogs = Blog.objects return render(request, 'blog/allblogs.html', {'blogs': blogs}) def detail(request, blog_id): try: question = get_object_or_404(Blog, pk=blog_id) except Blog.DoesNotExist: raise Http404("Question does not exist!!!") return render(request, 'blog/detail.html', {'questions': question}) -
Remove events from cell in FullCalendar. Place at the bottom of calendar in an event wrapper/container
I am using FullCalendar to embed in my website because it seems the easier option than trying to figure out how to make one from scratch. Is there a way to remove the events from the cell altogether and make it look something like this where if you click on the date the event shows at the bottom calendar with event at the bottom when clicked I am not sure on how to even begin doing this because I have very little experience with Jquery. Can Someone please help me or give me advice on what I could do instead? I've tried many different things, but none worked out. Thank You kindly. -
Django - Admin page login automatically even when trying to login in non-admin page
When I login in one of the non admin page (page which I created through LoginView Class in Django), it also automatically tries to authenticate admin login page and if the user is superuser, the admin page gets logged in even when the superuser does not want to login to the admin page and when a non super user logs in, again it tries to login in the admin page only to not get authorized. -
How to get data from dynamic models in Django
Hi Friends i have created models using django-dynamic-models library and able to create fields and data for new table. But unable to get data from dynamic table. I am using Django 2.2.6 version and python version is 3.6. If you have any solution, please help me. Please see the below code. With below test table has been created. But i want to retrieve data from this table same as from django tables. Tried with Test.objects.filter(), but not working. from dynamic_models.models import ModelSchema, FieldSchema car_schema = ModelSchema.objects.create(name='test') Car = car_schema.as_model() car_model_field = FieldSchema.objects.create(model_schema=car_schema, name='model', data_type='character') car_year_field = FieldSchema.objects.create(model_schema=car_schema, name='year', data_type='integer') # # # `as_model()` must be called again to regenerate the model class after a new field is added Car = car_schema.as_model() Car.objects.create(model='Chevrolet', year=1997) # assert Car.objects.filter(model='Chevrolet').count() == 1 -
Multiple images upload Django with dropzone
I want create django app with multiple upload images with dropzone I have 2 models: class Post(models.Model):user = models.ForeignKey(User) title = models.CharField(max_length=128)body = models.CharField(max_length=400) class Images(models.Model):post = models.ForeignKey(Post, default=None) image = models.ImageField(upload_to=get_image_filename,verbose_name='Image') My forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'body', ) class ImageForm(forms.ModelForm): class Meta: model = Images fields = ('image', ) My views.py: def post(request): ImageFormSet = modelformset_factory(Images,form=ImageForm, extra=3)#without extra if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES,queryset=Images.objects.none()) if postForm.is_valid() and formset.is_valid(): post_form = postForm.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: image = form['image'] photo = Images(post=post_form,image=image) photo.save() messages.success(request,"Posted!") return HttpResponseRedirect("/") else: print postForm.errors, formset.errors else: postForm = PostForm() formset = ImageFormSet(queryset=Images.objects.none()) return render(request, 'index.html',{'postForm': postForm, 'formset': formset},context_instance=RequestContext(request)) How create add post page with dropzone??? Please help me -
How to retrive Useres selected object and use it later on in calculations
I am trying to calculate how much of chosen food a dog should get based on some variables. A User can choose a food type from database and click Select. The moment he does, I would like to get the 'calories_per_kg' based on his choosing, to calculate the dosage. I don't know how. Please help. What I have now: urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), path('dogs', views.results, name="results"), path('add_dog', views.AddDogView.as_view(), name="add_dog"), path('dogs/<int:id>', views.DogInfoView.as_view(), name="dog_info"),] models.py class DogForm(forms.Form): name = forms.CharField(max_length=20) age = forms.IntegerField() weight= forms.IntegerField() height = forms.CharField(max_length=2, widget=forms.Select(choices=HEIGHT)) dog_variable = forms.IntegerField(widget=forms.Select(choices=DOG_VARIABLE)) class DogFoodDry(models.Model): brand = models.CharField(max_length=25) name = models.CharField(max_length=100) calories_per_kg = models.IntegerField(null=False) def __str__(self): return "Brand: " + self.brand + "Name: " + self.name + "Calories_per_kg: " + str(self.calories_per_kg) forms.py class DogFoodDryForm(forms.Form): brand = forms.CharField(max_length=25) name = forms.CharField(max_length=100) calories_per_kg = forms.IntegerField() views.py: class DogInfoView(View): def get(self, request, id): form = DogFoodDryForm() dog = Dog.objects.get(id=id) foods = DogFoodDry.objects.all() rer = 70*dog.weight**0.75 dv = dog.dog_variable multiplier = None if dv == 0: multiplier = 3 elif dv == 1: multiplier = 2.5 elif dv == 2: multiplier = 1.6 elif dv == 3: multiplier = 1.8 elif dv == 4: multiplier = 2 elif dv == 5: multiplier … -
Problem with filtering and ordering data in Django-rest-framework
I have a problem in my views.py class BooksListAPIView(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer # filter_backends = (filters.OrderingFilter,) filterset_fields = ['published_date'] filter_fields = ['published_date'] search_fields = ['published_date'] ordering_fields = ['published_date'] lookup_field = 'id' and in my settings.py: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], } The problem is i want to order results with 'published_date' field as well as filter with it but when i comment out REST_FRAMEWORK and uncomment # filter_backends = (filters.OrderingFilter,) its ordering here and when i do opposite its giving only filter here. And i want both. Thanks in advance -
I don't know how to write views for Onetoonefield where I submit the details of lawyers and that is connected to model User
Can someone show me how to write the views for Onetoonefield when I submit the details I want to know which user details are that? -
FIlter instances that has the same field as instance id of which I provide in one query?
I have simple model: class User(models.Model): group_uuid = models.UUIDField(default=uuid.uuid4) Let say i have only available user_id, and I need to retrieve all the users that has the same group_uuid as user id of which I have in user_id variable. Not sure if we can utilize F or Subquery object in some ways. So we want to achieve this in one query: user = User.objects.get(id=user_id) User.objects.filter(group_uuid=Subquery(user)) This obviously is NOT making one query, but it should be possible to make it in one right? -
How to Create Staff/Superuser without code?
How can I have a dropdown menu for me to choose whether i want to add someone as a normal user, staff or super user? Im creating a django website/form This is my code for the user registration form on my django website. from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/registration.html' success_url = reverse_lazy('login') -
Why is this PUT request behaving like a PATCH?
So I'm working in this app with Django and DRF in the backend, and I'm having a problem with a certain endpoint. When making a PUT request to /api/v1/expenses/:id, if I modify the client or provider fields, as long as there is at least one client or provider, there is no problem, they can be modified all right. The request payload would look like this: { "id": 1, "type": 2, "provider": 4, "client": 6, "attachments": "[]", "tax": 1, "cost": "200.00", "withholding": "0.00", "total_cost": "242.00", "date": "2021-2-11", "description": "Factura luz sede", "created": "2021-02-11T13:51:33.218081Z", "updated": "2021-03-19T14:45:05.322533Z", "creator": 1 } However, if I leave the provider or client fields empty, and they aren't present in the request payload, they're not emptied, the response would still return whatever provider and/or client were there before. If I understand the PUT HTTP verb correctly, it should replace the resource with what's provided, right? Here is an example request to illustrate what I mean: { "id": 1, "type": 2, "attachments": "[]", "tax": 1, "cost": "200.00", "withholding": "0.00", "total_cost": "242.00", "date": "2021-2-11", "description": "Factura luz sede", "created": "2021-02-11T13:51:33.218081Z", "updated": "2021-03-19T14:43:31.780350Z", "creator": 1 } The model, stripped down to the problematic fields: class Expense(models.Model): provider = models.ForeignKey('contacts.Contact', on_delete=models.SET_NULL, related_name="expenses", …