Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Django, bycrypt check password returns false
# coding: utf-8 from django.http import HttpResponse from django.http import JsonResponse from django.views.generic import View from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth import authenticate from django.contrib.auth.models import User as UserDjango from bcrypt import hashpw, gensalt, checkpw from categories.models import User import datetime class Register(APIView): def post(self, request): now = datetime.datetime.now password = request.data['password'].encode('utf-8') username = request.data['username'].encode('utf-8') email = request.data['email'].encode('utf-8').lower() if( User.objects.filter(email = email).count() == 1) : return Response( { 'success': False, 'message': 'Email registered previously' }) else: hashed = hashpw(password, gensalt() ) user = User(email=email, username=username, password=hashed, active='1', verified='0') user.save() return Response( { 'success': True, 'message': 'Succesful registration' }) class Login(APIView): def post(self, request): if(request.data['password'] == None or request.data['email'] == None) : return Response( { 'success': false, 'message': 'Username and password needed' } ) password = request.data['password'].encode('utf-8') email = request.data['email'].encode('utf-8').lower() user = User.objects.filter(email = email) if user.count() == 0 : return Response( { 'success': False, 'message': 'Email not registered' } ) But, at the moment to test it, I get the next error: Internal Server Error: /user/login Traceback (most recent call last): File "/usr/lib64/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/lib64/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib64/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response … -
How can I make a page that will always display the latest post from my Django Model
Thank you to all of the people who looked at this in advance! I really appreciate it. I have setup a very simple model that consists of two parameters (title, which is the date when this was published and the text, that's it): models.py class Post(models.Model): title = models.DateField(blank=True, null=True) body = models.TextField() def __str__(self): return str(self.title) After following a standard "create a blog in Django tutorial" I have created two views that show the list of everything posted and a view that will show details of any selected post. views.py class NowListView(ListView): model = Post template_name = 'archive.html' class NowDetailView(DetailView): model = Post template_name = 'then.html' Finally, I have this urls.py that successfully shows all the posts at http://127.0.0.1:8000/now/archive and specific post at http://127.0.0.1:8000/now/archive/1 (or any other number, depending on the pk). urls.py urlpatterns = [ path('archive', NowListView.as_view(), name='archive'), path('archive/<int:pk>', NowDetailView.as_view(), name='then'), ] What I want to achieve is to display the latest post on http://127.0.0.1:8000/now. I have tried a million ways to do it, and nothing worked, always something in the way (would take too long to write all of them). After all this tries it is obvious to me that I have to use a query to … -
List available SRID values in GeoDjango
What is the easiest way to generate a list of SRID values and their WKT names/titles. There should be about 3000 values that are listed in the table SPATIAL_REF_SYS. Are there Django models that I can load to access this info or do I need to create a sql query to access the info? -
Using user_passes_test Restrict Access to View by Group or Logged in User
Users have individual profiles where I am trying to restrict their access to their individual profile while allowing users in an admin Group to access all profiles. Ideally I was hoping to accomplish this by way of the decorator user_passes_test with one function. If need be I could use two different functions with a decorator for each. Though combining all into one may be cleaner. # Views.py def profile_access(CustomUser, request): officer = CustomUser.groups.filter(name='Officer') logged_in_user = request.self.CustomUser if officer or logged_in_user: return True else: return redirect('homepage') @user_passes_test(profile_access) def profile(request, pk): # Profile content here I am not sure how to identify the logged in user to restrict them to their Profile only while also allowing users in the Officer group to see all Profiles. -
How do I store information about a front-end button on the Django server?
Basically I want to store a buttons service server-side that way it can persist through browser closes and page refresh. Here's what the user is trying to do The user searches in a search bar for a list of products. When the results show up, they are shown a button that triggers an action for each individual product. They are also shown a master button that can trigger the same action for each product that is listed. Upon clicking the button, I want to disable it for 30 seconds and have this persist through page refreshes and browser close. What I've done Currently I have this implemented using AJAX calls on the client side, but if the page refreshes it resets the button and they can click it again. So I looked into using javascript's localStorage function, but in my situation it would be better just to store this on the server. What I think needs to happen Create a model in my Django app for a button. Its attributes would be its status and maybe some meta data (last clicked, etc). Whenever the client requests a list of products, the views will send the list of products and it … -
How to use the django import-export library with django and angular?
Good community, I have a question, I want to use the django import-export library to upload records through excel, the question is that I'm using the frontend angle and django rest frameowork to consume a api rest, in this case a database for show a CRUD with the data of the database, but I have the question of how to import records in Excel through angular, until now I had achieved it with the views and django template, but in this case if I have no idea. -
Implement bulk save in django admin using another model
Assuming I wanted to track which countries airlines fly to. I might have a model Airline and a model Country with a many-to-many relationship between them. Say I made that through model explicit and called it CountryCoverage with a foreign key each to Airline and Country. All is working well but now I want to add a new airline which happens to cover the whole world. While there are other options, going through Django admin would require a new entry in CountryCoverage for each country/airline combination... a lot of manual work. As it happens the Country model has a many-to-many relationship with another model called CountryGroup. Ideally what I would like to do is to show CountryGroup on the CountryCoverage admin page and if the user selects the combination Airline X / Global coverage then I would like to automatically save an entry for each Airline X / Country combination. How can I best achieve this? I saw that it is possible to display another model on the admin page and to overwrite the save method so I thought of combining the two somehow. -
Django sqlite3 database displayed on HTML table
I'm trying to filter (by column element) and display information from a sqlite3 database directly onto a HTML table. I've read in multiple places that you should use Django's ORM instead of a database. However, the data is continuously updating in the database so I'm not sure if this is a route to pursue with this. TL;DR I'm looking for a way to open a sqlite3 .db file and chuck it into an HTML table. I have looked over the django documentation regarding models, as well as looked at several different websites/tutorials (here, stack overflow; I even found django-tables2 which I thought was going to work), all to no avail. I'm essentially at a roadblock and I'm not sure where to go and/or what to do. Here is how the database is structured: --------------------------------------------- | Name | Type | Col 1 | ... | Col N | Color | --------------------------------------------- | Gary | A | Data | ... | Data! | Green | | Mark | A | Data | ... | Data? | Blue | | Ray | B | Data | ... | Data. | Red | ... As far as the HTML is concerned, I'd like to … -
How do a advanced filter to django rest framework with OR and AND operators
I need do a filter to django rest framework API that support OR and AND operators. -
Migrations error in django 2; AttributeError: 'str' object has no attribute 'decode'
I am running migrations on my newly built app called 'core'. When I run migrations on it, I get an error that tells me this; query = query.decode(errors='replace') AttributeError: 'str' object has no attribute 'decode' I am posting the Traceback below; C> python manage.py makemigrations core Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "C:\Python37\lib\site-packages\django\db\migrations\loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "C:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations if self.has_table(): File "C:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor return self._cursor() File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 233, in _cursor self.ensure_connection() File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.init_connection_state() File "C:\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 233, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "C:\Python37\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python37\lib\site-packages\django\db\backends\mysql\features.py", line 82, in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') File "C:\Python37\lib\site-packages\django\db\backends\utils.py", line … -
HTML: Align progress bars vertically
I have a list of items with a progress bar each: What I want is that all progress bars are aligned, no matter how long the text on the left is. (I already know how long the longest text on the left will be) The code snippet (in Django): <strong style="font-family:Arial">{{ score.0 }}</strong> <progress value="{{ score.1 }}" max="10" style="margin-left: 5%"></progress> style="margin-left: 5%" doesn't work because it's relative to the corresponding text. I already tried using "vertical-align" variations, but nothing worked. -
Django: Reuse ModelForm with different Models
I am trying to make a schedule with different responsibilities. I want to order the participants for a rotation, like: Participant 12 Participant 4 etc... I was going to save each responsibility order in a different model. Since my ModelForm is the same for each responsibility, is it possible to change the model being used when the form is instantiated? class ReusableModelForm(ModelForm): class Meta: model = desired_model # Call it like this ReusableModelForm(data, desired_model=MyModel_1) ReusableModelForm(data, desired_model=MyModel_2) -
Specify AM and PM TimeField in Django model and serializer
I have my models.py class Restaurant(models.Model): name = models.CharField(max_length=100, blank=False) opening_time = models.TimeField(blank=False) closing_time = models.TimeField(blank=False) def __str__(self): return self.name @property def is_open(self): return True if self.opening_time <= datetime.now().time() < self.closing_time else False And, my serializer.py: class RestaurantSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Restaurant fields = ('pk', 'name', 'opening_time', 'closing_time') How can I have so the time I input is either 24 hours or AM and PM. -
The imageField doesnt upload images django
I am trying to upload pictures from a imageField, but it doesnt upload anything when i try. I did it before but i dont know what is causing this, everything seems to be fine, so i hope you can help me: here is my models.py: def upload_location(instance, filename): return "uploads/%s/img/%s/" % (instance.id, filename) class CustomUser(AbstractBaseUser, PermissionsMixin): ...... width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) photo = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field" ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() Here is my form: class UserConfigurationForm(UserChangeForm): class Meta: model=CustomUser fields = ( 'first_name', 'last_name', 'email', 'phone_number', 'direction', 'password', 'photo', ) Dont pay attention to the other fields apart from ´photo´,those fields works fine. just have the problem with the image My view: def configuration(request): categoria = Clasificacion.objects.filter(existencia=True) templates = Templates.objects.get(isSelected=True) if request.method == 'GET': form = UserConfigurationForm(instance=request.user) else: form = UserConfigurationForm(request.POST or None, request.FILES or None, instance=request.user) if form.is_valid(): form.save() return redirect('myuser:myuser') return render(request, 'myuser/configuration.html', {'form': form, 'categoria':categoria,'templates':templates}) And finally my template (I will include the entire form soyou can see it).. <form method="post" action='' enctype="multipart/form-data"> {%csrf_token%} <div class="col-sm-8 "> <strong>{{form.photo}}</strong></div> <!--FIRST NAME--> <label for="first_name">Nombre</label> <div class="form-group"> <input class= "form-control" type="text" name="first_name" maxlength="20" value="{{user.first_name}}" required> </div> <label for="last_name">Apellidos</label> … -
Display data from a database in a HTML page using django views
I have a problem with creating a view with data from the database. I created a view that should download data from videos (var films) and display them, unstable I only have a blank page. views.py from django.shortcuts import render from django.http import HttpResponse from .models import Films # Create your views here. def index(request): filmy = Films.objects return render(request, 'films/index.html',{'filmy':filmy}) index.html <h1>Films</h1> {% for film in films.all %} {{filmy.summary}} <br> {% endfor %} models.py from django.db import models # Create your models here. class Films(models.Model): image = models.ImageField(upload_to='images/') summary = models.CharField(max_length=200) def __str__(self): return self.summary