Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need way to know when my Django Model instances are queried
I am trying to add a Framework to my Django Models that will allow for my model instances to Expire. I will have a timed task that will walk through the expirable Models and delete the expired instances. I have different types of expirations that I want to do. The first one is a basic TimeDeltaExpiry which will expire the instances after a timedelta from the time the instance was last Saved. The expiry gets updated when the instance is saved. def save(self, *args, **kwargs): self.expiry = self.expiry.datetime + timedelta(minutes=2) super(TimeDeltaExpiry, self).save() The second one is a RefreshableTimeDeltaExpiry that should have the expiry updated every time the instance gets queried. Not sure if this is even possible, but I was looking for a method or feature that would allow me to capture when the instance is referenced. There also is the concern that when my purging task runs, that it would also be referencing the instance and update the expiry, which I of course would not want to have happen. Is there a technique that might allow me to do what I want? Here is my untested code so far class ExpiryManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( expired=ExpressionWrapper(Q(expiry__lt=Now()), output_field=BooleanField()) ) class … -
Django throws an error: class UserinLine(admin.StackedInLine) AttributeError 'User' object has no attribute 'StackedInLine when copying to production
I have it working on pyhcarm, running django 2.2.10. Once I moved it /var/www folder. And run via apache2, I am getting that error Django throws an error. Why its happening on production? Not when I run it via pycharm, did sthg happen when copying the folders? My Python version is 3.6.9 -
Accessing foreign key viewflows
im attempting to access a foreign key within flows.py but am facing an error : 'NoneType' object has no attribute 'approved' Here is the relevant parts of my code: flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess #process starts here start = flow.Start( CreateProcessView, fields=["payment_code", "bPBankAccount"], task_title="New payment voucher" ).Permission( auto_create=True ).Next(this.preparer) preparer = flow.View( PreparerSignature ).Next(this.check_preparer) check_preparer = flow.If( cond=lambda act: act.process.approved_preparer.approved ).Then(this.verifier).Else(this.end) #there is more to the code but i am leaving it out as it is not relevant models.py class PaymentVoucherProcess(Process): payment_code = models.CharField(max_length=250,default='100-200-121') bPBankAccount = models.ForeignKey('BPBankAccount', on_delete=models.CASCADE) approved_preparer = models.ForeignKey('PreparerSignatureModel' , on_delete=models.CASCADE , null=True) drop_status = models.CharField( null=True, max_length=3, default=None, choices=(('SCF', 'Successful'), ('ERR', 'Unsuccessful')) ) remarks = models.TextField(null=True) class PreparerSignatureModel(JSignatureFieldsMixin): name = models.ForeignKey(User,on_delete=models.CASCADE) approved = models.BooleanField(default=False) As seen from the error code , it seems that i am unable to access the foreignkey using : act.process.approved_preparer.approved Is there a way i can access a foreignkey within flows.py? -
Client doesn't receive data in Django Channels
I created a Django channels consumer that, once the connection is open, should establish a connection to an external service, retrieve some data from this service and send the data to my frontend. Here is what i tried: import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer from binance.client import Client import json from binance.websockets import BinanceSocketManager import time import asyncio client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', self.process_message) bm.start() def process_message(self, message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] self.send(Rate) print(Rate) When the connection is started, the consumer starts receiving data and the print statement works, meaning that i see the data appearing on my console, but the data doesn't arrive to my frontend, which means that self.send(Rate) doesn't work. Here is the only thing that i see when i open my frontend: MessageEvent {isTrusted: true, data: ""test"", origin: "ws://127.0.0.1:8000", lastEventId: "", source: null, …} Can someone help me fix this issue? Why is the data appearing on my django command line but it doesn't arrive to the frontend? -
django doesn't display form errors in template
When I try to test my form with an field is not alpha doesn't display form errors in template. my form validation: def clean_eta(self): eta = self.cleaned_data['eta'] if not eta.isalpha(): raise forms.ValidationError( 'Questo campo può contenere solo lettere') return eta my views: def pubblica_annunci(request): if request.method == "POST": form = AnnunciForm(request.POST, request.FILES) if form.is_valid(): annunci = form.save(commit=False) annunci.eta = form.cleaned_data['eta'] print(annunci.eta) annunci.user = request.user annunci.save() messages.success(request, 'Ottimo, Abbiamo ricevuto il tuo annuncio, questo sarà esaminato dallo staff e ' 'pubblicato nel minor tempo possibile.', extra_tags='alert alert-success alert-dismissible fade show') return redirect('pubblica_annunci') else: messages.error(request, 'La preghiamo di compilare tutti i campi correttamente e riprovare.', extra_tags='alert alert-danger alert-dismissible fade show') return redirect('pubblica_annunci') else: form = AnnunciForm() context = {'form': form} return render(request, 'annunci/pubblica_annunci.html', context) template: {{ form.eta.errors }} -
Integrity error when creating a user in django
I want my admin to be able to login and create users on my Django app, but each time I try to create a user I get this error message IntegrityError at /backoffice/add-exco/ (1062, "Duplicate entry '1' for key 'user_id'") The approach I used was to extend the User model using a one-to-one link. I also saw a post on stackoverflow suggesting how to solve this by doing the following Change your OneToOneField to a ForeignKey In your form validation make sure that a record does not exist When creating the form check if an entry already exists and then allow the user to edit it. I do not know how to go abt 2, 3 is there a better approach? Below is my code on models.py class AdditionalProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) mobile1 = models.CharField(max_length=15) mobile2 = models.CharField(max_length=15, blank=True, null=True) occupation = models.CharField(max_length=5, choices=OCCUPATION_FIELD, default=CHOOSE) job_cader = models.CharField(max_length=5, choices=JOB_CADER, default=CHOOSE_JOB) profile = models.ImageField(blank=True, null=True, upload_to='backend/') def __str__(self): return self.user.username on forms.py class RegisterForm(UserCreationForm): class Meta(): model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return … -
Automatically create a token for admin in Django
I am looking for a method to create, automatically, a token with rest_framework.authtoken.models.Token when admin logins into admin panel. I can set-up it manually by adding the Token, but I would prefer to have it automatically created at login and destroyed at logout. -
django rest framework token authorization
I'm doing tutorial and I have a problem with access to data with authorization token. I changed in my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), I generate users and tokens for them, if I try GET, response is {"detail":"Authentication credentials were not provided."}curl: (6) Could not resolve host: Token curl: (6) Could not resolve host: e7e9047a515b141209ace33597b53771ef8f5483' i used commad: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' from https://riptutorial.com/django-rest-framework/example/28222/using-curl of course with my token and address If I change 'rest_framework.permissions.IsAuthenticated' to 'rest_framework.permissions.AllowAny' and use curl -X GET http://127.0.0.1:8000/api/v1/friends/there are no problems, I'm getting json form database. I don't know what i'm doing wrong :( -
How to change a label of AuthenticationForm called in the LoginView and how to use another form in LoginView ? (Django 3.0)
I'm learning Django 3.0 and I'm actually using the django.contrib.auth.views.LoginView Here is my views.py file: from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): template_name = "blog/loginview.html" And here is my urls.py file: from django.contrib.auth.views import LoginView from django.conf.urls import url urlpattenrs = [ url(r'^login/$', views.CustomLoginView.as_view(), name='login') ] I know I could put everything in the url without making my own view but I wanted to test it. Here is my template: <h1>Connection with LoginView</h1> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}" /> <input type="submit" value="Connect" /> </form> Everything works perfectly, but on my page, I can see the default labels from the AuthenticationForm used by default by the LoginView. These are Username: and Password:. Now here are my questions: Is it possible to change the labels to foo instead of Username: and bar instead of Password: from the template and keep the {{ form.as_p }} in the template? Or even better, changing the labels from the CustomLoginView ? Is it possible to use a custom form for the CustomLoginView ? Or even better, directly in the LoginView ? Thank you for your help. -
Django - map an argument to model
I'm sorry if this is a noob question. I'm new to this and even though I believe it is a simple problem I can't seem to find the right terms for googling. I have a several types of devices. Since they have notably different characteristics, I cannot accommodate them into one model. So I have separate models for each device type. I also have a table (model) of device types, i.e. a simple table which lists all available types. Each device a memeber called device type which is a foreign key to this table. Minimal example: from django.db import models class DeviceType(models.Model): device_type = models.CharField(max_length=30) class Foo(models.Model): memeber_a = models.CharField(max_length=30) memeber_b = models.CharField(max_length=30) device_type = models.ForeignKey(DeviceType, on_delete=models.PROTECT) class Bar(models.Model): memeber_a = models.URLField() memeber_b = models.URLField() memeber_c = models.CharField(max_length=30) device_type = models.ForeignKey(DeviceType, on_delete=models.PROTECT) I also added a simple view which lists all available types by querying the DeviceType model. Now I wish that upon clicking on each type (they are links), a page would open, listing all devices of this type. It is a simple matter to send the correct DeviceType.id within the view I have. However, new I have a view which receives the id as an argument, and needs … -
How to use post_save and use instance.save inside post_save without call post_save signal again?
I'm using a signal to change the uploaded file and do some process to convert the .mkv|mp4 file into .m3u8 and .ts files, but when i save the instance using new .m3u8 file created in the signal, the instance.save method call the signal again, and this raise a error. Code example: @receiver(post_save, sender=Lecture) def handle_video_upload(sender, instance, created, **kwargs): # check if a new video has uploaded file_has_changed = instance.tracker.has_changed('file') if created or file_has_changed and instance.file_type == "V": # .../ process to convert video into a .m3u8 file... # open the m3u8 created file and change the original (mp4, mkv...) file for the m3u8 with open(m3u8_absolute_path, "r") as file_object: file_m3u8 = File(name=m3u8_absolute_path, file=file_object) instance.file.save(m3u8_filename, file_m3u8) # this call this signal again and raise a error the file field is: file = models.FileField() -
Pass instance field to function as parameter
I have this code which generates slug for django models. I have a different model field which is passed to function for generating it from (for example- name, title) I marked variable name by naming it HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION How do I pass this "title", "name" fields that so this function will work for any field name I pass it to. # utils.py DONT_USE = ['create'] def random_string_generator( size=2, chars=string.ascii_lowercase + string.digits ): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION, new_slug=None): if new_slug is not None: slug = new_slug else: slug = slugify(instance.HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = f"{slug}-{random_string_generator(size=4)}" return unique_slug_generator(instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION, new_slug=new_slug) return slug I will use that function here # models.py class Category(models.Model): name = models.CharField(max_length=64) slug = models.SlugField(unique=True, blank=True) class Event(models.Model): title = models.CharField(max_length=128) slug = models.SlugField(unique=True, blank=True) def event_slug_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator( instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION="title" ) def category_slug_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator( instance, HELP_HERE_INSTANCE_FIELD_PASS_TO_FUNCTION="name" ) -
Word or pdf file from own website to csv file
I want to save a word or pdf file in csv to my database in django. I have searched for youtube videos but couldn't find any. Please help -
How to upload django website (basic HTML) onto Heroku without using Git/GitHub AT ALL?
Is this possible? I've read other threads but they do not answer the question and are deprecated besides. I have made my django project's website in PyCharm and I want to now host it on Heroku so I can give people a hyperlink to go to a basic HTML website instead of http://127.0.0.1:8000/ (which will eventually host my app which is already built). Any help would be appreciated. Ideally I would like a step-by-step SIMPLE guide for porting pycharm django html code into heroku or some other easier hosting website if some such hosting service exists. -
Hello, I'm trying to install channels but it's not installing because It is finding it hard to install twisted, what can I do?
I'm trying to install channels but it's not installing because It is finding it hard to install twisted, what can I do? it brings this error and stops. How can I go about this? copying src\twisted\internet\test\fake_CAs\chain.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\not-a-certificate -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\thing1.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\thing2-duplicate.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\internet\test\fake_CAs\thing2.pem -> build\lib.win-amd64-3.8\twisted\internet\test\fake_CAs copying src\twisted\mail\test\rfc822.message -> build\lib.win-amd64-3.8\twisted\mail\test copying src\twisted\python\test\_deprecatetests.py.3only -> build\lib.win-amd64-3.8\twisted\python\test copying src\twisted\trial\test\_assertiontests.py.3only -> build\lib.win-amd64-3.8\twisted\trial\test copying src\twisted\words\im\instancemessenger.glade -> build\lib.win-amd64-3.8\twisted\words\im copying src\twisted\words\xish\xpathparser.g -> build\lib.win-amd64-3.8\twisted\words\xish running build_ext building 'twisted.test.raiser' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\sirto\Anaconda3\envs\feb2020\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\sirto\\AppData\\Local\\Temp\\pip-install-jb1hixq_\\twisted\\setup.py'"'"'; __file__='"'"'C:\\Users\\sirto\\AppData\\Local\\Temp\\pip-install-jb1hixq_\\twisted\\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\sirto\AppData\Local\Temp\pip-record-bqr18jdh\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\sirto\Anaconda3\envs\feb2020\Include\twisted' Check the logs for full command output.` -
Force model fields in Django
When creating model in Django for example something like this: class Musician(models.Model): first_name = models.CharField(max_length=50, primary_key = True) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) I noticed some problem (not sure if that's best word) with this approach. There is nothing preventing you from creating something like: musician = Musician() musician.save() effectively having primary_key value equal to None. I would like to force user to set first_name, but frankly speaking I cannot find any simple solution for that. Is there a way to achieve this? -
How to access jinja variables of dictionary which is rendered through ajax call in Django
t.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset=\"utf-8"\> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Title</title> </head> <body> <form method="post"> <textarea id="t1" name="editor">{{c}}</textarea> <br> <button type="button" id="b1" onclick="calling();">press</button> </form> **{{c}}** **{{b}}** <script type="text/javascript"> function calling(){ $.ajax({ type:'POST', url: "{% url 'test' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(){ alert("Hello"); }, error: function(){ alert("sorry"); } }); } </script> </body> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </html> I want value in {{c}} after ajax call. tview.py: from django.shortcuts import render def home(request): return render(request, 't.html') def test_view(request): print("hello") c = 2+3 dict1 = {'c': c, 'b': 'hey'} return render(request, 't.html', dict1) urls.py: from django.conf.urls import url from . import tview urlpatterns = [ url(r'^$', tview.home), url(r'^test', tview.test_view, name='test') ] enter image description here And when i press button ajax call is successfully made and did show a dictionary content on a chrome developer tools at response preview but not showing in main front page. This is the image. -
django Many to Many fildes
i want to add in only one user from Available classic to Chosen classic but not from admin page from view when user click on button I tried this pro = Profile(user=request.user) pro.classic.add(name='Frank Sinatra-i love you baby') but i get tthis error -
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `CitySerializers`
AttributeError: Got AttributeError when attempting to get a value for field name on serializer CitySerializers. -
What to choose Class Based Views or Function Based Views?
I really want know is that bad if someone know only one method from the above two ? i mean just working on something like class based views and not much in functions based views is a bad sign for getting hire in company. By the way i worked on both of them but i really like how quick class based views are and helps to avoid repeatation of code. Also, the best part in class based views i find is during testing. That's the biggest reason why i like class based views more. But seriously i dont know how knowing only one of the two can affect getting me hired or something. As i dont know what developers like to work on more. Love to know your opinions guys please suggest. -
hosting Django application on Apache
I'm following a tutorial on hosting Django application on Apache, and I'm new to these types of server error. I modified the apache config file to communicate with the wsgi of my application using the following code: LoadModule wsgi_module "c:/users/adwy/appdata/local/programs/python/python35/lib/site-packages/mod_wsgi/server/mod_wsgi.cp35-win_amd64.pyd" WSGIScriptAlias / "D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app/wsgi.py" WSGIPythonHome "C:/Users/Adwy/AppData/Local/Programs/Python/Python35" WSGIPythonPath "D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app" Alias /static/ C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin\static Alias /templates/ C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin/templates <Directory C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin/static> Require all granted </Directory> <Directory C:/Users/Adwy/Adwy/Django_ Learning_ 1/Lib/site-packages/django/contrib/admin/templates> Require all granted </Directory> <Directory "D:/Backup/Learning Python/Organized and important file/Learning files and sheets/Django_ Learning_ 1/weblog_app/weblog_app"> <Files wsgi.py> Require all granted </Files> </Directory> -- Now I restarted my apache server, and run the Django server in parallel, I get Error 500, here I copy below the logs of the Error from the Apache server: [Sat Apr 04 18:41:05.681919 2020] [wsgi:warn] [pid 8608:tid 288] (70008)Partial results are valid but processing is incomplete: mod_wsgi (pid=8608): Unable to stat Python home C:/Users/Adwy/AppData/Local/Programs/Python/Python35. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. [Sat Apr 04 18:41:05.725921 2020] [mpm_winnt:notice] [pid 8608:tid 288] AH00354: Child: Starting 150 … -
Trying to implement a read more button that is specific to Django model attribute
So I've had success in creating a 'read more' that displays more information on a music artist and the button appears under each artist on my page. The button displays the bands bio which is taken from a Django model that holds the bio information in my database. The button works for the first artist on the page but when I click the button under the other artists on the page, it still only displays the bio for the first band (the one at the top of the page). How do I make it so that the button displays the information of each specific band? Here is my html code <p><span id="dots">...</span><span id="more">{{ artist.bio }}</span></p> <button onclick="myFunction()" id="readmore">Show more on this artist</button> Here is my css code p { font-size: 18px; margin-left: 40px; margin-right: 40px; } #readmore { font-size: 18px; color: darkgrey; margin-left: 40px; margin-right: 40px; } #more { display: none; } Here is my java function myFunction() { var dots = document.getElementById("dots"); var moreText = document.getElementById("more"); var btnText = document.getElementById("readmore"); if (dots.style.display === "none") { dots.style.display = "inline"; btnText.innerHTML = "Show more on this artist"; moreText.style.display = "none"; } else { dots.style.display = "none"; btnText.innerHTML = "Hide information on … -
Date Picker inside the Form is not showing up
forms.py Here in forms.py i have written the form perfectly but can't find the problem from bootstrap_datepicker_plus import DatePickerInput,DateTimePickerInput class SchedulAuctionForm(forms.ModelForm): # auction_start_date=forms.DateTimeField(widget=DateTimePickerInput()) # auction_end_date = forms.DateTimeField(widget=DateTimePickerInput()) class Meta(): fields=('auction_start_date','auction_end_date') model = models.CurrentAuction widgets = { 'auction_start_date': DateTimePickerInput(), 'auction_end_date': DateTimePickerInput(), } views.py class AuctionScheduling(UpdateView): model = models.CurrentAuction template_name = 'auctions/admin/auction_scheduler.html' form_class = forms.SchedulAuctionForm success_url = reverse_lazy('home') def form_valid(self, form): prop = get_object_or_404(models.PropertyReg,pk=self.kwargs.get('pk')) prop = form.cleaned_data['something'] prop.save() return super().form_valid(form) auction_scheduler.html {%extends 'auctions/admin/admin_base.html'%} {%load static%} {%load bootstrap4%} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% include "bootstrap_datepicker_plus/input.html" %} {%block heading%} <br/> <br/> <br/> <center><h1 id="scroll">Auction Schedule</h1></center> <br/> {%endblock%} {%block content%} {{ form.media }} <br/> <div class="container"> <form method="post"> {%csrf_token%} {%bootstrap_form form%} <input type="submit" value="Schedule This" class="btn btn-danger"> </form> </div> <br/> {%endblock%} enter image description here As You can see in the image picker is not showing up at all -
How can i train model and then use in my django project to classify text getting from scrapper?
I am making a web scrapper which scrap news from url save into database after classification. Im using django and python for web and mongoDB as an database. -
Django serializer with a filed that has a OneToOne relationship
In my project I have two 'types' of users: Customers and Businesses. They are an extension of the django base User from django.contrib.auth.models.User. I have in my models.py: class Customer(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) birth_date = models.DateField(blank=True, null=True) phone = PhoneNumberField(unique=True) def __str__(self): return self.user.username class Business(models.Model): user = models.OneToOneField(User, related_name='business', on_delete=models.CASCADE) cf = models.CharField(max_length=16, validators=[ssn_validation]) birth_date = models.DateField(null=True) city = models.CharField(max_length=50, blank=False) address = models.CharField(max_length=150, blank=False) Ok, then I have two different registration, one for Customers and one for Businesses. A problem is that, to validate the password, sent from a REST API, I need to compare password with password2, create a User (django base), and pass it to my Customer.objects.create, like: I have in my serializers.py: class CustomerRegistationSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username', validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(source='user.email', validators=[UniqueValidator(queryset=User.objects.all())]) first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') password = serializers.CharField(source='user.password', write_only=True) password2 = serializers.CharField(style={'input_style': 'password'}, write_only=True) birth_date = serializers.CharField(required=False) class Meta: model = Customer fields = ['id', 'username', 'email', 'password', 'password2', 'first_name', 'last_name', 'birth_date', 'phone'] def save(self): username = self.validated_data['user']['username'] password = self.validated_data['user']['password'] password2 = self.validated_data['password2'] email = self.validated_data['user']['email'] first_name = self.validated_data['user']['first_name'] last_name = self.validated_data['user']['last_name'] phone = self.validated_data['phone'] try: birth_date = self.validated_data['birth_date'] except KeyError: birth_date = None if password != password2: raise …