Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datalist tag not working on making changes in HTML file related to Django
I am working on a task where I have to make a drop-down box with search filter. Here:- What is happening here is after selecting Fiscal year, it is displaying Annual work plan for the user according to that (after filtering). But it is displaying the drop down only, what I want is it should display the drop down with a filterbox too. In forms.py, select annual work plan is as follows:- Select_Annual_Work_Plan = forms.ModelChoiceField(queryset=annual_work_plan.objects.none().order_by("Annual_Work_Plan_ID"), label='Select Annual Work Plan', ) -> Its a ModelChoiceField. This is the function in views.py as ajax_load_Select_Annual_Work_Plan, by which we are rendering the html to display the dropdown, function is as follows:- @login_required() def ajax_load_Select_Annual_Work_Plan(request): Fiscal_year_val = request.GET.get("Fiscal_year") Select_Annual_Work_Plan_list = annual_work_plan.objects.filter(Fiscal_year = Fiscal_year_val).order_by("Annual_Work_Plan_ID") return render(request, "procurement_data/Select_Annual_Work_Plan_dropdown_list_options.html", {"Select_Annual_Work_Plan_list": Select_Annual_Work_Plan_list}) Select_Annual_Work_Plan_dropdown_list_options.html file is as follows(This is the complete code of this file):- {% for Select_Annual_Work_Plan in Select_Annual_Work_Plan_list %} <option value="{{ Select_Annual_Work_Plan.pk }}">{{ Select_Annual_Work_Plan}}</option> {% endfor %} I tried datalist tag of the html, which is basically used for the dropdown with search box but that is not working here as:- <div> <datalist id="suggestions"> {% for Select_Annual_Work_Plan in Select_Annual_Work_Plan_list %} <option value="{{ Select_Annual_Work_Plan.pk }}">{{ Select_Annual_Work_Plan}}</option> {% endfor %} <input autoComplete="on" list="suggestions"/> </datalist> </div> I tried some jQuery solutions … -
dj-rest-auth page not found while clicking on confirmation link
Via Postman I send POST http://127.0.0.1:8000/dj-rest-auth/password/reset/ with json: { "email" : "pyroclastic@protonmail.com" } I received the email with the confirmation link:http://localhost:8000/dj-rest-auth/password/reset/confirm/3/b18epl-d065751bdebfd3abacd0ddd62c419877 However upon clicking on this link it shows Page not found (404) As you can see through my url.py, I tried other ways (including ones in the faq and the api endpoints and config pages and went through the source codes) url.py from django.contrib import admin from dj_rest_auth.registration.views import VerifyEmailView from django.urls import path from django.urls import include, re_path from django.conf.urls.static import static from django.conf import settings from dj_rest_auth.views import PasswordResetConfirmView, PasswordResetView from allauth.account.views import ConfirmEmailView from django.views.generic import TemplateView from .router import router from BackendApp.views import P2PListingModule, empty_view, GoogleLogin, FacebookLogin urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('entity/', include(router.urls)), path('enduser/<str:pk>/service/', P2PListingModule.userServiceListing), path('enduser/<str:pk>/request/', P2PListingModule.userRequestListing), path('enduser/<str:pk>/swap/', P2PListingModule.userSwapListing), path('enduser/<str:pk>/premade', P2PListingModule.userPremadeListing), path('entity/p2p_listing/order/', P2PListingModule.placeOrder), path('api/p2plisting/service', P2PListingModule.ServiceListingView.as_view()), path('api/p2plisting/request', P2PListingModule.RequestListingView.as_view()), path('api/p2plisting/swap', P2PListingModule.SwapListingView.as_view()), path('api/p2plisting/premade', P2PListingModule.PremadeListingView.as_view()), re_path(r'^', include('django.contrib.auth.urls')), path('dj-rest-auth/password/reset/', PasswordResetView.as_view(), name="rest_password_reset"), path( "dj-rest-auth/password/reset/confirm/", PasswordResetConfirmView.as_view(), name="rest_password_reset_confirm", ), path( # path('/dj-rest-auth/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,32})/$', "/dj-rest-auth/password/reset/confirm/<uuid:uidb64>/<slug:token>/", # PasswordResetConfirmView.as_view(), # ConfirmEmailView.as_view(), TemplateView.as_view(template_name="password_reset_confirm.html"), ), path('auth/google/', GoogleLogin.GoogleLoginView.as_view(), name='google_login'), path('auth/facebook/', FacebookLogin.FacebookLoginView.as_view(), name='fb_login'), re_path(r'^accounts/', include('allauth.urls'), name='socialaccount_signup'), # path('dj-rest-auth/account-confirm-email/', ConfirmEmailView.as_view(), name='account_email_verification_sent'), # re_path(r'^password-reset/$', # TemplateView.as_view(template_name="password_reset.html"), # name='password-reset'), # re_path(r'^password-reset/confirm/$', # TemplateView.as_view(template_name="password_reset_confirm.html"), # name='password-reset-confirm'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns = [ # url(r'^admin/', include(admin.site.urls)), # ] + … -
Why not cached when crossing domain?
I write a django project,use minio to save files like css,js. The project run on a:8100,minio run on b:9001. When I open(new open) the page by browser,I get the result: It showed: not cached.(200 http code) But the response has headers(the server want the client to keep cache): And when I click the refresh button.It shows different(the client cached!): It cached? response status code is 304. But if I click by new open(not refresh), the response's http code also is 200,which shows not cached. And the another page,like the situation above(but the image more large,about 5-7 Mb),not cached,both click refresh and new open page. Could anyone tell anything about the cache when crossing domain? I hope the staticfile could use local cache when crossing domain >..< -
how to use pagination in ListView in django using get_paginate methed
class ManageStudentView(ListView): model = Student template_name = 'student/manage_student.html' def get_context_data(self, **kwargs): kwargs = super(ManageStudentView, self).get_context_data(**kwargs) kwargs['student'] = User.objects.filter(user_type=STUDENT) return kwargs def get_queryset(self): search_query = self.request.GET.get("student", None) if search_query != None: return Student.objects.filter(name__contains=search_query) return Student.objects.all() def get_paginate_by(self, queryset): self.paginate_by = settings.PAGINATION_NUMBER return self.paginate_by -
how to join multiple table sum in single query with foreign key Django ORM
Here i giving table Structure: class MainTable(models.Model): code = models.CharField(max_length=25) qty = models.FloatField(default=0) class Table1(models.Model): code = models.ForeignKey(MainTable, on_delete=models.CASCADE, related_name='table_one') date = models.DateField() qty = models.FloatField(default=0) class Table2(models.Model): code = models.ForeignKey(MainTable, on_delete=models.CASCADE, related_name='table_two') date = models.DateField() qty = models.FloatField(default=0) class Table3(models.Model): code = models.ForeignKey(MainTable, on_delete=models.CASCADE, related_name='table_three') date = models.DateField() qty = models.FloatField(default=0) I want this type of table: ________________________________________________________ | Code | qty | table1_sum| table2_sum | table3_sum | --------------------------------------------------------- |code1 | 5000 | 2000 | 3000 | 4000 | --------------------------------------------------------- |code1 | 5000 | 2000 | 3000 | 4000 | --------------------------------------------------------- |code1 | 5000 | 2000 | 3000 | 4000 | -------------------------------------------------------- I am traying this query but it does not give proper value: query = MainTable.objects.all().annotate(table1=(Sum('table_one__qty')),table12=(Sum('table_two__qty')),table3=(Sum('table_three__qty'))) In this query, table one gives the actual value but the other table gives the wrong value. need proper query. -
Direct assignment to the reverse side of a related set is prohibited in custom Django query
So I'm trying to use the Django ORM in a non-standard way - I want to get relationships with related tables, but I am trying to do via a raw query - mostly because I need to use ORDER BY RAND() rather than the standard Django random query method, because it's substantially slower. So I have this query: base_sql = "SELECT article_sentence.id, article_sentence.language_id, article_sentence.per_language_id, rule_mapping_sentence.rule FROM article_sentence " join_sql = "JOIN rule_mapping_sentence ON (article_sentence.id = rule_mapping_sentence.sentence_id) " where_sql = "WHERE article_sentence.id IN " subquery_sql = "(SELECT sentence_id FROM rule_mapping_sentence GROUP BY sentence_id HAVING COUNT(*) >= 0) " order_sql = "ORDER BY RAND() " limit = "LIMIT " + str(number) query = base_sql + join_sql + where_sql + subquery_sql + order_sql + limit sentences = models.Sentence.objects.raw(query) However I get: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use rule.set() instead. This seems to be due to the way that my models are related. Here's my sentence model: class Sentence(models.Model): sentence = JSONField(default=dict, null=True, ) json = JSONField(default=dict, null=True, ) per_language = models.ForeignKey( PerLanguage, on_delete=models.CASCADE, null=True, related_name="sentence" ) language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True) Here's my Rules model: class Rules(models.Model): rule = models.CharField(max_length=50) function = models.CharField(max_length=50) definition = … -
Django - models.ForeignKey Giving error that mentions class is not defined
I am developing a Student management system in django and while making it I got this class Dept(models.Model): id = models.CharField(primary_key='True', max_length=100) name = models.CharField(max_length=200) def __str__(self): return self.name class Course(models.Model): dept = models.ForeignKey(Dept, on_delete=models.CASCADE) id = models.CharField(primary_key='True', max_length=50) name = models.CharField(max_length=50) shortname = models.CharField(max_length=50, default='X') def __str__(self): return self.name and while doing make migrations I get this error by what means Can I get this right and how can I tackle this error (studentmanagementsystem) C:\Users\harsh\dev\student management\student_management>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\harsh\anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\harsh\anaconda3\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\harsh\anaconda3\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\harsh\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\harsh\dev\student management\student_management\student_app\models.py", line 10, in <module> class Dept(models.Model): File "C:\Users\harsh\dev\student management\student_management\student_app\models.py", line 18, in Dept class Course(models.Model): File "C:\Users\harsh\dev\student … -
Django Model default field overridden by seriliazer
I set my default value of publish to True in the model, but after creating a new entry in the EntrySerializer it saves as False. I can manually correct this by overriding the create() method in the serializer, but I'm wondering it there's a more elegant way. class EntrySerializer(serializers.ModelSerializer): class Meta: model = Entry fields = '__all__' read_only_fields = ['code', 'author', 'slug', 'created', 'modified'] My model class Entry(models.Model): slug = models.SlugField(max_length=255) title = models.CharField(max_length=200) description = models.TextField() publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) media = models.TextField(validators=[URLValidator()], null=True, blank=True) def save(self, *args, **kwargs): if not self.id: slug_str = "%s %s" % ( uuid4().hex[:6].upper(), self.title) self.slug = slugify(slug_str) super(Entry, self).save(*args, **kwargs) Results of post request { "id": 9, "slug": "f4eabc-new-test", "title": "new test", "description": "dsfsdfs", "publish": false, "created": "2022-02-22T03:12:52.479158Z", "modified": "2022-02-22T03:12:52.479190Z", "media": null, "author": 1 } -
Define mysql command line args in Django DATABASES settings
When using mysql with Django, the presence of .my.cnf causes this: $ python manage.py dbshell ERROR 1045 (28000): Access denied for user 'foo'@'localhost' (using password: YES) CommandError: "mysql --user=foo --host=localhost --default-character-set=utf8mb4 quxdb" returned non-zero exit status 1. I'd like to keep my my.cnf and be able to use dbshell, etc. Is there a way to set --no-defaults or other mysql command line args in DATABASES in settings.py? -
Django Forbidden (CSRF cookie not set.): / POST / HTTP/1.1" 403 2864 on Google Colab
so i'm tryin to run my Django web program on Google collab based on this tutorial https://medium.com/@arsindoliya/running-django-on-google-colab-ea9392cdee86 And i did it the web can running! running web But, if i want to make POST it's always error like this Forbidden (CSRF cookie not set.): / [22/Feb/2022 02:13:47] "POST / HTTP/1.1" 403 2864 And i'm already try some solution like put the CSRF_COOKIE_SECURE = True inside my settings.py but still not working and i do put the @csrf_token on my form too and it's still not working. Also i wanna try this solution to from django.views.decorators.csrf import csrf_exempt but i'm still don't understand how to use that. Does anyone has a solution for it? I'm still new in Django and i made it for my college's final project, so any solution that you guys make really helpful for me. Thank you -
Problem linking CSS file to HTML file using Django
I had some issues linking a CSS file to HTML file while using Django. Here is my HTML file where I linked a static file name home.css {% load static %} <link rel="stylesheet" href="{% static 'home.css' %}" type="text/css"> My folder is organised as so for my templates folder: \Users\me\Desktop\mysite\templates\base\home.html And for my static folder: \Users\me\Desktop\mysite\static\home.css Doesn't someone know from where does the problem come? -
My website template is aligned to the left side
My code is exceeding the word limit so you can see the code here. This is my template and when I run the server locally, the webpage is kinda aggined to the left side like this. But in fact, it should look like this.. I set the static directory in the settings.py as STATIC_DIRS = (os.path.join(BASE_DIR, "static"),) and I loaded the static on the top of the page as shown. Can't figure out the problem. -
How to apply split function to a specific field in Django's queryset
I am using Django and groupby based on the 'teacher' field. However, there are two or three values in the 'teacher' field as well as one, so I want to split it. However, I get an error saying that 'F' object has no attribute 'split'. If you have any other workaround, please help me! [views.py] counts = Research.objects.values(F('teacher').split('/'))\ .annotate(count=Count('id', distinct=True))\ .values('teacher', 'count') teacher subject Helen math Adam/Jennie science Jennie music The result I want to get is: <Queryset: [{teacher:'Helen', count:'1'}, {teacher:'Adam', count:1}, {teacher:'Jennie', count:2}]> -
403 Forbidden when using Django's PermissionRequiredMixin
I'm trying to restrict access to the view 'GovernmentView' to users whose account has True on the field 'is_government' by implementing the PermissionRequiredMixin argument. But it's not working. Registered users who have True for the field 'is_government' are getting the 403 Forbidden error (and Superusers who have False on that field do not see the error and can access the template). How can I fix this error and restrict access as stated above? Thanks. settings.py: LOGIN_URL = reverse_lazy('users:login') LOGIN_REDIRECT_URL = 'users:home' urls.py: app_name = 'users' urlpatterns = [ path('', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('activate-user//', views.activate_user, name='activate'), path('home/', views.home, name='home'), path('government/', views.GovernmentView.as_view(), name='government'), models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_active = models.BooleanField(default=True) is_email_verified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_government = models.BooleanField(default=False, verbose_name="Gov't Official") date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email @staticmethod def get_absolute_url(self): return reverse("users:home") views.py: class GovernmentView(PermissionRequiredMixin, ListView): permission_required = 'CustomUser.is_government' template_name = 'users/government.html' model = List form_class = Form def get_context_data(self, **kwargs): context = super().get_context_data() context["List"] = List.objects.all() return context government.html: {% if request.user.is_government%} <div class="nav"> <a id="government" {% block government %} class="selected" {% endblock %} href="{% url 'users:government' %}"></a> </div> {% endif … -
in this django code when i post some text saveed in the table betwen (' my text i post ',)
view def Apply2 (request): if request.method=="POST": q1 = order.objects.last() if q1 is not None: q1.Course_Selection = request.POST["1221"], q1.save() response = redirect('/apply3') return response return render(request,'Apply_Now2.html') -
Django with aurora, how to use two instances?
I have django script with mysql My settings is below. mysql server is in the local. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": 127.0.0.1, "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } } Now I want to use amazon AURORA It has two instances reader/writer How can I set the instance to django?? -
'SimpleHistoryAdmin' has no attribute _meta problem
i installed django-simple-history but, it's not working. I tried python manage.py makemigrations i paced below error. like AttributeError: type object 'SimpleHistoryAdmin' has no attribute '_meta' I want to see history in django-admin. what's wrong????? Traceback (most recent call last): class AccountClassificationAdmin(admin.ModelAdmin): File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/contrib/admin/decorators.py", line 100, in _model_admin_wrapper admin_site.register(models, admin_class=admin_class) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 113, in register if model._meta.abstract: AttributeError: type object 'SimpleHistoryAdmin' has no attribute '_meta' # settings.py i added 'simple_history', at installed_app 'simple_history.middleware.HistoryRequestMiddleware', at middleware # models.py class PayHistory(TimeStampedModel): package_patient = models.CharField(max_length=10, null=False) package_classification = models.CharField(max_length=10, null=False) history = HistoricalRecords() class PayHistoryChange(TimeStampedModel): payhistory = models.ForeignKey(PayHistory, on_delete=models.CASCADE, null=False) history = HistoricalRecords() # admin.py @admin.register(PayHistory) class AccountCategoryAdmin(SimpleHistoryAdmin): list_display = ( "package_patient", "package_classification" ) -
Cannot get "images" net::ERR_CONNECTION_REFUSED (Gitpod)
On Gitpod, my NextJS frontend is trying to fetch the list of objects which contain "product names", "prices" and "images" from my Django Rest API backend. Then, my NextJS frontend can get the list of objects which contain "product names" and "prices" but not "images" so my NextJS frontend cannot get only "images" as shown below: ("product names" such as "boots 4", "boots 3" ... and "prices" such as "£12.10", "£10.50" ... are displayed but not "images") This is my desired output with "product names", "prices" and "images": On Gitpod, both my NextJS frontend on port 3000 open (private) and my Django Rest API backend on port 8000 open (private) are running: And my NextJS frontend uses this Rest API call with "localhost" as shown below to get the list of objects which contain "product names", "prices" and "images": http://localhost:8000/api And, this is the errors: 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/paid.png net::ERR_CONNECTION_REFUSED 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/size.png net::ERR_CONNECTION_REFUSED 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/download.jpg net::ERR_CONNECTION_REFUSED 3000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/:987 GET http://localhost:8000/media/images/02173_l.jpg net::ERR_CONNECTION_REFUSED Actually, I solved these errors above by using this Rest API call with my Gitpod domain as shown below to get the list of objects: https://8000-gitpodio-templatetypescr-tqzkjl97w1d.ws-us33.gitpod.io/api But other error occurs as shown below: Server Error FetchError: invalid json response … -
Django 2.0 migration breaks django-autocomplete-light unit test with TypeError
I am trying to migrate to Django 2.0 from 1.11 but some unit tests related to django-autocomplete-light (3.5.1) have started failing with a TypeError after calling self.client.get() from TestCase class. (__init__() takes 1 positional argument but 2 were given) Some suggestions I found stated that missing as_view() in the URL view could be the issue but it is already there. I also changed the MIDDLEWARE_CLASSES variable to MIDDLEWARE in the settings. test.py from django.urls import reverse from django.test import TestCase from django.contrib.auth.models import User class AutocompleteTestCase(TestCase): def setUp(self): self.admin_cred = { 'username': 'test', 'password': 'test', } self.user = User.objects.create_superuser('test', 'test@test.com', self.admin_cred['password']) def query_autocomplete_view(self, url_name, query=None): data = {} if query: data['q'] = query self.client.force_login(self.user) response_json = self.client.get(reverse(url_name), data=data).json() return response_json.get('results') Error Traceback Traceback (most recent call last): File "/home/circleci/project/test/apps/dataadmin/tests/test_autocomplete_views.py", line 131, in test_dataadmin_field_autocomplete results = self.query_autocomplete_view('admin:dataadmin_autocomplete_dataadminfield', query='test') File "/home/circleci/project/dataadmin/common/test_utils.py", line 23, in query_autocomplete_view response_json = self.client.get(reverse(url_name), data=data).json() File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 517, in get response = super().get(path, data=data, secure=secure, **extra) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 332, in get return self.generic('GET', path, secure=secure, **r) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 404, in generic return self.request(**r) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 467, in request response = self.handler(environ) File "/home/circleci/project/venv/lib/python3.6/site-packages/django/test/client.py", line 125, in __call__ self.load_middleware() File "/home/circleci/project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 39, in load_middleware … -
Django how to add specific query results to model when appending to database
I have a model that holds "title", "area", "price" and "price2". I have a database table that holds "area", and "price2". First I create model object. Then I want to go to database, get average "price2" for the "area" of the model, and then save that into "price2" of the model. How can I accomplish this? Thank you. -
Django postgres full text search error "Unsupported lookup 'search' for CharField"
All similar problems have been solved by adding django.contrib.postgres to INSTALLED_APPS in settings.py, which is also all the docs mention on how to use the lookup. I've already done this and the lookup still isn't working, despite whether I use __search or search= for the filter. Any ideas? Do I need to register the lookup in my model myself? settings.py: INSTALLED_APPS = [ ... 'django.contrib.postgres', # my_project 'my_project.apps.appname', 'my_project.apps.appname', ... error line: x = y.objects.filter(description__search="example") -
Select specific option from dropdown menu DJANGO
I have a page that lists all the items from a table named Stocks for each row there's a clickable ORDER button that leads users to another page where they can enter all their details as well as select what item and how much they wanna buy which would then save all of that data to a table named Orders. This orders table is linked with the Stocks table like this: class Order(models.Model): name = models.CharField(max_length=50, blank=True, null=True) quantity = models.IntegerField(default='0', blank=False, null=True) order_item = models.ForeignKey(Stock, on_delete=models.CASCADE, blank=True) address = models.CharField(max_length=50, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) Depending on what item they clicked the order button for I wanted to automatically select the corressponding item from the dropdown menu on the next page so that they won't have to. def create_order(request, pk): queryset = Stock.objects.get(id=pk) form = CreateOrderForm(request.POST or None, initial={'order_item':queryset.item_name}) if form.is_valid(): form.save() context = { 'form':form } return render(request, 'add_items.html', context) I tried doing this by using the intitial command but for some reason it just won't change from the default blank option. Here's my forms.py just in case class CreateOrderForm(forms.ModelForm): class Meta: model = Order fields = ['name','quantity','order_item','address','city'] -
Cannot import name 'force_text' from partially initialized module 'django.utils.encoding'
My project was working perfectly fine until I tried installing security for Bruteforce for the login system by installing packages like Django-defender & BruteBuster. However, suddenly I was prompted with this error and cannot seem to find the reason why. There are many other similar questions where the answer would say to change the force_text to force_str within the graphene_django folder in my ENV. Therefore, I do not know where to insert or change the text to str as I do not have a graphene_django folder at all. Furthermore, I have checked other Django projects within my device which also shows a similar error even though I have barely done anything. For more description here is the full error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 263, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\core\management\__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\DELL7390\AppData\Local\Programs\Python\Python38- 32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line … -
How to use a model inside django settings?
I need to use one of my models to define Django settings variables. Meaning, the django variables will be dinamically defined by what's on the database. When I use a function that uses one of my models: from util.auth_utils import get_app_auth auth = get_app_auth() It throws an error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If I try to use this code inside the settings.py: import django django.setup() Also throws an error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Besides that, I tryed to move the django.setup() part to after the INSTALLED_APPS, but then it wont load settings correctly. Any clues? -
What's the difference beetwen django database engines?
In setting.py file I can that sqlite3 is set by default as db engine. In the docs i read that I can change it to other engines like PostgreSQL MariaDB or MySQL. But here is my question. What for ? Are these engines better/faster than default sqlite3 ? Is there any point of learning how to change database for other than default ?