Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rewrite website from PHP YII to Python Django [closed]
Good afternoon. We have a corporate website at work, with a lot of data for a couple of years. It is written in PHP YII, my task now is to rewrite it in Python Django. The database is PosgresSQL, it has data coming in automatically and is generally well designed, so I want to keep it. Bottom line: What's the best way to rewrite the site in python and keep the old database. It turns out I will need to rewrite the models suitable for this database. Maybe there is some methodology for this? -
How to create two docker compose containers on one server
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8a58a0898843 repo.com/test_nginx_dev "..." 3 seconds ago Up 2 seconds 80/tcp, 0.0.0.0:9000->9000/tcp test_nginx_dev a1fzd92a1c9d repo.com/test_django_dev "..." 3 seconds ago Up 2 seconds 8080/tcp, 0.0.0.0:8100->8100/tcp test_django_dev CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7516491ae772 repo.com/test2_nginx_dev "..." 7 seconds ago Up 5 seconds 0.0.0.0:80->80/tcp test2_nginx_dev 59a344089c51 repo.com/test2_django_dev "..." 7 seconds ago Up 6 seconds 8080/tcp test2_django_dev First, test2_nginx_dev and test2_django_dev were created with docker-compose. After that, if I create test_nginx_dev and test_django_dev with docker-compose test2_nginx_dev and test2_django_dev disappear. how do i solve it -
how solve Error when run django app on server of heroku?
i create django app and now i run it on heroku app my procfile and other thing are as follow. but when i build it on heroku then it succesfully uploaded but not run on website. this app is run in localhost is good but not at online hear is procfile web: waitress-server --port=$PORT todoapp.wsgi:application hear is last logs 2022-01-24T07:20:24.200304+00:00 app[api]: Deploy 5e0ae6c8 by user zeelmehta.zm31@gmail.com 2022-01-24T07:20:24.200304+00:00 app[api]: Release v10 created by user zeelmehta.zm31@gmail.com 2022-01-24T07:20:33.000000+00:00 app[api]: Build succeeded 2022-01-24T07:20:40.938065+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=todoapp-zeel.herokuapp.com request_id=81d8bb3e-5f6c-4f37-8be0-90508cebef10 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:41.630709+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=todoapp-zeel.herokuapp.com request_id=87aff06b-aff3-4846-9abc-95b1db51d632 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:55.134817+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=todoapp-zeel.herokuapp.com request_id=9a920057-d443-4404-badd-493951c0c196 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https 2022-01-24T07:20:55.760932+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=todoapp-zeel.herokuapp.com request_id=0f0b6bfc-2181-4eb0-b0af-8e444058b163 fwd="157.32.119.168" dyno= connect= service= status=503 bytes= protocol=https``` please help me to solve this error -
How to change the file name when uploading an image field in Django
When uploading an image field (media file) in Django, it asks about renaming the file. The page url to upload the image contains the pk of the foreign key. I want to rename the image file to {pk}.png when uploading an image. When the code below works, it is saved as none. What's the problem? [urls.py] app_name = 'dataroom' urlpatterns = [ path('det/<int:research_id>/', views.detData, name='DataDet'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) [models.py] import .utils import rename_imagefile_to_uuid class protocol_upload(models.Model): trial = models.ForeignKey(Research, on_delete=models.SET_NULL, blank=True, null=True) protocol_file = models.FileField(upload_to='protocol/', null=True, blank=True) clusion= models.ImageField(upload_to='criteria/clusion/', null=True, blank=True) reference = models.ImageField(upload_to=rename_imagefile_to_uuid, storage=OverwriteStorage(), null=True, blank=True) def image_save(self, *args, **kwargs): if self.id is None: saved_image = self.reference self.reference = None super(protocol_upload, self).save(*args, **kwargs) self.reference = saved_image super(protocol_upload, self).save(*args, **kwargs) def __str__(self): return str(self.trial) [utils.py] import os from uuid import uuid4 def rename_imagefile_to_uuid(instance, filename): upload_to = 'reference/' ext = filename.split('.')[-1] uuid = uuid4().hex if instance: filename = '{}.{}'.format(instance.id, ext) else: filename = '{}.{}'.format(uuid, ext) return os.path.join(upload_to, filename) [views.py] def detData(request, research_id): research = Research.objects.get(id=research_id) protocol = protocol_upload.objects.all() for reference in request.FILES.getlist('reference'): protocol = protocol_upload() protocol.research = research_id protocol.reference = reference protocol.save() context = { 'protocol': protocol, 'research': research, } return render(request, '/detail.html', context) [detai.html] <form method="POST" action="{% url 'dataroom:DataDet' research_id=research.id … -
What is the average cost of hosting a django app?
Due to current RBI guidelines on recurring payments for standing instructions I am unable to use Heroku which is great for small apps. Therefore I have to choose other platoforms. I have narrowed down my choice to two platforms aws and digital ocean. overview of my django website : The website which I made for my client is not that big. In this website a user registers, chooses some plan and then book an intructor to teach him/ her driving. A user after loging in has to accept an agreement and also has an udate plan page. Thats it on the user side. Now I use celery which uses redis, to send emails such as otp, registration successful, change password, contracts and updated contracts (the contracts' email are send both to the client and the user as per the clients demand). As you can see I have to use celery and redis because there is a lot email work that has to be done by the website. And the database i am using is Postgresql. Now comming to traffic, we cannot predict what will be the number of visitors on the site, but we accept maximum of 10 registrations per … -
Displaying the Custom model field in the Post method
I am facing some problems regarding Django-Rest-Framework, post method. There are two things I want to accomplish: Adding fields in the view of the Post method. --> Here instead of sending the data in Json format, I want to replace the filed names with the Custom model's fields And when using '@renderer_classes([BrowsableAPIRenderer])' decorator in a view, the view page shows '[No renderers were found]'. Here are snippets of my code and the screenshots of the errors I got... serializers.py class CreateTodoSerailizer(serializers.ModelSerializer): class Meta: model = Todos fields = ('title', 'user', 'desc', 'todo_date', 'is_completed',) def save(self): todo = Todos( title = self.validated_data['title'], user = self.validated_data['user'], desc = self.validated_data['desc'], todo_date = self.validated_data['todo_date'], is_completed = self.validated_data['is_completed'], ) todo .save() return todo models.py class Todos(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=30) slug = models.SlugField(max_length=50, blank=True) desc = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) todo_date = models.DateField(default=date.today) is_completed = models.BooleanField(default=False) class Meta: verbose_name = _("Todos") verbose_name_plural = _("Todos") ordering = ['-date_created'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(Todos, self).save(*args, **kwargs) views.py @api_view(['POST']) def createTodo(request, format=None): if request.method == 'POST': serializer = CreateTodoSerailizer(data=request.data) data = {} if serializer.is_valid(): todo = serializer.save() data['response'] = 'Successfully added' data['title'] = todo.title data['username'] = todo.user … -
Creating a database using python and Django and populating that database from HubSpot API Data
I am trying to populate the database using HubSpot's Companies API data. I have created a table in models.py. In views.py file I have called API data, however I am not able to save that data in the Database. I do not understand if there an issue in my code or anything else? your help on this task would be really appreciated. views.py def index(request): url = "https://api.hubapi.com/companies/v2/companies?" headers = {} r = requests.get(url = url, headers ={'Authorization':'Bearer %s' %os.getenv('access_token')}) try: response_dict = json.loads(r.content) companies_list= response_dict['companies'] for company in companies_list: Company.update_or_create( companyID = company['companyId'], sourceID = company['sourceId'], portalID = company['portalId'], country = company['country'] ) except Exception as e: response_dict= "Data not found:" return render(request, 'Apihub/index.html', {'response_dict': response_dict} In models class: models.py class Company(models.Model): companyID = models.CharField(max_length=50, blank=True, null=True) sourceID = models.CharField(max_length=20, blank=True, null=True) portalID = models.IntegerField(default=0) country = models.CharField(max_length=50, blank=True, null=True) -
Django forms hidden field value assignation with a var after 'forms.is_valid()' doesn't save it
I have a form with an hidden input called social_color where I want nothing in, I need this input to assign a value after validating the form content to use one of the field content to do stuff and then assign the results to the hidden input. According to this answer: https://stackoverflow.com/a/813474/15352101 I can simply do : if form.is_valid(): form.cleaned_data['Email'] = GetEmailString() but for me using : form.cleaned_data["social_color"] = icon_main_color icon_main_color is the results of the stuff I had to do, it's a tuple containing 3 values but when I check the created object with the form, the value of social_color is still empty. -
Adding a variable in Django templates static tag {% %} enclosure
I have a project in Django Python. And, I am trying to figure out how to add a variable in a {% %} enclosure I'ved got variables set in this way: CP_ENV_SMALLAPPNAME_CAPITALIZE <-- meta title variable CP_ENV_FAVICON_PATH <-- favicon variable path <title>{{ CP_ENV_SMALLAPPNAME_CAPITALIZE }}</title> <-- this works <link rel="icon" type="image/png" sizes="16x16" href="{% static 'img/{{CP_ENV_FAVICON_PATH}}/favicon-16x16.png' %}"> <--- this doesnt work How can I insert CP_ENV_FAVICON_PATH into {% static %} enclosure in django ? -
storing large data into mongodb collection using python
I am working on a Django project where I have to create 10 years of data and store them in MongoDB retrieve it and display it on the HTML page. I am trying to divide 10 years of data into 1 year and then store it in MongoDB collection but whenever I try to do so only two documents get stored and this error is shown in pymongo. errors.DocumentTooLarge: BSON document too large (29948865 bytes) - the connected server supports BSON document sizes up to 16793598 bytes. my python code is now=start workdate=now.date() nowtime=now.time() endt=end ktime=start times=[] states=[] level=[] #generating random level of water in the tank while (now!=endt): # loop for creating data for given time ktime=ktime+relativedelta(months=5) print(current_level) def fill(): global df global now global workdate global nowtime global ktime global current_level global flag global times global states global level while x=='on' and current_level<=450: times.append(now) states.append(x) level.append(current_level) current_level+=filling current_level=round(current_level,2) now=now+timedelta(minutes=1) nowtime=now.time() workdate=now.date if now==ktime: times.append(now) states.append(x) level.append(current_level) print("true") flag='red' break def drain(): global df global now global workdate global nowtime global ktime global current_level global flag global times global states global level while x=='off' and current_level>50: times.append(now) states.append(x) level.append(current_level) print(current_level) current_level-=emptyrate current_level=round(current_level,4) now=now+timedelta(minutes=1) nowtime=now.time() workdate=now.date() if now==ktime: times.append(now) states.append(x) … -
How to send array of django model objects in post api?
class Product(models.Model): name = models.CharField(max_length=255) class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="images") class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer How can I make my serializer and views? My post api request payload will be: [{"name":"Laptop", "images":[array of image files]}, {"name":"Shoes", "images":[array of images]}] -
Telegram Oauth2 with Django
I am exploring ways to send telegram messages to the users using Telegram bot from my Django application. The bot should be able to initiate the conversation - these messages are more like alerts and updates but not conversations. From Telegram developer documentation I could not find a standard OAuth2 implementation with Telegram to get access tokens for sending messages to the users using REST APIs. Does anyone know Oauth flow implementation for Telegram if at all it exists Sending messages using API - I am not planning to run a bot server. The messages just need to be pushed to the user - more like push notifications. Appreciate your help. -
Annotating the value difference from given Time Range Django
Considering a simple model class Event(models.Model): title = models.CharField(max_length=100) amount = models.IntegerField() What I want to achieve I'm trying to somehow use annotate to give me the difference b/w the last_entry(created for event) - first_entry(created for event) and ignore the rest in between I think we should be able to do this but if not possible please provide basis of telling so and thanks in advance -
why uploaded files is not deleting
I am new in Django, Here I have added a correct code but it is not deleting the file. Please help me someone. views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"usermaster/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): if request.method == 'POST': controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return HttpResponseRedirect('/usermaster/controlfile/') models.py: class Controlmachine(models.Model): machine_name = models.CharField(max_length=100) operation_no = models.IntegerField() control_uploadfile = models.FileField(upload_to='control_files/') class Meta: db_table = "controlmachine" def delete(self, *args, **kwargs): self.machine_name.delete() self.operation_no.delete() self.control_uploadfile.delete() super.delete(*args, *kwargs) forms.py: class ControlForm(forms.ModelForm): class Meta: model = Controlmachine fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/ widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }), 'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }), } urls.py: path('controlfile/',views.control_index,name='control_index'), path('cdelete/<int:id>',views.control_destroy,name='control_destroy'), path('controlupload/',views.control_upload,name='control_upload'), path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine'), control_show.html: {% extends 'usermaster/home.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> </head> {% block body %} <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%"> <thead> <th><input type="checkbox" id="checkall" /></th> <th>ID</th> <th>Machine Name</th> <th>Operation Number</th> <th>File</th> <th>Delete</th> </thead> <tbody> … -
Error when running heroku run manage.py migrate
If you run python manage.py migrate in Heroku, python: can't open file 'manage.py': [Errno 2] No such file or directory I am getting this error. How can I fix this error? If i run heroku run ls accounts config db.sqlite3 manage.py media photo Procfile requirements.txt runtime.txt templates rqueirments.txt asgiref==3.5.0 dj-database-url==0.5.0 Django==3.2.11 django-heroku==0.3.1 django-storages==1.12.3 gunicorn==20.1.0 Pillow==9.0.0 psycopg2==2.9.3 psycopg2-binary==2.9.3 pytz==2021.3 sqlparse==0.4.2 typing-extensions==4.0.1 whitenoise==5.3.0 Procfile `web: gunicorn config.wsgi` runtime `python-3.7.12` -
New superuser unable to log in to CMS
I'm new to Wagtail and django. I've completed the https://learnwagtail.com/wagtail-for-beginners/ course and managed to get my site up and running on Digital ocean, however I'm unable to login to the admin area. I have tried using the superuser credentials that were used locally. I have also tried multiple times to create a new superuser with: python manage.py createsuperuser and while the process appears to work successfully in the terminal (I'm logged in via SSH to my DO droplet), I continually receive the 'Your username and password didn't match. Please try again.' message when attempting to log in with the newly created username and password. If I use the shell to check users I can see my newly created user exists. I have also tried using python manage.py changepassword myusername to change the password on the previously created superusers, but again, while the process appears to work successfully in the terminal I continue to receive the error message when attempting to log in. Can anyone point me in the right direction as to what I might be missing or doing wrong here? And / or how I might best debug the issue? Thanks in advance! -
Error while adding records by admin panel django
So, lately I have been using Termux app in my android device to build django app. while I was using admin panel it opened but when I tried to add any records in my database tables through it It just prompted this error in the Termux terminal. Internal Server Error: /admin/travello/destination/add/ Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/files/move.py", line 61, in file_move_safe locks.lock(fd, locks.LOCK_EX) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/files/locks.py", line 111, in lock fcntl.flock(_fd(f), flags) OSError: [Errno 38] Function not implemented During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1670, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1549, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1599, in … -
List Class View didn't return an HttpResponse
I've been trying to get a class-based list view to display all entries under a user's account (applicant), but when loading the page I'm given the following error: The view jobassessment.views.view didn't return an HttpResponse object. It returned None instead. To me that sounds like the URL dispatcher isn't running the correct view, but this is my URL file for both the whole site and the jobassessment application and I can't seem to spot the fault. Site URL.py: urlpatterns = [ path('admin/', admin.site.urls, name="admin"), path('accounts/', include('django.contrib.auth.urls'), name="accounts"), path('applicant/', include('userprofile.urls'), name="applicant"), path('assessments/', include('jobassessment.urls')), ] JobAssessment App's URL.py: from django.urls import path from . import views urlpatterns = [ path("", views.AssessmentListView.as_view(), name="assessment"), ] This is my ListView that is called: class AssessmentListView(LoginRequiredMixin, generic.ListView): model = Assessment template_name ='assessments_index.html' paginate_by = 5 def get(self, request, *args, **kwargs): # Ensure they have first created an Applicant Profile if not Applicant.objects.filter(user=self.request.user).exists(): messages.info(request, "You must create a profile before you can view any assessments.") return redirect('profile_create_form') def get_queryset(self): return Assessment.objects.all().filter(applicant=Applicant.objects.filter(user=self.request.user)).order_by('-assessment_stage') -
selenium test doesn't display static files and data objects
Everything works perfectly on the local server and in the production but when trying to run the selenium test, the static files don't load. Even created data objects been displayed on the template is not also displayed. Here are the static setting in the settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' -
How to make auto-genertion(auto-fill and increment) in django admin
I want to make code field should be auto filled and auto increment in django admin. models.py class GeneralDocumentType(models.Model): code = models.CharField(max_length=10, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name I want to show my code field default=DOC001, and it will show increment by 1 before adding data by user.How can I achieve this?.. -
Django Search Box not displaying results
I'm new to coding and working on my class assignment displaying a search box in Django. I was able to display the search box, but the results are not being displayed. In the inspector tool, I do see the search results coming through the GET method so I am assume it must an issue with my HTML code. I would appreciate any suggestions/resources on how to fix this issue. Picture of search box {% extends "base_menu.html" %} {% block content %} <h1>Ads</h1> <div style="float:right"> <!-- https://www.w3schools.com/howto/howto_css_search_button.asp --> <form> <input type="text" placeholder="Search.." name="search" {% if search %} value="{{ search }}" {% endif %} > <button type="submit"><i class="fa fa-search"></i></button> <a href="{% url 'ads:all' %}"><i class="fa fa-undo"></i></a> </form> </div> <p> {% if ad_list %} <ul> {% for ad in ad_list %} <li> <a href="{% url 'ads:ad_detail' ad.id %}">{{ ad.title }}</a> {% if ad.owner == user %} (<a href="{% url 'ads:ad_update' ad.id %}">Edit</a> | <a href="{% url 'ads:ad_delete' ad.id %}">Delete</a>) {% endif %} </li> {% if user.is_authenticated %} <!-- Two hrefs with two stacked icons each - one showing and one hidden --> <a href="#" onclick= "favPost('{% url 'ads:ad_unfavorite' ad.id %}', {{ ad.id }});return false;" {% if ad.id not in favorites %} style="display: none;" … -
.NET vs Django vs Node [closed]
I'm a beginner at web development. I am considering learning web development and I need to choose a framework. What will you use .NET, Django or Node? I like being the language is typesafe. I'm currently learning C++. Could you please give me advice such as job opportunities, current trends? -
Connection to the another DB not created by Django
I have Django project and want to look the another db (not default db created by Php Symfony) Django can set up two DB in settins.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } 'extern': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config("DB_EXTERN_NAME"), 'USER': config("DB_EXTERN_USER"), 'PASSWORD': config("DB_EXTERN_PASSWORD"), 'HOST': config("DB_EXTERN_HOST"), 'PORT': config("DB_EXTERN_PORT"), } } and set models.py for example class Area(models.Model): class Meta: db_table = 'my_area' However it requires to change the extern database when python manage.py makemigrations,python manage.py migrate I just want to reference the extern db not alter. Is there any good practice?? -
Using DRF + frontend framework with Django froms
Background I ran into a really annoying problem here. I've decided to use Svlete as my frontend. Also, I have a lot of endpoints in my REST api that expect form data. In the past I would just forms.py in my app's directory and then add a form like: class ProductsModelForm(forms.ModelForm): class Meta: model = Product fields = ( 'name', 'weight', ) class ProductForm(forms.Form): name = forms.CharField() weight = forms.IntegerField() And would then use <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> In the HTML template. All cool. DRF + Frontend Framework Obviously I still have the form in the forms.py but now I have to define the form in the fronend too. And with bigger forms it gets really annoying because I always have to compare that I have every field in my frontend form that I have defined in the django backend form. Is ther any solution to this? -
Trying to make a form with 2 inputs
I have two different forms in my register page as the one to one relationship in one of the model will show a drop down box therefore I am using the second models field where the user will have to input the field. How would I make it so when the forms are valid, the 'SNI' will save to the first form and not the second. Model from asyncio import FastChildWatcher import email from pyexpat import model from xxlimited import Null from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=256, primary_key=True) Used = models.IntegerField(null=True, blank=True) password = None USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(primary_key= True ,max_length=256, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, …