Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'BooleanField' object has no attribute 'use_required_attribute' in django
as the title says i am getting the error while i am using a booleanfield: 'BooleanField' object has no attribute 'use_required_attribute' in django Models.py class contactData(models.Model): ... mapActivated = models.BooleanField(default=True) forms.py: class ContactForm(forms.ModelForm): class Meta: model = contactData fields = [ 'vision', 'horario', 'image_path', 'mapActivated', ] labels = { 'image_path': '', } widgets = { 'mapActivated': forms.BooleanField(required=True) } Anyone can help me with this? Thank you! -
How do I stop ajax call from refreshing my page?
<form id="review" method="post"> {% csrf_token %} <button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" > <span class="icon text-white-50"> <i class="fas fa-poll-h"></i> </span> <span class="text">Fetch Reviews</span> </button> </form> This is my html form on a Django rendered page <script type="text/javascript"> $(document).on('submit','#review'.function(e){ e.preventDefault(); e.stopPropagation(); $.ajax({ type:'POST', URL:'/reviews/', data:{ asin:$('#sbtn').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, beforeSend:function() { $('#loader').removeClass('hidden'); }, complete : function() { $('#loader').addClass(''); }}); return false; }); This is the ajax function on the page. The problem is...the current page is the result of a form on a previous page so as soon as the form-submit event is invoked the page refreshes and data on the page is lost. I tried both e.preventDefault() and e.stopPropagation() but that doesn't help. I'd like to know if you have some approach or a workaround..Thank you! -
How can I embed an API to a Django Project?
So I'm working on a Django project where I want to embed an API made by a friend of mine with python and some libraries like matplotlib and others,it should process some images and return a result(also an Image).however i can't really get my mind around it,I made a data model with ImageField but i don't know how I can call the API with get(from HTML button) method ( making a view for it ) or how i should handle this. I thought that I could make a model with two fields one is the uploaded by the user and the other is the processed but what's next ? -
Django sometimes receives ManyToManyField lookup result from some sort of cache
When I try to access a ManyToManyField with through= specified using the field name, the results are taken from some kind of cache - not from the database. Suppose we have these (simplified) models: class Device(models.Model): name = models.CharField(max_length=50) class Person(models.Model): name = models.CharField(max_length=50) devices = models.ManyToManyField( Device, through="Person_device", related_query_name="device", related_name="person" ) class Person_device(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE) row_time = models.DateField(auto_now=True) # just some extra data ipad = Device.objects.create(name="iPad") iphone = Device.objects.create(name="iPhone") samsung = Device.objects.create(name="Samsung") sam = Person.objects.create(name="Sam") mary = Person.objects.create(name="Mary") Person_device.objects.create(person=sam,device=iphone) Person_device.objects.create(person=susie,device=samsung) # Note we didn't apply ownership of any iPads Now, let's try to access some of these. [device.name for device in Person.objects.get(name="Sam").devices] [device.name for device in Person.objects.get(name="Mary").devices] We were supposed to get ["iPhone"] ["Samsung"] But what I actually am getting is: ["iPad"] ["iPad"] Now, this problem is hard to reproduce. I have simplified this, but this is essentially the same code I used in my project. One of the possible reasons that crossed my mind, is that it messes up when you play around with editing the model, running application, then editing it back (no migrations in the middle). Of course, this problem is solved if we access the necessary QuerySet directly by … -
Django django.utils.timezone.make_aware not adding default timezone
Naive datetime not properly converted in timezoned datetime by django timezone.make_aware My application is handling some strings representing datetime, for example: 2019-05-20 15:47:19 I'm receiving these data from an external API so I don't have control over the received values. I'm trying to set this datetime in my python model using the following code: datetime_to_parse = '2019-05-20 15:47:19' my_model.start = timezone.make_aware(datetime.strptime(datetime_to_parse, "%Y-%m-%d %H:%M:%S")) my_model.save() What I'm obtaining is the following error: DateTimeField Event.start received a naive datetime (2019-05-20 15:47:19) while time zone support is active Since I'm calling make_aware I expect the datetime to be automatically converted in a timezoned datetime using the timezone specified in my django settings. My django settings contain the following definition: TIME_ZONE = "Europe/Zurich" Am I doing something wrong ? -
Why one Django database query is working when similar one is not
I reused similar code twice but on one occasion it doesn't add anything to database, can anyone tell me why? Lack of form validation is the problem? I'm trying to increase some user model fields by certain integer every time form is send to server. One of them working, one doesn't. Code below increase amount_comments by one every time: def add_comment(request, pk): ticket = get_object_or_404(Ticket, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): user = CustomUser.objects.get(username=request.user) user.amount_comments += 1 user.save() return redirect('show_single', pk=pk) else: form = CommentForm() ...and this one doesn't increase contributions for some reason: def show(request, pk): if request.method == "POST": user = CustomUser.objects.get(username=request.user) user.contributions += 5 user.save() return redirect('checkout', pk=pk) I don't get any errors just checking admin panel and user doesn't get his contributions field changed by 5 when amount_comments goes up every time. -
Unable to display QuerySet in Django view
I was trying to display a QuerySet using method below, Passing Django Queryset in Views to Template I was able to display single object by using get() method, however it returns as a blank page when I try to return all data in the Restaurant Table. Class Restaurant class Restaurant(models.Model): restId = models.AutoField(db_column='restId', primary_key=True) restName = models.TextField(db_column='restName') phone = models.IntegerField() address = models.TextField() ratings = models.DecimalField(max_digits=2, decimal_places=1) cuisine = models.TextField() region = models.TextField() #image = models.ImageField() last_modify_date = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = "restaurant" views.py def index_view(request): rest_list = Restaurant.objects.all() context = { 'rest_list': rest_list } return render(request, 'index.html', context) index.html <h1>Index</h1> {% for rest in rest_List %} {{ rest.restId }} {{ rest.restName }} {% endfor %} -
How do I implement a location drop down menu
I would like to implement a location drop down menu like the ones shown on Airbnb.com and Postmates.com. Basically I would like a user to be able to type in a location anywhere around the world and show only results from that location. I assume the location drop down menu has something to do with Google maps but I can't seem to figure it out. -
Django NotFoundError at /admin/blog2/article/add/
I am trying to create a post from Django default admin template but fires me an error that i am not getting... this is my models: from django.db import models import uuid class Organization(models.Model): organization_name = models.CharField(max_length=50) contact = models.CharField(max_length=12, unique=True) def __str__(self): return self.organization_name class Author(models.Model): name = models.CharField(max_length=40) detail = models.TextField() organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Article(models.Model): alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) and fires me below this error: -
How to fix "pip installation error on pillow"
I just ran pip install pillow on pycharm windows but it gives an error as mentioned below help me to solve this problem i tired manually installing pillow form downloading pillow form github by python setup.py install but didn't work on installing on pycharm i don't know what the error is the entire process in mentioned below:- Collecting Pillow Using cached https://files.pythonhosted.org/packages/81/1a/6b2971adc1bca55b9a53ed1efa372acff7e8b9913982a396f3fa046efaf8/Pillow-6.0.0.tar.gz Installing collected packages: Pillow Running setup.py install for Pillow ... error Complete output from command C:\Users\rijal\Desktop\webdevlops\django_project\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\rijal\\AppData\\Local\\Temp\\pip-install-di5is9gd\\ Pillow\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\rijal\AppData\Local\Temp\pip-record-zdea w2p6\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\rijal\Desktop\webdevlops\django_project\venv\include\site\python3.8\Pillow: C:\Users\rijal\AppData\Local\Temp\pip-install-di5is9gd\Pillow\setup.py:29: RuntimeWarning: Pillow does not yet support Python 3.8 and does not yet provide prebuilt Windows binaries. We do not recommend buildin g from source on Windows. warnings.warn( running install running build running build_py creating build creating build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\PIL copying src\PIL\BdfFontFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ContainerIO.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\CurImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ExifTags.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\features.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FliImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FontFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FtexImagePlugin.py -> … -
Is Django admin functionality used in production on large sites or do you use it for testing only?
I have been working through the Django tutorial and I note on page 7... https://docs.djangoproject.com/en/2.2/intro/tutorial07/ ...that the much touted "admin for free" feature of Django is rather weak. The tutorial shows how to add Choice objects to Question objects in the Polls admin. Three Choices are added by the ChoiceInline class, but the problem is that none of those three may be removed. Only Choices added by clicking the Add button may be removed. This is poor UI/UX because it mixes static and dynamic behaviour in an arbitrary way. It doesn't look so bad in the tutorial example, but if the feature is deployed thoroughly, it can result in new Question objects having three Choices (or however many are specified) that cannot be deleted. One solution is to use no Choices by default and only use the Add button, but that is not good either, as there should be at least one Choice object by default, or rather two of them, since we're working on a Poll. But the fields should all have the same functionality, they should all be removable. Having seen this, my question for those experienced in working with Django on large projects: Is the "admin for … -
How can I display the values from a ManyToMany Field in Django instead of their Id?
I have two models Influencer class Influencer(models.Model): full_name = models.CharField('Full Name',max_length=255) username = models.CharField('Username',max_length=255,unique=True) photo = models.URLField(blank=True,max_length = 500) email_id = models.EmailField('Email Id',blank=True,max_length=500) categories = models.ManyToManyField(Category,blank=True,max_length=400) and 2. Categories class Category(models.Model): name = models.CharField(max_length=400) def __str__(self): return self.name Influencer has a many to many field categories. My views functions to display all the influencers is: def index(request): influencers = Influencer.objects.all().order_by('followers') paginator = Paginator(influencers,16) page = request.GET.get('page') paged_listings = paginator.get_page(page) user_list = UserList.objects.all().filter(user_id = request.user.id) queryset = list(chain(paged_listings,user_list)) ser_query = serializers.serialize('json', queryset) return HttpResponse(ser_query,content_type='application/json') The HttpResponse contains category id's instead of category names, something like this: where categories is an array which contains category id's. I want to display the name of categories instead of their id's. I think this can be achived using Django Rest Framework nested serializer, but at this moment I am not using DRF. -
How the users can access my Elasticsearch database in my Django SaaS?
Let's say that I have a SaaS based on Django backend that processes the data of the users and write everything to the Elasticsearch. Now I would like to give users access to search and request their data stored in ES using all possible search requests available in ES. Obviously the user should have only access to his data, not to other user's data. I am aware that it can be done in a lot of different ways but I wonder what is safe and the best solution? At this point I store everything in one index and type in the way shown below but I can do this in any way. "_index": "example_index", "_type": "example_type", "_id": "H2s-lGsdshEzmewdKtL", "_score": 1, "_source": { "user_id": 1, "field1": "example1", "field2": "example2", "field3": "example3" } -
Using numpy, javascript, and django
I am trying to create a web app using django, and integrating some javascript and i'm not sure where to put the numpy analysis to allow javascript to access the data easily. I am just looking for some advice on where to put my data analysis code within the django framework. At the moment I have got a model/form for people to enter data, and within views.py I have access the inputs and done the calculation (creating a dataframe) there. Still within the views, I have created a graph (using matplotlib) that saves as an image that my html reads in. I am not happy with the graph that is being created, so I want to use chart.js for this instead. However I am not sure on the best way to go about structuring this. Should I keep the calculations within the views class, or is it best to move it out? I have looked at using the django rest framework, but I am having difficulty getting the dataframe that I created in my view for the javascript to read. Has anyone done a similar thing or has any advice on how to go about setting this up? -
Sqlite ordering/sorting for turkish alphabet
How can I sort letters for Turkish alphabet? Can I do it with a function? > def a(request): > keyword = request.GET.get("keyword") > if keyword: > makaleler = Makale.objects.filter(title__contains = keyword) > return render(request,"a.html",{"makaleler":makaleler}) > > makaleler = Makale.objects.filter(title__startswith="A").order_by("title") > context = { > "makaleler":makaleler > } > return render(request, "a.html",context) -
ModelForm save() got an unexpected keyword argument 'commit'
i try to make custom user in django but have a problem with, please help the probem is when me add or change the user from the admin and save it, i am not understand where the problem is but i feel in form.py, please help me to fix this. models.py class ObUser(AbstractUser): SEX = ( ('M', 'MALE'), ('F', 'FEMALE'), ) username = models.CharField(max_length=30, unique=True) email = models.EmailField(max_length=30, unique=True, blank=False, null=False) first_name = models.CharField(max_length=20, blank= False, null=False) last_name = models.CharField(max_length=50, blank= False, null=False) password = models.CharField(max_length=50) born_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) address = models.TextField(blank=True, null=True) phone = models.IntegerField(blank=True, null=True) sim_id = models.IntegerField(blank=True, null=True) quotes = models.CharField(max_length=100, blank=True, null=True) sex = models.CharField(max_length=1, choices=SEX) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) last_update = models.DateTimeField(auto_now=True, auto_now_add=False, blank=True, null=True) date_joined = models.DateField(auto_now=False, auto_now_add=True) is_verified = models.BooleanField(default=False) objects = ObUserManager and then i make the ModelForm form.py class ObUserCreate(forms.ModelForm): password1 = forms.CharField(label='password', widget=forms.PasswordInput) password2 = forms.CharField(label='konfirmasi password', widget=forms.PasswordInput) class Meta: model = ObUser fields = ('username', 'email', 'first_name', 'last_name', 'password') def clean_password2(self): password1=self.cleaned_data.get('password1') password2=self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('password tidak sama') return password2 def save(self, commit=True): self.clean_password2() user = super().save(commit=False) user.set_password(self.cleaned_data['password2']) if commit: user.save() return user class … -
Connect Form attributes with User model inside views before saving form data
I am trying to connect a form to the username value. What I am trying to do is to save the person who commented on a post (author) as the username of the User. I have tried a few methods but none is working. When I ask users to manually provide an author value, it saves it and shows in my html page as posted by followed by the value provided by users. Below are the codes. def add_comment_to_post(request,pk): post=get_object_or_404(Post,pk=pk) if request.method=='POST': form=CommentForm(request.POST) if form.is_valid(): def update_form(self,form): self.comment=form.save(commit=False) self.comment.post=post self.comment.author= User.username self.comment.save() return redirect('post_detail',pk=post.pk) else: form=CommentForm() return render(request,'blog/comment_form.html',{'form':form}) When I used the above code, the submit button did not return any value. and I have also used comment=form.save(commit=False) comment.author = User.username The above code says value too big(50) My Commentform is class CommentForm(forms.ModelForm): class Meta: model= Comment fields=('text',) widgets={ 'text': forms.Textarea(attrs={'class': 'editable medium-editor-textarea'}), and models.py is class Comment(models.Model): post=models.ForeignKey('blog.Post', related_name='comments',on_delete=models.CASCADE) author=models.CharField(max_length=50) created_date=models.DateField(default=timezone.now) approved_comment=models.BooleanField(default=False) def approve(self): self.approved_comment=True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text What can I do to save the value so that the only that users, who commented on the post is able to delete the comment (except admin). -
how to implement checkbox selection of products in frontend using jquery or any other approach
I am working on compare product functionality , and i want to compare product .My issue is that i want to implement compare product functionality like used in this website (only frontend part) like the way it is showing selected product on compare template at the bottom of page and removes when ckecked on removed button.I need advice and steps if possible. -
How can I create group of objects to store information?
I have two models Pigeons and Treatment. Every pigeon can have multiple treatment. I want to create some groups of pigeon like all pigeons, cock, female, squeakers and when I want to create a treatment to select the group and assign the medication. #models class Pigeons(models.Model): ring= models.CharField(max_length=25, null=False, blank=False, unique=True) status = models.ForeignKey(PigeonStatus, on_delete=models.CASCADE, null=False, blank=False) ...... class Treatment(models.Model): date = models.DateTimeField(default=timezone.now, null=True, blank=True) # we can treat only one pigeon pigeon = models.ManyToManyField(Pigeons, on_delete=models.CASCADE) # or select group to assign medication group = ...... medication = models.ForeignKey(Medication, on_delete=models.SET_NULL) Which is the best approach to do this? I have to create a separate model that store groups or it can be in the template? -
Add to same template another ListView depending on previous ListView item selection Django
How can I pick one item in a ListView and list further items which are an array field of that item and allow them to be picked? For example: I have a model that has as its field two other models as ArrayModelFields (which is a Djongo class for MongoDB integration, functions like a formset) class LobDetail(models.Model): lob_name = models.CharField(max_length=64, primary_key=True, choices=LOB_CHOICES, default='thanks') #type = models.CharField(max_length=20, choices=TYPE_CHOICES) source = models.ArrayModelField( model_container = Source, ) destination = models.ArrayModelField( model_container = Destination, ) def __str__(self): return self.lob_name + " "+ self.type (where Source and destination are two abstract models) I have a template file that shows a ListView of all the available LobDetails. I have added a link along with each list item that allows me to pick that item. Now I want to list all the sources and destination, depending on that picked item and further allow me to pick one amongst them. All of this I want to do on the same page. But I can't figure out how? -
Use variable with TemplateView
I used to have my pages in Django defined with functions like this: def pdf(request): return render(request, 'blog/pdf.html', {'title': 'PDF files'}) Where I was using a Title var for html page title. I started to use a TemplateView class for my pages and I'm not sure how to use the same title inside of something like this: class About(LoginRequiredMixin, TemplateView): template_name = 'blog/about.html' -
csrf token using decorator is not working in Djnago Deleteview
csrf token is not working I am looking for a reason. error message is this Failed to load resource: the server responded with a status of 403 (Forbidden) code is this from django.http import JsonResponse from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import ListView, DeleteView from todo.models import Todo @method_decorator(csrf_exempt, name='dispatch') class ApiTodoDelV(DeleteView): model = Todo def delete(self, request, *args, **kwargs): print("todo 삭제 실행 ~!") self.object = self.get_object() self.object.delete() return JsonResponse(DATA={}, status=204) html script code is this remove_todo: function (todo,index) { console.log("remove_todo()...", index); var vm = this; axios.delete('/api/todo/' +todo.id+'/delete/') .then(function(res){ console.log("DELETE RES" , res); vm.todoList.splice(index, 1); }) .catch(function (err){ console.log("DELETE ERR", err); }) }, do you know why or how to slove problem? -
Django guardian user.has_perm false for existing data
I was trying to give permission using Django guardian. when I try to give permission for existing data its show me a false message but when I create a new object its show me true. what I'm doing wrong? My code : >>>from django.contrib.auth.models import User >>>from print.models import * >>>from guardian.shortcuts import assign_perm >>>user = User.objects.create(username='tanvir',password='antu') >>>excel = ExcelData.objects.all() >>>assign_perm('delete_exceldata', user, excel) >>>user.has_perm('delete_exceldata', excel) >>>False But If I do >>>from django.contrib.auth.models import User >>>from print.models import * >>>from guardian.shortcuts import assign_perm >>>user = User.objects.create(username='tanvir',password='antu') >>>excel = ExcelData.objects.create(order_number='01245632145214') >>>assign_perm('delete_exceldata', user, excel) >>>user.has_perm('delete_exceldata', excel) >>>True -
Issue on Django Url Routers
I an trying to make url router in Django which supports following URLs : http://localhost:8000/location/configuration http://localhost:8000/location/d3d710fcfc1391b0a8182239881b8bf7/configuration url(r'^locations/configuration$',location_config.as_view(), name="location-config"), url(r'^locations/(?P<location_key>[\w]+)/configuration$',location_config.as_view(), name="location-config-uri") Whenever I tried to hit - http://localhost:8000/location/configuration, it picked up the second url routing format instead of picking up first one. It throws an error : TypeError at /locations/configuration/ get() missing 1 required positional argument: 'location_key' Can anyone help me here what goes wrong with the url routing format ?? -
manage create method of django when there are lots of fields
I am working on project where I have taken django in backend. I have a model call profile which is related to the user. A profile model has more than 10 fields and when trying to update the user profile, my code for updating all those fields would be something like this class UpdateProfile(graphene.Mutation): class Arguments: input = types.ProfileInput(required=True) success = graphene.Boolean() errors = graphene.List(graphene.String) profile = graphene.Field(schema.ProfileNode) @staticmethod def mutate(self, info, **args): is_authenticated = info.context.user.is_authenticated data = args.get('input') if not is_authenticated: errors = ['unauthenticated'] return UpdateProfile(success=False, errors=errors) else: profile = Profile.objects.get(user=info.context.user) profile = models.Profile.objects.get(profile=profile) profile.career = data.get('career', None) profile.payment_type = data.get('payment_type', None) profile.expected_salary = data.get('expected_salary', None) profile.full_name = data.get('full_name', None) profile.age = data.get('age', None) profile.city = data.get('city', None) profile.address = data.get('address', None) profile.name_of_company = data.get('name_of_company', None) profile.job_title = data.get('job_title', None) profile.zip_code = data.get('zip_code', None) profile.slogan = data.get('slogan', None) profile.bio = data.get('bio', None) profile.website = data.get('website', None) profile.github = data.get('github', None) profile.linkedin = data.get('linkedin', None) profile.twitter = data.get('twitter', None) profile.facebook = data.get('facebook', None) profile.image=info.context.FILES.get(data.get('image', None)) profile.save() return UpdateProfile(profile=profile, success=True, errors=None) so my question is, suppose, if there are even more than 20, 30 fields, how would you design your code on updating those fields? (considering only views part)