Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)])
I am building a simple gallery image app and using django-rest-framework. I am saving two model instances, which I am rendering as nested response and also saving throughh nested json. But when I click on Post from api admin then it is showing 'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]) I think the problem is in the create() function. I have also tried modifying it but it is still not working and showing the same error. models.py class Gallery(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) class Image(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name="images") text = models.CharField(max_length=300) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class GallerySerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Gallery fields = "__all__" def create(self, validated_data): created = Gallery.objects.create(poll=1) created.images.set(validated_data['images']) return created my response which I am saving { title: "First Gallery", images : [ { "gallery": 1, "text": "First Image" } ] } And When i print validated_data like :-: print(validated_data['images']) then it is showing [OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Second Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Third Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Fourth Image'), ('gallery', <Gallery: First Gallery>)])] I have just started learning … -
How can i edit uploaded mp3 files by user
I want my django app to do. User Uploads mp3 file user inputs time range my app trims the mp3 file to the range given avail result mp3 to user -
Django: How to automatically update a model instance everytime another model instance is updated
In online shop projects, I have a model called Order (and this model stores order instances) and a model called Points. The model Points stores bonus points which are collected by the users when they make orders. But the order may be cancelled, so I would like to be able to monitor when an order is being cancelled (model Order instance's status being changed to "cancelled") in order to take the points away. How can I do that? -
Django Imagefield renaming works only every other time
I'm attempting to upload a profile picture to a django model which should always be named pic.jpg. Old pictures are deleted using django_cleanup. This works every other time. I upload an image and it's saved as pic.jpg, then upload a different one and it's saved as pic_{randomchars}.jpg (i.e pic_wCU5xwv.jpg). def rename_pic(instance, filename): return os.path.join("api/media/me/", filename) pic = models.ImageField(upload_to=rename_pic) def save(self, *args, **kwargs): try: # Opening the uploaded image img = Image.open(self.pic) output = BytesIO() img = img.convert('RGB') # after modifications, save it to the output img.save(output, format='JPEG') output.seek(0) # Set field to modified picture self.pic = InMemoryUploadedFile(output, 'ImageField', "pic.jpg", 'image/jpeg', sys.getsizeof(output), None) except Exception as e: print(e) print(self.pic.name) # Always prints pic.jpg super(MyData, self).save() # Error happens in this line print(self.pic.name) # Prints api/media/me/pic.jpg and api/media/me/pic_{randomchars}.jpg alternating The error happens somewhere in the super(MyData, self).save() line, as the file has the correct name before it's called. -
deleting a post in django
hi ive read some of similar posts but couldn't find same problem. i wrote a code to delete post and when i press delete it shows 404 error but when back to home post is still there views: def delete_music_view(request,music_id): #view for deleting music my_object = add_music.objects.get(id=music_id) if request.method == 'POST': my_object.delete() return redirect('pages:home') context = {'my_object':my_object} return render(request,'pages/delete_music.html',context) url: app_name = 'pages' urlpatterns = [ path('',views.home,name='home'), path('add_music/',views.add_music_view,name='add_music'), path('musics/<int:music_id>',views.musics_view,name='music_page'), path('musics/<int:music_id>/delete',views.delete_music_view,name='delete_music'), ] template: {% extends 'pages/base.html' %} {% block content %} <form action="." method='POST'> {% csrf_token %} <p><input type="submit" name="delete" value="yes"><a href="../../">cancel</a></p> </form> {% endblock %} can u pls tell me whats wrong? -
Django: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead
I see this is a common problem and understand the idea is that you cannot add many to many unless it is created first. I have seen multiple solutions for this but unsure which one to use. Models.py class Concert(models.Model): venue = models.CharField(max_length=200, null=True) concertid = models.CharField(max_length = 200, null=False, default='didnotsaveproperly') date = models.DateField(null=True) city = models.CharField(max_length=100, null=True) country = models.CharField(max_length=200, null=True) user = models.ManyToManyField(USER_MODEL, related_name="concerts", null=True) song = models.ManyToManyField("Song", blank=True, null=True) def __str__(self): return str(self.concertid) + " " + str(self.venue) + " " + str(self.date) Views.py def log_concert_and_song(request, concertdict): if request.method == "POST": Concert_save = Concert( concertid=concertdict['id'], date=concertdict['eventDate'], venue=concertdict['venue'], city=concertdict['city'], country=concertdict['country'], user = request.user ) Concert_save.save() Should I use the User model? -
modify the model to take the information from the another model
I have two models the first form is for users and the second is for candidates when I register an account that is done using the first form and when I enter to edit the account information as the name and date of birth I need to rewrite this information back knowing that I put it during the account registration, is there a way to modify the second model form to take the information from the first model the first models : from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField GENDER_CHOICES = ( ('M', "Male"), ('F', "Female"), ('O', "Other"), ) class User(AbstractUser): username=None email=models.EmailField( verbose_name='email address', max_length=255, unique=True ) date_of_birth = models.DateField(default='1990-01-01') gender=models.CharField(max_length=1,choices=GENDER_CHOICES,blank=True) picture=models.ImageField( upload_to='img/users',null=True,verbose_name="" ) phone = PhoneNumberField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email the secound models : from django.db import models from accounts.models import User from django.utils import timezone from autoslug import AutoSlugField from django_countries.fields import CountryField from recruiters.models import Job from django.utils import timezone CHOICES = ( ('Full Time', 'Full Time'), ('Part Time', 'Part Time'), ('Internship', 'Internship'), ('Remote', 'Remote'), ) class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name='profile') full_name = models.CharField(max_length=200, null=True, blank=True) country = CountryField(null=True, blank=True) … -
Django: key error after setting the key with AJAX from JAVASCRIPT
I am using django to manage my site. I have a JAVASCRIPT event that update's the server with this an AJAX call: **script_x.js** $.ajax({ type: "POST", url: "my_url_to_server", headers: {'X-CSRFToken': csrftoken}, data: {}, success: function(response){alert(response);} }); On the server in the views, I set the "SESSION variable" once the JQUERY function fires: **views.py** def set_session_now(request): if not request.is_ajax() or not request.method=='POST': return HttpResponseNotAllowed(['POST']) request.session['my_key'] = 0 return HttpResponse('ok') and in the urls.py: path('set_session_now', views.set_session_now, name='set_session_now'), But once the process finishes; I only get "ok" sent from the server; but the session is not set; the server returns "Key Error: 'my_key'". Any help would be appreciated. -
How to populate field from the view django?
I am trying to populate a field on a template form in Django. I have tried to do it on the view as well as a value on the form template but no luck. Here is my work The outcome would be to populate username and email field from the resource model, but I am getting an UNIQUE constraint failed: auth_user.username error. Thanks forms.py class AdminRegistrationForm(UserCreationForm): is_superuser = forms.BooleanField(), password1 = forms.CharField( label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password Confirmation", widget=forms.PasswordInput) class Meta: model = User fields = ['password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if not password1 or not password2: raise ValidationError("Please confirm your password") if password1 != password2: raise ValidationError("Passwords must match") return password2 view.py def admin_registration(request, username): resources = Resource.objects.get(username=username) if request.user.is_authenticated: return redirect(reverse('index')) if request.method == "POST": resources = Resource.objects.get(username=username) admin_registration_form = AdminRegistrationForm(request.POST) if admin_registration_form.is_valid(): obj = admin_registration_form.save(commit=False) obj.is_superuser = True obj.save() user = auth.authenticate(username=[resources.username], password=request.POST['password1']) if user: auth.login(user=user, request=request) messages.success(request, "You have successfully registered") return redirect(reverse('index')) else: messages.error(request, "Unable to register your account at this time") else: admin_registration_form = AdminRegistrationForm() return render(request, 'registration/registration.html', { "registration_form": admin_registration_form, 'email': resources.email }) models.py class Resource(models.Model): ROLE = [ ('Analyst', "Analyst"), ('Team Manager', "Team Manager"), ('Quality Auditor', … -
OMR BubbleSheet Test Recognization
I'm handling my last homework for the university in Spain (Business Adminstration), and I decided create a system that the Teacher insert the Exam correct answer, then download a model to give to the students do the exam, and after recieve the exams, he uploads it and the system compare the correct answers with the answers that the students did. The model is this one: answers sheet model The model with correct answers: answer sheet correct Wrong answer exam: wrong answer exam I could develop the backend in Django, they can do everything before the test corrector. Of course I tried multiple ways (Bubblesheet OMR on google and we have a lot of people doing the same test using the same example: https://pyimagesearch.com/2016/10/03/bubble-sheet-multiple-choice-scanner-and-test-grader-using-omr-python-and-opencv/ ), I found more examples, but the most closer one was : Detect All Circles in an image (Optical Mark Recognition) using Python OpenCV , but not worked in my example file. Can someone help me please? Here you have the three options. The Idea is that the teacher will upload all the PDF files, then is transformed into img (i did it using pdf2image), and then the corrector system loop in all the images/pdf correcting and … -
Why some fields are not created while making migrations?
I have this two models in models.py class Bid(models.Model): bid = models.IntegerField(default = 0) user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "bid") def __str__(self): return f"Bid of {self.bid} from {self.user}" class AuctionListings(models.Model): name_of_item = models.CharField(max_length=32) description = models.CharField(max_length=400) owner = models.ForeignKey(User, on_delete = models.CASCADE, related_name="auctionlistings", default = None)** bid = models.ForeignKey(Bid, on_delete = models.CASCADE, related_name = "auctionlistings", default = None)** is_closed = models.BooleanField(default=False, blank=True, null=True) url = models.CharField(max_length=800) watchlist = models.ManyToManyField(User, blank=True, related_name="watch_listings") category = models.CharField(max_length=50) When i makemigrations: operations = [ migrations.CreateModel( name='AuctionListings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name_of_item', models.CharField(max_length=32)), ('description', models.CharField(max_length=400)), ('is_closed', models.BooleanField(blank=True, default=False, null=True)), ('url', models.CharField(max_length=800)), ('category', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Bid', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('bid', models.IntegerField(default=0)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bid', to=settings.AUTH_USER_MODEL)), ], ), My Question is: Why Django did not create the fields: "bid" and "user" specified in models.py. -
when there is no Overlapping i am getting overlapping validation error
With thins code i can check overlappig but the problem when overlapping is not happening i am getting overlapping validation error. How i can solve this error. form.py for i in range(count): start = self.data.get(f'applicationdefinition_set-{i}-start', []) end= self.data.get(f'applicationdefinition_set-{i}-end', []) if (start > end_bbch) or (start == start): raise ValidationError( 'Overlapping Not Allowed' ) -
How can I integrate a website functionality to a mobile app and share same database
I'm creating a website using Django as a back-end and next I will make a native mobile app using Flutter, so how can I bond these together (share same database and funcionality)? Making what is called PWA (progressive web app) -
form.is_valid() always returns False and form is not valid
i have a simple form for adding comments and in views i am checking it for validity. But it always returns False and i get error404 according to my code. I have several assumption, but it didn`t work. And now i have no idea how to get the reason views.py: class ProductDetailView(DetailView): model = Product template_name = "core/product.html" context_object_name = "product" .... def post(self, request, *args, **kwargs): if request.POST.get("product_detail_form") == 'add_comment_form_two': if self.request.user.is_authenticated: form = CommentForm(request.POST) if form.is_valid(): comment = Review(review=request.POST.get("review"), rating=request.POST.get("rating"), author=self.request.user, product_connected=self.get_object()) comment.save() print("success ") return redirect("product_detail", *args, **kwargs) else: print("error") raise Http404 .... html form <form action="" method="post"> {% csrf_token %} {{ comment_form.as_p }} <input type="submit" name="product_detail_form" value="add_comment_form_two">add comment</input> </form> forms.py class CommentForm(forms.ModelForm): review = forms.CharField( required=True, widget=forms.TextInput( attrs={"class": "comment_form", "placeholder": "Comment"}), label="" ) OPTIONS = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ) rating = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS) class Meta: model = Review fields = ["review", "rating"] model class Review(models.Model): review = models.TextField(max_length=500) author = models.ForeignKey(User, on_delete=models.CASCADE) product_connected = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="reviews") creation_date = models.DateTimeField(auto_now_add=True) last_update_time = models.DateTimeField(auto_now=True) rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) Thanks for any help, I just can't understand it for a long time. stupid rule that I have to write … -
How to use model's field's distinct values as select field's choices
My model looks like this. class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) roll_no = models.CharField(max_length=32) course = models.CharField(max_length=120) Now I want to want to make a filter form using django_filters and want to use distinct values of course field as choices of select input but it requires each value to be associated with unique id and this field have any unique id. I tried this: class StudentFilter(django_filters.FilterSet): course = django_filters.ModelChoiceFilter(queryset=Student.objects.values("course",flat = True).distinct(),empty_label=('Course')) class Meta: model = Student fields = [] but it didn't work. Note I do not want to make separate model for course. -
Does not appear to have any patterns in it. Django
when I run the project on the server, I get the following error, but there is no problem in local. The included URLconf 'config.settings' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import home.urls code from django.urls import path, include from home.views.anasayfa import anasayfa from home.views import iletisim, kategori from home.views.articles import articles_detail from home.views.productdetail import product_detail from home.views.surdur import surdur from home.views.about import abaut_detail from home.views.sozluk import sozluk urlpatterns = [ path('', anasayfa, name='anasayfa'), path('iletisim', iletisim), path('<slug:kategoriSlug>', kategori, name='kategori'), path('detail/<slug:slug>', product_detail, name='product_detail'), path('articles/<slug:slug>', articles_detail, name='articles'), path('surdurulebilirlik/<slug:slug>', surdur, name='surdur'), path('kurumsal/<slug:slug>', abaut_detail, name='abaut_detail'), path('sozluk/', sozluk, name='sozluk'), path(r'^ckeditor/', include('ckeditor_uploader.urls')) ] confi.urls code from xml.etree.ElementInclude import include import django from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path ('' , include('home.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get a response with new line characters with Django Rest Framework's Response?
I am currently trying to understand how to use the Response class from DRF. Using Django's HttpResponse, and using the following code: return HttpResponse("Hello \n World", content_type="text/plain") I get the following response: Hello World Which is what I am expecting. However, using the following code: return Response("Hello \n World", content_type="text/plain") I get the following response: "Hello \n World" Notice how I also get the pair or quotes in the second one "". Since Response is a child of HttpResponse, how can I have the same result using Response? I've come to this problem because I want to present new line characters and tab characters with Response, but I have not been successful so far. The only the I've seen that might help me was using Renderers from DRF, and making a custom one for plain text. but I do not understand how to apply them to Responses, and I am a bit surprised that DRF doesn't support plain text considering it is a subclass of HttpResponse. Thank you -
Django form fields not rendering in template
I am trying to render a simple Django Form on my index page. I have stripped it way back in an attempt to get it to work. I can display other context elements when passing them in, and I know an instance of the Form is being created (by printing type(form)), it is just empty and I cannot figure out why. I have made similar forms multiple times before without running into this issue. I have tried rendering as {{ form.as_p }} as well as {{ form }}. All that renders is the heading, the hidden csrf_token, and the submit button. Thanks in advance... from django import forms class NewPostForm(forms.Form): title: forms.CharField(label='Title', max_length=100) content: forms.CharField(label='Content', max_length=100) def index(request): form = NewPostForm() return render(request, "network/index.html", { "form": form }) {% block body %} <div class="new-post"> <h5>New Post</h5> <form action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Add Post"> </form> </div> {% endblock %} -
ManyToMany Relationship with additional fields Django Forms
For my Django project I am trying to create a singular form that allows me to add a row in my Pipeline model and link that row to the Process model through the PipelineProcess model. This is fairly straightforward by using ModelForms IF the PipelineProcess model did not have an extra field (phase). models.py class Pipeline(models.Model): name = models.CharField(max_length=100) sector = models.CharField(max_length=100, blank=True, null=True) process = models.ManyToManyField(Process, through='PipelineProcess') class Meta: managed = True db_table = 'pipeline' class Process(models.Model): name = models.CharField(max_length=100) class Meta: managed = True db_table = 'process' class PipelineProcess(models.Model): pipeline = models.ForeignKey(Pipeline, models.DO_NOTHING, blank=True, null=False) process = models.ForeignKey(Process, models.DO_NOTHING, blank=True, null=False) phase = models.CharField(max_length=100) class Meta: managed = True db_table = 'pipeline_process' forms.py class PipelineForm(ModelForm): class Meta: model = Pipeline fields = ['name', 'sector', 'phase'] This form generates the following error which makes sense: django.core.exceptions.FieldError: Unknown field(s) (phase) specified for Pipeline I have tried looking up examples of other people but none of which are useful to me. Most were far too complicated for me to put into my own project. I am fairly new with Django and web dev in general. Any help would be greatly appreciated. -
user login changes automatically in django
whenever I login in my admin panel, automatically my user site login changes to admin in django I am using django's AuthenticationForm from django.contrib.auth.forms import AuthenticationForm this is my login form code class LoginForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus':True, 'class':'form-control'})) password = forms.CharField(label=_("Password"), strip=False ,widget=forms.PasswordInput(attrs={'autocomplete':'current-password', 'class':'form-control'})) -
Django using PostGres Full Text Search not recognizing certain words when setting config='english'
So I'm running into a very weird issue. I'm using Django's SearchQuery app in Django, using Django 3.2.1 and the most up to date PostGreSQL. The issue emerges when I use a search query with websearch and config set to english. Here is the initial code for the instantiation of the search_query with config='english' search_query = SearchQuery(query_string, search_type='websearch', config='english') And this is the code for when I search for it: agenda_items = AgendaItem.objects.annotate(search=SearchVector('name', 'description', 'note'),search_rank=SearchRank('search', search_query)).filter(search=search_query).order_by('-search_rank').distinct() When I search for the word "cupcake" it displays nothing, despite the word actually being present. However, if I remove config='english' from the SearchQuery it works. However, I lose the English language support. Does anyone have any ideas. -
'AnonymousUser' object is not iterable at my index
So hello guys, Im new here at Django and while running my code i ran to this kind of error 'AnonymousUser' object is not iterable it highlight my error in my index line 37. patient=Patient.objects.filter(user = request.user) so this is my views.py def index(request): feature1 = Feature.objects.all() Appnt = Appointment() if request.user: patient=Patient.objects.filter(user = request.user) if request.method == 'POST': name = request.POST.get('name') Appnt.name = name email = request.POST.get('email') Appnt.email = email phone = request.POST.get('phone') Appnt.phone = phone Adate = request.POST.get('date') Appnt.Adate=Adate Dept = request.POST.get('department') Appnt.Dept=Dept Doc = request.POST.get('doctor') Appnt.Doc=Doc Content = request.POST.get('message') Appnt.Content = Content Appnt.ref = "ref_" + str(len(Appointment.objects.all()) + 1) Appnt.save() sendEmail(email, "Date: " + Adate + "\n" + name + "\n" + phone + "\n" + Dept + "\n" + Doc + "\n"+ Content) context = { 'feature1' : feature1, 'Appointment' : Appnt } return render(request, 'index.html', context) and this is my urls.py path('', views.index , name='index'), -
Adding custom permission to Django Rest Framework Function-Based view
I am trying to write a custom IsOwner permission for a DRF function based view that has a parameter of user_id. The view is as follows: @api_view(['GET']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def return_credibility(request, user_id): credibility = utils.get_credibility(user_id) return Response({'id': user_id, 'credibility': credibility}) except I would want to replace permissions.IsAuthenticatedOrReadOnly with my custom IsOwner permission. I tried writing something like this: class IsOwner(permissions.BasePermission): def has_permission(self, request, view): return request.user.id == view.user_id except I am not sure how to access the user_id property from the view. Does anyone know how I can do this? Thanks! -
How Django handling long request in another request?
Issue about django handling a long request(50sec) in another request(3sec). I have a POST request will return some infomation for user, in this request will call another api in the same app and it will query database and generate pdf report then upload to s3, it will cost about 50sec. How can I let first request return infomation to user and generate pdf api run in background? I have done some research, found Celery may be can handle this task, is this recommend? or anyone have advice? Thanks in advance!!! -
Django 3.0 update a model inside of a detailview
I have a "project" model that has a "status" field. The status can be active, paused, or complete. I want to be able to update the field via form on the project detail view. I have read a few solutions to this problem but, as a newbie, I haven't been able to get this to work. When I submit the form I get an http 405 error and the instance is not updated. the model: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT) objects = ProjectManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('company_project:project_detail', args=[str(self.id)]) the view class CompanyProjectsDetailView(DetailBreadcrumbMixin, FormMixin, DetailView): model = Project id = Project.objects.only('id') template_name = 'company_accounts/project_detail.html' context_object_name = 'project' form_class = ProjectStatusForm notescount = Project.objects.annotate(num_notes=Count('notes')) documentscount = Project.objects.annotate(num_documents=Count('project_documents')) todoscount = Project.objects.annotate(num_documents=Count('todo_group')) def form_valid(self, form): project = get_object_or_404(Project, id=self.kwargs.get('pk')) theform = form.save(commit=False) theform.project = project form.save() return super(CompanyProjectsDetailView, self).form_valid(form) the form class ProjectStatusForm(forms.ModelForm): class Meta: model = Project fields = ['status'] labels = {'status': 'project status'} widgets = { 'status': forms.Select(attrs={'id':'PROJECT_CHOICES'}), } On the page I use this code to add the form <form action="" method="post"> {% csrf_token %} {{ …