Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "3": "StudentsEnrolledSubject.Subject_Section_Teacher" must be a "SubjectSectionTeacher" instance
Django signal Cannot assign "3": "StudentsEnrolledSubject.Subject_Section_Teacher" must be a "SubjectSectionTeacher" instance. i have foreignkey Subject_Section_Teacher in StudentsEnrolledSubject related in SubjectSectionTeacher in this line Subject_Section_Teacher=each.Employee_Users.id is my error I have this models.py class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) @receiver(pre_save, sender=StudentsEnrollmentRecord) def get_older_instance(sender, instance, *args, **kwargs): try: instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk) except StudentsEnrollmentRecord.DoesNotExist: instance._old_instance = None @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): if not created: older_instance = instance._old_instance if older_instance.Courses != instance.Courses or \ older_instance.Section != instance.Section or \ older_instance.Education_Levels != instance.Education_Levels: StudentsEnrolledSubject.objects.filter( Students_Enrollment_Records=instance ).delete() else: return None teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section, Education_Levels=instance.Education_Levels, Courses=instance.Courses) for each in teachers: StudentsEnrolledSubject.objects.create( Students_Enrollment_Records=instance, Subject_Section_Teacher=each.Employee_Users.id) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) -
React+ServiceWorker and Django admin panel caching problem
I am working on a larger project than usually and it is being hosted on AWS using dockers and all the magical stuff. We have backend that is available under /admin route and while the browser recieves a request I'd like to skip to loadBalancer instead of giving the request in to serviceWorker to decide if it should serve cached /admin or not. In my modules I've got: NavigationRoute.mjs constructor(handler, { whitelist = [/./], blacklist = [/^\/admin\/.*/]} = {}) so I was quite sure it should work, but that's just a local change. How should I go about to get these changes pushed? Sometimes I can see people waving eject command but I don't want to configure the project myself. Maybe someone here had a chance to work with Django+React+ServiceWorker like myself and would like to share hers/his approach. Current status: App is being hosted on https://staging.nextgloc.com/ and doesn't get /admin if you don't clear cache (therefore allowing me to access it until it's cached again). -
form not display on html, django
I tried to make a blog that allows user posts, store the posts in the db along with the posted date time and the person who posted it. My problem is that I somehow cannot load the {{form}} to my UI, which makes my form invalid and I just don't know why it doesn't show up the input text box. I'm not sure if I need a get_post function, but I'll just put it in views.py. (I havnt write the html of that part yet. Just need to see the form first.) I'm pretty new to Django, can somebody pls help me with this!!! Thanks! Below are my files. blog.html file: {% block posts %} <div> <span>New Post: </span> <form method="post" action="{% url 'posts' %}" enctype="multipart/form-data"> {% csrf_token %} <table> {{form}} <!--not showing in UI--> </table> <input id="id_post_button" type="submit" value="Submit" /><br> </form> <div> {% endblock %} urls.py urlpatterns = [ path('posts', views.post_action, name='posts'), path('post/<int:id>', views.get_post, name='post'), ] Models.py class PostModel(models.Model): user_id = models.IntegerField() post_input_text = models.CharField(max_length=100) post_profile = models.CharField(max_length=30) post_date_time = models.DateTimeField(default=timezone.now) def __str__(self): return 'id=' + str(self.user_id) + ", post_date_time=" + self.post_date_time + ", post_input_text=" + self.post_input_text + ", post_profile=" + self.post_profile Views.py: @login_required def post_action(request): print("----post action---") context … -
Django: encounter an OperationalError when migrate
I encountered this error when deployed my code on a ubuntu server. I have tested the migration locally (macOS Mojave) and made no mistakes. I tried to delete all migration files except the __intit__.py, but Django gave the same error. The error traceback (home is the name of my app): Applying home.0001_initial...Traceback (most recent call last): File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 381, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such column: REFERRING.S The above exception was the direct cause of the following exception: 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 "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 247, in apply_migration migration_recorded = True File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 34, in __exit__ self.connection.check_constraints() File "/home/admin/sites/site1/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", … -
Bulk create a primary object and objects referencing the primary object at the same time?
class Profile(models.Model): pass class Experience(models.Model): profile = models.ForeignKey(Profile) How would I save a a Profile along with a list of Experiences with a single transaction? Right now I'm doing the following p = Profile() p.save() e_list = [Experience(profile=p), Experience(profile=p)] Education.objects.bulk_create(e_list) Which is two database hits, can I do it in one? -
Refactor try and Except codeblocks in Python
Currently my app is working with several external APIs, and those functions can raise some kind of error, and I would like to be aware of all kind of situations and don't crash my app. In the following piece of code you can see my function, using slack api (it's just an example, not real example), and you can see how I'm creating a space giving the name and the emails. That function can returns several errors, like APIerror, TypeError... etc etc Also you can see, all the functions in that file, can raise some errors so it is using try and except and try to don't break our app. In the except part, I don't want to do anything special, just return the error or I don't know, raise an custom error. In the future would be cool if I can enqueue that task if something goes wrong. slack_client.py def create_space(): try: slack_api.create.space(spaceName='space name', email=emails) except (...): ... def delete_space(): try: slack_api.delete.space(spaceId=space_id) except (...): ... I would like to refactor the try and except part, because I don't want to copy and paste try and except during all my slack_client class, but in case the connection is down, or … -
Django referencing foreignkeys on updates
I just started recently learning Django but stumbled upon the situation that I use update_or_create Demo_user_sessions.objects.update_or_create(session=params['session'][0], defaults=item) however the object item contains one key that is being used as ForeignKey. Currently, I define the key with item[entry] = Demo_user_sessions.objects.get(session=params['session'][0]) This however doesnt work. So my question how do I have to change the create_update call or the key so that the reference to the foreign key works? -
Retrieving all the Json records from a Django Rest Framework endpoint using Jquery
I'm using Jquery to get JSON data from a DRF API endpoint. Here is how i fetch the data: $.getJSON('http://127.0.0.1:8000/tst/', function(data) { console.log(data) }); This is what i'll get in my console: count: 742, which is true, since there are 742 records in total; the problem is that the console.log() statement will give me only the first 50 records; same for any other operation: i'm only able to work with the first 50 records retrieved from the endpoint. Here is what my data looks like: "results": [ { "item": "First", "id": "1847" .. }, { "item": "Second", "id": "4442" ..}, { "item": "Third", "id": "3847" ..}, // 739 more records here ] And here is how i created the endpoint: view class tstList(generics.ListCreateAPIView): queryset = tst.objects.all() serializer_class = tstSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('item', 'id' ) And here is my serializer: class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('item', 'id') def create(self, validated_data): return tst.objects.create(**validated_data) What is happening here? Is the problem on my backend, or is it with Jquery? Any advice is appreciated -
Displaying results for items that have value in one of the field in the table
Is there a way to display content based on th value in the table field? Lets say that I have a field in my table called label, which isnt obligatory to fill in, can I filter the content based on if that field is populated for specific item? Item that has that field populated would be displayed and item with that field left blank wouldnt. model.py: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ManyToManyField(Category, blank=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() image = models.ImageField() views.py: def HomeView(request): item_list = Item.objects.all() context = { 'item_list': item_list, } return render(request, "home.html", context) -
django : 'LoginForm' object has no attribute 'cleaned_data'
I'm trying to make a Login but it doesn't work. the error is form.is_valid() return False and 'LoginForm' object has no attribute 'cleaned_data' I can't figure out out is the problem. user/forms.py class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput( attrs={'style': 'width:100%; height:100%;'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'style': 'width:100%; height:100%;'})) def __init__(self, request=None, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) self.fields['email'].label = "이메일" self.fields['password'].label = "비밀번호" def clean(self): super().clean() email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") try: user = models.User.objects.get(email=email) if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError( "비밀번호가 틀렸습니다.")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError( "존재하지 않는 계정입니다.")) users/views.py class LoginView(mixins.LoggedOutOnlyView, View): def get(self, request): form = forms.LoginForm(request.POST) return render(request, "users/login.html", {"form": form}) def post(self, request): form = forms.LoginForm(request.POST or None) print(form.is_valid()) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") get_user_name = user_models.User.objects.get(email=email) user = authenticate( request, username=get_user_name, password=password) if user is not None: login(request, user) return redirect(reverse("cores:home")) else: return render(request, "users/login.html", {"form": form}) -
installing virtual environment in windows 10
I was trying to install a virtual environment in windows and I am getting the following error message. I tried googling it but wasn't much of any help. -
How to pass Current user to Django_filters ModelChoiceFilterField queryset
How to pass Current user to Django_filters ModelChoiceFilterField queryset. I'm trying to filter the ModelChoiceFilterField based on the current user , i've used the init method in the filter but it failed: here is the code I've used : views.py def requests_reports(request): f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user), user=request.user) context = { 'filter': f, } return render(request, 'requests_reports.html', context) forms.py class RequestsFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(RequestsFilter, self).__init__(*args, **kwargs) self.fields['employee'].queryset = Employee.objects.filter(user=self.user) start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'})) end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'})) class Meta: model = LeaveRequest fields = ['employee', 'type'] It returns this error : 'RequestsFilter' object has no attribute 'fields' -
Is this DJango code snippet correctly retrieving data from the database?
I am having some issues with DJango. Currently, our website does not display all the options in the drop-down menu. It just shows one element that is not appropriate functionality trying to fix My suspicion is that the JQuery is not correctly retrieving the data. I was taking a look at the HTML file, and at line 42 is where the DJango code loops through the entity books, in order to retrieve the book id attribute that we want to display in the drop-down menu. I am new to DJango, and I am not sure if those lines(42-45) are correctly executing. Thank you very much. HTML file containing lines 42-45 -
Getting elasticsearch error while running the project
I am getting the following error when i am runnung the project.I am not getting the data from db otherwise every page is rendering. Failed to query Elasticsearch using 'status:(*"Live"*)': ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fd094b57ba8>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fd094b57ba8>: Failed to establish a new connection: [Errno 111] Connection refused) Traceback (most recent call last): File "/home/manas/Desktop/jobs/venv/lib/python3.6/site-packages/urllib3/connection.py", line 157, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "/home/manas/Desktop/jobs/venv/lib/python3.6/site-packages/urllib3/util/connection.py", line 84, in create_connection raise err File "/home/manas/Desktop/jobs/venv/lib/python3.6/site-packages/urllib3/util/connection.py", line 74, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused -
Unable to get image data in an API request along with json data for registration
I want to create a register API in which I have username,email, password input along with an image field.I am unable to receive and process the data properly.The default user class is extended to store image field. I have this extended user model:- from django.contrib.auth.models import User import os def get_upload_path(instance, filename): fileName, fileExtension = os.path.splitext(filename) return os.path.join("user_%s" % instance.user.username,"user_{0}.{1}" .format(instance.user.username,fileExtension)) # Create your models here. class Userprofile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) display_picture=models.ImageField(upload_to=get_upload_path) has_voted=models.BooleanField(default=False) voted_item=models.CharField(max_length=200,default='none') def __str__(self): return self.user.username These are the serializers:- from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User class UserprofileSerializer(serializers.ModelSerializer): display_picture = serializers.ImageField(required=True) def create(self, validated_data): user = Userprofile.objects.create(validated_data['display_picture']) return user class Meta: model=Userprofile fields=['display_picture'] class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(min_length=8,required=True) def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class Meta: model = User fields = ('username', 'email', 'password') this is the path/url:- path('register',views.FileUploadView.as_view(),name='Register'), View:- @method_decorator(csrf_exempt,name='dispatch') @parser_classes((MultiPartParser,FormParser)) class FileUploadView(APIView): def post(self, request): display_picture=request.FILES['display_picture'] #print(display_picture) serializer = UserSerializer(data=json.loads(request.data['data'])) serializers2=UserprofileSerializer(data=display_picture) print(str(serializer.is_valid()) +" and "+ str(serializers2.is_valid())) if serializer.is_valid() and serializers2.is_valid(): serializer.save() serializers2.save() return JsonResponse({'message': "Registered Successfully!"},status=201) return JsonResponse(serializer.errors,status=400) In the view, serializers2.is_valid() is false.So, unable to save the image data. -
How to connect Django database to Sql server?
I hope you are doing well. I have recently started learning django and it has been going great. However, there is a problem I am facing. I am having difficulties to connect it to the Sql database. I have read some of the previous threads and most of the people were suggesting to use "pyodbc" as a library. However, it appears that this library is not compatible with the new versions of python and django. After filling in the database information, I am getting the following error: django.core.exceptions.ImproperlyConfigured: Django 3.0.3 is not supported. I have tried a combination of different python, django, pyodbc, django-pyodbc-azure versions but none of them seems to be working. Moreover, when I run the code in the terminal it works and connect to the database. Hence, I wanted to know whether there is a workaround this problem? Or am I missing something obvious? DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxxxx', 'HOST': '111.111.1.111', 'USER': 'abc', 'PASSWORD': "bca", 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', #'driver': 'SQL Server', 'unicode_results': True, }, }, } Your help would be greatly appreciated! -
how to catch the exceptions from class method?
I have a class with method POST which contains exception class CsvToDatabase(APIView): def post(self, request, format=None): data = request.data for key, vendor in data.items(): v = Vendors( vendor_name=vendor['Vendor'], country=vendor['Country'], nda=vendor['NDA date'], ) try: v.full_clean() except ValidationError as e: data = json.dumps({'status': str(e)}) return Response(data, content_type='application/json') v.save() When the full_clean() method is triggered the clean() method of model is running. class Vendors(models.Model): # model fields def clean(self): if self.country not in [x[1] for x in countries]: raise ValidationError(detail="Country name does not match to the country list ") And finally I get a response "Country name does not match to the country list" from models, how to get as a response data from except block of class? -
Django Generic Foreign key filter by object nested field
I have a model with Generic Relationship in Django. class GenericModelDemo(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(blank=False) content_object = generic.GenericForeignKey('content_type', 'object_id') comment = models.TextField() The generic model being referered is like class ChildModel(models.Model): user = models.ForeignKey(User) data = generic.GenericRelation(GenericModelDemo) I want to filter records from GenericModelData based on the user__email from the ChildModel. Example objects = GenericModelDemo.filter(childmodel__user__email='email@example.com') I searched for how to achieve this but all answers are filtering based on the object_id like content_type = ContentType.objects.get_for_model(ChildModel) GenericModelDemo.objects.filter(content_type=content_type, object_id=child.id) But, this does not resolves my query. How can I filter using the generic foreign key fields instead of just id? -
how to implement ModelChoiceField in Django
I am trying to create an input selection from database model fields and I have tried using ModelChoiceField but I keep getting an error I don't know how to solve. I need help. Here are the models class WeeklySavingsDeposit(models.Model): WEEKLY_SAVE_DEPOSIT_STATUS_PENDING = 'Pending' WEEKLY_SAVE_DEPOSIT_STATUS_APPROVED = 'Approved' WEEKLY_SAVE_DEPOSIT_STATUS_DENIED = 'Denied' WEEKLY_SAVE_DEPOSIT_STATUS_CHOICES = ((WEEKLY_SAVE_DEPOSIT_STATUS_PENDING, 'Pending'), (WEEKLY_SAVE_DEPOSIT_STATUS_APPROVED, 'Approved'), (WEEKLY_SAVE_DEPOSIT_STATUS_DENIED, 'Denied')) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(default=timezone.now) savings_title = models.CharField(max_length=100, null = True, blank=True) amount = models.FloatField() dep_proof = models.ImageField(upload_to='deposit_proofs') status = models.CharField(max_length = 40, choices = WEEKLY_SAVE_DEPOSIT_STATUS_CHOICES, default='Pending') dep_tag = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} WeeklySaveDeposit' class WeeklySaving(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) title = models.CharField(max_length = 100, default = 'Weekly Savings Title') duration = models.CharField(max_length=40, choices=WEEKLY_SAVE_DURATION_CHOICES, default ='2 Months') completion_date = models.DateTimeField(null=True) amount = models.FloatField() target_amount = models.FloatField(null=True) status = models.CharField(max_length= 40,choices = WEEKLY_SAVE_STATUS_CHOICES, default='Pending') week_save_day = models.CharField(max_length =100, choices=WEEKLY_SAVE_DAY_CHOICES, default='Friday') amount_saved = models.FloatField() My Forms. class StartWeeklySaveForm(forms.ModelForm): title = forms.CharField(label = 'Savings Title', required=True) amount = forms.FloatField(label='Amount to Save Weekly? (in Naira):', min_value=WeeklySaving.MIN_WEEKLY_SAVE, max_value=WeeklySaving.MAX_WEEKLY_SAVE, required=True, widget=forms.TextInput(attrs={'placeholder': 'Input the amount you want to save weekly. Minimum 500'})) class Meta: model = WeeklySaving fields = ["title", "amount", "duration", "week_save_day"] class DepositWeeklySaveForm(forms.ModelForm): amount = forms.FloatField(label='Enter Amount in (Naira)', min_value=WeeklySaving.MIN_WEEKLY_SAVE, max_value=WeeklySaving.MAX_WEEKLY_SAVE, required=True, help_text='How … -
Django : How to make a login form and views?
I'm trying to make a Login but it doesn't work. more specifically, "HI WORLD" doesn't print out and "step1" is print out. "step2" doens't not print out I can't figure out out is the problem. user/forms.py class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput( attrs={'style': 'width:100%; height:100%;'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'style': 'width:100%; height:100%;'})) def __init__(self, request=None, *args, **kwargs): self.request = request super(LoginForm, self).__init__(*args, **kwargs) self.fields['email'].label = "이메일" self.fields['password'].label = "비밀번호" def clean(self): print("HI WORLD") email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") try: user = models.User.objects.get(email=email) if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError( "비밀번호가 틀렸습니다.")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError( "존재하지 않는 계정입니다.")) users/views.py class LoginView(mixins.LoggedOutOnlyView, View): def get(self, request): form = forms.LoginForm() return render(request, "users/login.html", {"form": form}) def post(self, request): form = forms.LoginForm(request.POST) print("step1") if form.is_valid(): print("step2") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") get_user_name = user_models.User.objects.get(email=email) user = authenticate( request, username=get_user_name, password=password) if user is not None: login(request, user) return redirect(reverse("cores:home")) else: return render(request, "users/login.html", {"form": form}) -
How to update objects from a model that has a OneToOneField with the User model in Django?
I have a Clients model connected to the Django's User model using a OneToOneField. (see below). I have a form that creates an object in Clients while creating a new user at the same time. Now, I want a form where the Client can update the first_name, last_name, email, mobile, and nif. Because first_name, last_name, and email belong to the User model and the rest to the Clients model, how can I create this form? This is what I have now: models.py class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) avatar = models.ImageField(null=True) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Clients.objects.create(user=instance) instance.clients.save() forms.py class UpdateClient(ModelForm): address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control'})) nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'})) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'})) def clean_nif(self): nif = self.cleaned_data['nif']; if Clients.objects.filter(nif=nif).exists(): raise forms.ValidationError("NIF já existente.") return nif def __init__(self, *args, **kwargs): super(UpdateClient, self).__init__(*args, **kwargs) self.fields['first_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['last_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['email'].widget = EmailInput(attrs={'class': 'form-control'}) class Meta: model = User fields = ('email','first_name','last_name', 'address', 'nif', 'mobile') And my views.py … -
How can i create an autocomplete with Jquery?
I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier. My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays. Here is what i have now: <script> $(document).ready(function(){ // Defining the local dataset $.getJSON('http://127.0.0.1:8000/myapi/', function(data) { console.log(data) //Autocomplete }); }); </script> <input type="text" id='firstfield' name='input_val'> This is what the data looks like, it's around 700 records; here are the first three: "results": [ { "item": "First", "id": "1847", }, { "item": "Second", "id": "4442", }, { "item": "Third", "id": "3847", }] I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance! -
How create a package with a valid command to Django?
I'm creating a package for Django, and I want create a command to install then. Install are suppose to run with python manage.py install_my_package, is this possible? my package is like this: django-my-package |-- __init__.py |-- MANIFEST.in |-- README.rst |-- LICENSE |-- setup.py |-- test_settings.py |-- my_package | |-- __init__.py | |-- models.py | |-- apps.py | |-- my_package.py | |-- management | |-- commands | |-- install_my_package.py On my install, I need migrate a simple table on my models.py file to db, and create a directory at root of Django project that called my package. -
django.urls.exceptions.NoReverseMatch: Reverse for 'account_email' not found. 'account_email' is not a valid view function or pattern name
when i use allauth,and allauth.account then this error occurs. django.urls.exceptions.NoReverseMatch: Reverse for 'account_email' not found. 'account_email' is not a valid view function or pattern name. -
Optimise Django query
I have a model in my Django project class AmazonSearchFrequency(models.Model): keyword_name = models.CharField(max_length=500) frequency = models.PositiveIntegerField(default=0) I am storing around 2 milion data in this table but whenever I do a search query like AmazonSearchFrequency.objects.filter(keyword_name=keyword) take a long time to execute the query. Is that anyway in Django where I can optimize this query.