Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a Parent/Child relationship with Django REST models?
I am new to Django REST and want to basically create a join table like this. One Page (txt doc) can have a parent and child Page. Each and every Page can be a parent and child of multiple other pages. Both the Page Entity and PageToPage Entity have an implemented model & serializer in the backend, where the serializer looks like this: class PageToPageSerializer(serializers.ModelSerializer): parent_page = PageSerializer(many=True, read_only=True) child_page = PageSerializer(many=True, read_only=True) class Meta: model = PageToPage fields = ['pkid', 'parent_page', 'child_page'] When entering the manage.py shell and create a PageToPage object, it just yields empty results: # Create Pages p1 = Page(title="Parent Page 1", text="Once upon a time, there was a young man...", page_of_user=u2) p1.save() p3 = Page(title="Child Page 1", text="Once upon a time, there was a young man...", page_of_user=u2) p3.save() # Create Page Relationships ptp = PageToPage(parent_page=p1, child_page=p3) ptp.save() # Select all Pages print("Created Pages:") ser2 = PageSerializer(Page.objects.all(), many=True) print(ser2.data) # Select all Page to Page relationships ser_ptp = PageToPageSerializer(PageToPage.objects.all()) print("Created Page relationships:") print(ser_ptp.data) Output: >>> Created Pages: >>> [OrderedDict([('pkid', 1), ('title', 'Test Page number 1'), ('text', 'Just some sample text'), ('creation_date', '17.06.2021'), ('page_of_user', UUID('eeec0437-75f2-44ba-935d-96fcb78e38c6'))]), ...] >>> Created Page relationships: >>> {} What am I doing wrong? … -
Django Admin 403 in Autocomplete as Superuser
Django==3.2.4 I'm getting error 403 when entering a query in a django admin autocomplete field. This only happens in production and in every model with autocomplete fields. Please tell me if more info is required in order to answer this question. Thanks! Example screenshot in Django Admin autocomplete field RESPONSE HEADERS alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443"; ma=86400 cf-cache-status: DYNAMIC cf-ray: *** cf-request-id: *** content-encoding: br content-language: es-ar content-type: text/html; charset=utf-8 date: Thu, 17 Jun 2021 21:29:22 GMT expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" nel: {"report_to":"cf-nel","max_age":604800} referrer-policy: same-origin report-to: *** server: cloudflare strict-transport-security: max-age=31449600; includeSubDomains; preload vary: Accept-Language, Cookie x-content-type-options: nosniff X-DNS-Prefetch-Control: off x-frame-options: DENY x-xss-protection: 1; mode=block REQUEST HEADERS :authority: *** :method: GET :path: /***/autocomplete/ :scheme: https accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 accept-encoding: gzip, deflate, br accept-language: es,es-US;q=0.9 cache-control: max-age=0 cookie: csrftoken=***; sessionid=*** dnt: 1 sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91" sec-ch-ua-mobile: ?0 sec-fetch-dest: document sec-fetch-mode: navigate sec-fetch-site: none sec-fetch-user: ?1 upgrade-insecure-requests: 1 user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36 -
Django Return JSON POST Response Header & Body
I created a webhook for my Django project and I am trying to do a verification with another API from SmartSheet SDK Python. Basically in order for me to enable a webhook for one of my sheets, I have to echo back the verification data from header and body back for the webhook to be enabled. Here is my python code. Basically up to this point, if you send a POST request through postman to my Django project, it will record it in the database with the changes, however I haven't created a process yet on what to do with the data. @csrf_exempt def SmartSheet_WebHook(request): if request.method == "GET": return HttpResponse("This is a GET Request.", content_type="text/plain") if request.method == "POST": record = APIInformation.objects.get(api_name = "SmartSheet") key = record.key given_token = request.headers.get("key", "") if compare_digest(given_token, key): print("Deleting stale records") WebHookSmartSheet.objects.filter(received_at__lte=timezone.now() - dt.timedelta(days=7) ).delete() payload = json.loads(request.body) WebHookSmartSheet.objects.create(received_at=timezone.now(),payload=payload,) print(payload) # Process Payload New Student Creation return JsonResponse(payload, safe=False) else: return HttpResponse("Verification Error.", content_type="text/plain") How do I return the data I am getting from the post request they are sending to my webhook? Here is their documentation on what they are looking for. "When an API client attempts to enable a webhook, Smartsheet … -
Django rest framework with client-side validation
I have so many questions, so I gonna contextualize what I am trying to do. I'm creating a Django chat app with rest_api in the backend and eventually will work with websocket to be a real-time website. The first feature that i am implementing is: I want to do some client-side validation that verify if the room that i want to connect already exists. in my api/models.py: class Room(models.Model): name = models.CharField(max_length=64, blank=False) host = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) def __str__(self): return self.name I created a serializer for that model and the follow APIView: class RoomView(ListCreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer pointing to the follow URL: app_name = 'api' urlpatterns = [ path('room/', views.RoomView.as_view(), name='index'), ] I have that function that check if the typed room already exist, if exist will redirect to that room, if don't, should send a POST request to my api, return and redirect. function roomExist() { let name = document.getElementById('name'); if (!isEmpty(name)) return; let room = document.getElementById('room'); if(!isEmpty(room)) return; fetch('../api/room') .then(res => res.json()) .then(data => { data.forEach((e) => { if (e.name === room.value) { submitForm() }}) createRoom(room.value) }) } wheel, my problem is with that last part, how i can send a POST request to … -
How to pass qs.query to a custom plpgsql function with Django ORM?
I have some queryset qs = MyModel.objects.filter(fieldname='fieldname') and a custom plpgsql function my_function(), that I can use in pg_shell like: SELECT my_function('SELECT * FROM my_model'); How to do this with Django ORM? I tried to: with connection.cursor() as cursor: query, params = qs.query.sql_with_params() query = f"SELECT my_function('{query}')" cursor.execute(query, params) But qs.query.sql_with_params() does not return valid SQL. Is something like this even possible with Django ORM? -
Hi, I am having a problem related a django postgreSQL
I have two tables and I need to calculate something similar to a smoothie Table fruit: fruit_Id, fruit_name, fruit_cost fruit_name(pk) Table smoothie: id juice_name fruit1_name References fruit.fruit_name, fruit1_% , fruit2_name References fruit.fruit_name, fruit2_% , smoothie_cost In order to calculate smoothie cost I need access price from Table fruit. Can you suggest best way to do this. I have tried to use Joins and triggers but no use. Is calculating in models.py is best approach or in PostgreSQL -
How I can create a textfield in dajngo admin that not create a field in database?
In django, I need a textfield and a button in django admin, but I don't want to save that textfield in database. For example I have a textfield named age. I need to a textfield to enter birthday.By clicking on button I will calculate age and assign to age field. This is only a example! -
Django MPTT selects all categories data while rendering to template?
I am using the django MPTT library for building my category model. Everything works fine but I noticed the following issue which is quite annoying. For every category that is rendered in my template, MPTT does a select * and gets all categories. I used the django debug toolbar to profile the query. I found this behaviour quite strange. Wanted to know if anyone else experienced such an error. This is the sample code from categories.base import CategoryBase class SampleCategory(CategoryBase): class Meta: verbose_name_plural = 'Sample Categories' class Product(models.Model): category = models.ForeignKey( SampleCategory, on_delete=models.SET_NULL, null=True, blank=True, ) In template <span class="dropdown"> <a href="#" class="dropdown-chevron" data-toggle="dropdown" data-display="static" aria-haspopup="true" aria-expanded="false"> </a> <span class="dropdown-menu dropdown-menu-lg-right filtersDropdown"> {% bootstrap_field filter.form.category bound_css_class='' show_label='sr-only' size='sm' %} {% bootstrap_button 'Filter' button_type='submit' size='sm' button_class='btn-primary mb-3 mr-md-2' %} </span> </span> filters.py category = django_filters.ModelMultipleChoiceFilter(field_name='category', queryset=SampleCategory.objects.all(), ) -
Images not displaying in a rendered pdf
I'm tryin to render a particular html file to pdf and it work. But the issue is the rendered pdf file does not contain an image which i linked in the html file. below is the code Below is my Views def get(request): template = get_template('success.html') context = { 'path': f"{surname}.png" } html = template.render(context) pdf = render_to_pdf('success.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Paymentslip%s.pdf" content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") utils.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Any solutions will be appreciated. Thanks. -
Django one to many query
I have a one-to-many model relationship an trying to query both the main and the referenced model in views. The model.py looks like this(simplified): class Project(models.Model): project_number = models.CharField(max_length=5, unique=True) .... class Phase(models.Model): time_input_id = models.AutoField(primary_key=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, default=None) phase_name = models.CharField(max_length=50, null=True) Views.py: How can I structure the views in order to pass all the fields to a template that shows info about the project and all its phases? I've tried so many things with no success, my brain just stopped functioning now. -
I want to make a User to User Private Live Chat App with React & Django
I'm really confused about that. I want to make a user to user chat app on my project with Django and React. I've tried create a model and fetch messages with Rest Framework API. But that's not what i need. I need to live chat between just two users. When a user send a message to me i want to display that instantly (without click anywhere) like Whatsapp. When i try this with DRF i can get messages and save them inside to useState. But i must to refresh page for display new messages. I don't want to this. I don't want to refresh to page. How can i do that? I saw Django Channel but i don't know can i use this for just between two user's private messaging. Also i don't know how to set this on React JS. Can anyone help me? I just need your opinions. I can try your opinion. You don't have to write code for me. -
Cross-Origin Request Blocked - REACT and webserver issue
My application consist of three major parts. Firstly, it consist of a Django application that functions as my REST-API. The second part consist of a nginx web-server that is linked with the Django application through a reverse-proxy. These two components, the web-server and Django application is containerized using docker. The last component, and the one which is creating problems is my React application which is responsible for the GUI. When requests are sent between React application, and the server though Axios, I'm getting the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/. (Reason: CORS request did not succeed). Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. As I understand from the error, the problem is most likely connected to Cross-Origin Resource Sharing. Consequently I've tried the following modifications. In aspect to the Nginx, I've change the conf folder by adding: add_header Access-Control-Allow-Origin *; upstream API { server web:8000; } server { listen 80; location / { proxy_set_header Host $host; add_header Access-Control-Allow-Origin *; proxy_pass http://API; } location /staticfiles/ { alias /home/app/web/staticfiles/; } location /mediafiles/ { alias /home/app/web/mediafiles/; } } In terms of the Django application, I've added the CorsMiddleware middleware and … -
pipenv Locking failed: No closing quotation
I am trying to use django in a virtual environment. I am using windows 10 and python 3.9. I write in my cmd pipenv install django but it constantly gives me a locking error: Installing django... Adding django to Pipfile's [packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Resolving dependencies... Locking Failed! Traceback (most recent call last): File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 764, in <module> main() File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 758, in main _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write, File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 741, in _main resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 702, in resolve_packages results, resolver = resolve( File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 684, in resolve return resolve_deps( File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1397, in resolve_deps results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1110, in actually_resolve_deps resolver.resolve() File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 825, in resolve results = self.resolver.resolve(max_rounds=environments.PIPENV_MAX_ROUNDS) File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 813, in resolver self.get_resolver(clear=self.clear, pre=self.pre) File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 804, in get_resolver constraints=self.parsed_constraints, repository=self.repository, File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 797, in parsed_constraints self._parsed_constraints = [c for c in self.constraints] File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 797, in <listcomp> self._parsed_constraints = [c for c in self.constraints] File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\patched\notpip\_internal\req\req_file.py", line 137, … -
database connection isn't set to UTC - Django getting timestamp
Set-up I'm trying to run unit tests in Django. pipenv run python manage.py test test_module.tests.test_application.ExampleTest I'm getting the following error: Traceback (most recent call last): File "C:\Users\Dom_W\Documents\Development\Projects\project_test\data_load_api_functions\tests\test_deepcrawl_api.py", line 210, in setUp print(list(User.objects.all())) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\sql\compiler.py", line 1130, in execute_sql return list(result) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\sql\compiler.py", line 1509, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\sql\compiler.py", line 1509, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\utils.py", line 96, in inner return func(*args, **kwargs) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\backends\postgresql\utils.py", line 9, in utc_tzinfo_factory raise AssertionError("database connection isn't set to UTC") AssertionError: database connection isn't set to UTC I think it might've started because of the switch to BST, but now despite forcing timezone I can't get Django to recognise it. What I've tried I set the default Postgres timezone to UTC in postgresql.conf That did nothing so I inspected the function which is responsible: def utc_tzinfo_factory(offset): if offset != 0: raise AssertionError("database connection isn't set to UTC") return utc And discovered it's being given a datetime.timedelta with a value of 0:00:00 which then causes this line to fail: … -
How to displaying an HTML table with pandas in another template using Django?
I would like to display a data table HTML in an specific template with Django, but I couldn't archive it successfully, am I missing sth important? views.py def dato(request): item = pd.DataFrame({'Nombre Proyecto': ['Cargador de Film', 'Planta de desarrollo','Envasadora'], 'Responsable Proyecto': ['Francisco Bruce','Daniel Nieto','Patricio Oyarzun'], 'Evaluador Proyecto': ['Equipo Austral Pack','Equipo Austral Pack','Equipo Austral Pack'], 'Descripción Proyecto': ['Carga films platicos para envase','Desarrolla Productos','Envasa Productos'] }) data =item.to_html(index=False) return render(request, 'dato.html', {'data': data}) dato.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> </head> <body> {% block content %} <h1>Dato</h1> {{data | safe}} {% endblock %} </body> </html> urls.py from django.urls import path from . import views urlpatterns = [ path("dato.html",views.dato, name="dato"), ] -
Is there any way to use url without writing anything in views?
I have made a model and have registered it. In the urls i have Path = ( r'^Api/', ) Is there a way to make this work without adding any views reference? -
the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I need to send an email in Django but I'm getting this error. What should I do? views.py def home(request): info = About.objects.first() # send email if request.method == 'POST': email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] send_mail( subject, message, email, [settings.EMAIL_HOST_USER], ) print(message) print(subject) print(email) return render(request,'base/index.html', {'info': info}) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'hamadakamal819@gmail.com' EMAIL_HOST_PASSWORD = 'qwtbjecezmvrxjfj' EMAIL_USE_TLS = True -
Rest Framework cant save serializer with foreign key
I have next serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = Post fields = ['id', 'title', 'text', 'date', 'category'] And here is my view: @api_view(['POST']) def create_post(request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors) return Response(serializer.data) I want to create new Post object, but when I pass an category id at form it does not work, it is not saving my object. I tried to replace create method at my PostSerializer, to this: def create(self, validated_data): category_id = validated_data.pop('category') post = Post.objects.create(**validated_data, category=category_id) return post but this dont work. Using postman formdata it is saying, that category field is required despite I filled it. -
Error while running server in Wagtail CMS
This error happens when I add a banner title. Banner title I believe is the property in the class and it's being referenced as a string. Completely new to DJANGO & Wagtail CMS + only been coding/programming for the last eight months! Any help greatly appreciated (: Here is what my terminal says Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/alessiolivolsi/Work/Projects/first_wag/wagsite/home/models.py", line 8, … -
Get User ID from rest-auth social Login
I have been trying extensively to get the User ID from Django rest-auth Google login. The default response is: { "key": "6ee5ff4db218a25113f35580d00aeeaf2fe8a2d1" } which is not enough, I need to have the user ID with it. I looked at using custom model serializers but to no avail. My class-based view is: class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter Would appreciate any guidance in this regard. Thank you -
Detect if a model is the through model of an M2M relationship
I've got a widget which offers choices built from content types so that objects can be referenced by ID & content type. I'd like to exclude from those choices; proxy models, automatically created models and M2M (through) models. While inspecting the model _meta I found many_to_many so have implemented the following; content_types = ContentType.objects.all() cts = {} for ct in content_types: model = ct.model_class() _meta = getattr(model, '_meta') if not _meta.proxy and not _meta.auto_created and not _meta.many_to_many: cts[ct.id] = str(_meta.verbose_name) This dictionary is then fed to javascript and a select box is generated. The problem that I have, is that models are being excluded simply for containing a ManyToManyField. What's the correct way to identify a through model if not many_to_many? -
How can I fix Page loading along with the preloader?
I have created a preloader here but am having a hard time since the page is displaying along with the preloader. I want only the preloader to show then the other elements after the preloader fades.The preloader is fading out perfectly. Here is the element I want to display after the preloader [![<div class="row "> <div class="col-md-10 offset-1"> <div class="card"> <div class="card"> <h5 class="card-header">Featured</h5> <div class="card-body"> <h5 class="card-title">Special title treatment</h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </div> </div>][1]][1] Here is the Javascript part <script src="{% static 'user/js/jquery-3.5.1.min.js' %}"></script> <script> $( document ).ready(function(){ $('.row').hide(); $('.pre-loader').fadeIn('slow', function(){ $('.pre-loader').delay(2500).fadeOut(); $('.row').show(); }); }); </script> {% endblock %} -
Saving foreign key from form
I have an Order model and an Address model. Address is a foreign key on an Order. I would like to save an Address object to the Order object when an order goes through checkout. order.complete and order.transaction_id both work, but order.address does not link an address to an order. Printing address returns Address object (16) relevant code: address = Address.objects.create( customer = customer, name = request.POST.get('name'), line_1 = request.POST.get('line_1'), line_2 = request.POST.get('line_2'), state = request.POST.get('state'), postal_code = request.POST.get('postal_code'), country = request.POST.get('country') ) order.transaction_id = charge.id order.address = address # this is the line that doesn't work order.complete = True order.save() models: class Address(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=200) line_1 = models.CharField(max_length=200) line_2 = models.CharField(max_length=200, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) country = CountryField(null=True, blank=True) postal_code = models.CharField(max_length=15, null=True, blank=True) class Meta: verbose_name_plural = "addresses" class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) class Meta: verbose_name_plural = "orders" -
How to filter a django OR query correctly
I tried to make an OR query with django q. But the number of results is differnt to filter in single queries: //result is 7 len(Project.objects.filter(Q(moderator='A') | Q(participant='B'))) //result is 6 len(Project.objects.filter(Q(moderator='A'))) //result is 0 len(Project.objects.filter(Q(participant='B'))) since the third query responses a empty queryset, I expect the same results with first and second query. What is here the problem? -
How to get a django field value throw a custom models.Field?
I have a custom field: class MyCustomTextField(models.Field): (...) and use that on my model: class MyModel(): encrypted_password = MyCustomTextField(null=True) password_seed = models.TextField(null=True) I need when I use MyModel to grab encrypted_password, I need to grab first password_seed and return a new value using the password_seed value. How can I do that, since custom model is instantiate before the data comes to the model?