Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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", … -
Get top n values of multiple columns after a group_by in django
qs = models.Stats.objects.all().values('player_id').annotate(**player_stats) I have a GROUP_BY with aggregation over multiple columns, see above. In my case that produces a result set of 8523 elements. [{'player_id': 1, 'abc': 205.0, 'def': 53.0, 'ghi': 37.0, 'jkl': 151.0, 'mno': 2.0, 'pqr': 959.0, ...}, {'player_id': 2, ...}, {'player_id': 3, ...}, ...] I want to get the top n players of different categories now, my first naive approach was to order_by that result set for every key i want o get the top n players for. qs.order_by('-abc)[:5], qs.order_by('-def)[:5] That is pretty slow because it hits the database with the full initial GROUP_BY query every time which is pretty heavy itself. In the end i just need the top 5 for each category ( abc, def, ghi ...), e.g. [{'player_id': 1, 'abc': 205.0}, {'player_id': 477, 'abc': 202.0}, {}, {}, {}] My guess is i can somehow achieve that with Djangos Window functions in a way more efficient manner, but i'm a little bit lost. -
Get Logged user, while updating Model User with UpdateView in Django
new to Django here building my first project. I´m using Django authentication and when user is logged, I show in a template panel the logged user using <li> <a style="color: wheat;" href="#"><i class="fi-torso"></i>{{user.full_name}}</a> <ul class="menu vertical" style="background-color:rgb(51,51,51); border-color: wheat;"> <li><a href="{% url 'users_app:user-logout' %}">Cerrar Sesión</a></li> </ul> </li> The thing is that logged user can modify other users attributes through UpdateView. So when I select user for updating (context user now is the user that is going to be updated), and I access Modify user template, in my panel instead of seeing logged user, I see the user that is being modify. How can I diferenciate this? I understand why this is happening, but haven´t found how to solve it -
How to check spyder versions in windows command prompt?
Please provide commands for checking Spyder IDE , Python IDLE, Atom IDE,SublimeText3 versions in windows command prompt -
JS fetching current data after posting form data
I am trying to create a single page application, but I am having problem getting the latest data after redirecting from the compose-form to the list of sent emails page. I get the previously loaded emails instead. I have to click the sent button, so as to update the list. Any solutions The html code is <h2>{{ request.user.email }}</h2> <button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button> <button class="btn btn-sm btn-outline-primary" id="compose">Compose</button> <button class="btn btn-sm btn-outline-primary" id="sent">Sent</button> <button class="btn btn-sm btn-outline-primary" id="archived">Archived</button> <a class="btn btn-sm btn-outline-primary" href="{% url 'logout' %}">Log Out</a> <hr> <div id="emails-view"> </div> <div id="compose-view"> <h3>New Email</h3> <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary mt-2" value="Send" id="sendButton"/> </form> </div> The JS code // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); //My added events // To initiate post request, when posting the mail document.querySelector('#compose-form').addEventListener('submit', post_email); // By default, load the inbox load_mailbox('inbox'); }); var state; function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; … -
python - django - local variable referenced before assignment django error
I am at my wit's end, I have no idea what may cause that issue. The only change I've made was add the loginquiredmixins to my class-based views. Once I started stylising the login page I seem to have broken something, but I have no idea what exactly, which is a weird idea to have, what issue could CSS or some HTML cause, right? I tried to assign the variables before the if statement and set it to null but that seems not to work properly as it throws an error regardless. I am using the basic django authentication system. The exact error I am getting is - local variable 'course' referenced before assignment Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login Django Version: 3.0.7 Python Version: 3.7.3 Installed Applications: ['mainpage.apps.MainpageConfig', 'quiz.apps.QuizConfig', 'courses.apps.CoursesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, … -
How to get the user's username and other parameters instead of just 'id' when using django.core.serializers?
Hey guys I want to get the user's username instead of id from the below code when I use django's serializer method, also want to know the possibilities of getting their profile pictures as well. This is the code. This method is being used with django-channels for a simple chat system. def get_chat_list(self, user): try: chats = Chat.objects.by_user(user).order_by('-timestamp') chat_list = serialize('json', chats, fields=('first_user', 'second_user', 'timestamp')) payload =json.loads(chat_list) # print(payload) return payload except Exception as e: print('Exception: ', str(e)) return None How can I get the first_user's and second_user's username and profile images? Thanks in advance.