Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create dynamic graphene arguements class
Just started using graphene for my backend, I have three types of users, they all have username, email and user_type as required, but the rest are optional. Instead of of creating 3 mutation classes, I'm trying to implement just one generic CreateUser Class My current implementation is: class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: # user = graphene.ID() email = graphene.String(required=True) password = graphene.String(required=True) user_type = graphene.String(required=True) first_name = graphene.String() last_name = graphene.String() street_address = graphene.String() city = graphene.String() state = graphene.String() zip_code = graphene.Int() date = graphene.Date() ... #so on def mutate(self, info, email, password, user_type, **kwargs): user = CustomUser.objects.create( username=email, email=email, user_type=user_type, password=password, ) ... # code where I use kwargs return CreateUser(user=user) QUESTION: Is there a way to create the class Arguments: dynamically at runtime? -
Optimal coding in django
I have been asked which of the following methods is more optimal? I want to show the best-selling and latest products to users.In method A, I query the database twice. In method B, I only query product models once, and in the template, I use filters to display the best-selling and newest. Is the second method more logical and better than the first method? I have been asked which of the following methods is more optimal? I want to show the best-selling and latest products to users.In method A, I query the database twice. In method B, I only query product models once, and in the template, I use filters to display the best-selling and newest. Is the second method more logical and better than the first method? A : def home(request): create = Product.objects.all().order_by('-create')[:6] sell = Product.objects.all().order_by('-sell')[:6] return ... B: def home(request): products = Product.objects.all() return ... my template: for sell: {% for product in products|dictsortreversed:'sell'|slice:":8" %} -------------------- for create : {% for product in products|dictsortreversed:'create'|slice:":8" %} -
Django AJAX form and Select2
I am rendering a form on to my site with AJAX (view below) def add_property_and_valuation(request): """ A view to return an ajax response with add property & valuation form """ data = dict() form = PropertyForm() context = {"form": form} data["html_modal"] = render_to_string( "properties/stages/add_property_and_valuation_modal.html", context, request=request, ) return JsonResponse(data) The form and modal render on button click with the following JQuery code: $(".js-add-property").click(function () { var instance = $(this); $.ajax({ url: instance.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#base-large-modal").modal("show"); }, success: function (data) { $("#base-large-modal .modal-dialog").html(data.html_modal); } }); }); The issue I am having is that I am trying to use Select2 and because the form is being rendered after the DOM has loaded Select2 isn't working. Does anyone have a way to work around this? Watch for the DOM to change and enable Select2? Many thanks -
How to run an asynchronous curl request in Django rest framework
How to run an asynchronous curl request in Django rest framework. The request should be running background. my code is like: def track(self, appUserId, appEventName, appEventData): asyncio.run(self.main(appUserId, appEventName, appEventData)) async def main(self, appUserId, appEventName, appEventData): async with aiohttp.ClientSession() as session: tasks = [] task = asyncio.ensure_future(self.sendData(session, { "userId": self.appUserIdSandbox if (self.sandBoxEnabled == True) else appUserId, "eventName": appEventName, "eventData": appEventData })) tasks.append(task) task_count = await asyncio.gather(*tasks) async def sendData(self,session, appEventData): response = {} payload = json.dumps(appEventData) headers = { "Authorization": self.__authKey, "Cache-Control": "no-cache", "Content-Type": "application/json", } async with session.post(self.__apiUrl, headers=headers, data=payload) as response: result_data = await response.json() return response -
Can you containerize different django applications belonging to a single project in different docker containers?
So basically, I have three different modules or apps in a single django project - These are registration application (registers the user), login application (login), status application (retrieves the data and displays the currently online users). I use redirects to redirect from one template to another such that the registration page will redirect to the login html page and so on. I have kept all the html files in a template folder. I have a common project for all these applications. I want to containerize each of these applications in to a single container, such that I would have three different containers but I am having troubles in understanding how the redirects would work? As these applications are interacting with each other, how would I be doing this? I would implement the databae on AWS or GCloud. -
How to add multiple language to Django project?
I am adding a second language to my Django website but when I chose the second language nothing changes. settings.py # provide a list of language which your site support LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('en', 'English'), ('ar', 'Arabic'), ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # List where django should look into for django.po LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale'), ] urls.py from django.conf.urls.i18n import set_language from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from django.conf import settings urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls), path('', include('company.urls')), path('', include('core.urls')), path('', include('movement.urls')), path('', include('warehouse.urls')), path('setlang/', set_language, name='set_language'), path('', include('maintenance.urls')), path('', include('reporters.urls')), path('', include('accounts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html {% load i18n static %} {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <div class="btn-group"> <button type="button" class="btn dropdown-toggle dropdown-icon" data-toggle="dropdown"> <i class="fa fa-language"></i> </button> <div class="dropdown-menu" role="menu"> {% for language in languages %} {% if language.code != LANGUAGE_CODE %} <a class="dropdown-item" href="{% url 'set_language' %}" class="dropdown-item" data-language-code="{{ language.code }}"> {{ language.name_local }} </a> {% endif %} {% endfor %} </div> </div> I also run these command py manage.py … -
Django: migrate subapp model.py file
My issue is the following. How to migrate a the models in models.py file that is not the automatically generated with django-admin startapp appname I have made a simple directory that illustrates my issue: example_app ├── app.py ├── models.py ├── tenants │ └── tenant1 │ ├── models.py │ └── tenant1_views.py ├── tests.py └── views.py so what I want is to migrate what is inside of tenant1.models.py I have not found any clue on how to achieve this, does anyone know? -
VScode autocomplete not working after using sshfs to mount a directory inside the workspace
I’m using VScode to develop a Django web application on the next environment: • OS and Version: Windows 10 • VS Code Version: 1.52.2 • Python Extension Version: v2021.5.842923320 • Remote – SSH Version: v0.65.4 From my Windows laptop, I work on an Ubuntu 20.04 VM using the Remote – SSH plugin, So I have configured a python3.9 virtual environment with Django3.2 and others python packages. Also, I have pylint installed and all works as expected. The issue arises when I mount a folder inside the application media folder (inside the workspace) from another station through sshfs. What happens is that autocomplete stops working and when y press Clr+Space I just get a loading message. Note that this folder that I mount through sshfs is very big more than 1 TB with many files including python scripts and also I note that even when I close the VScode I cannot unmount this folder because the fusermount said that the folder is used by some process (I guess is the VScode process inside the VM). After all, if I don’t open the VScode I'm able to mount and unmount this folder without a problem. I have also excluded this media folder … -
"Ran 0 tests in 0.000s"
I writed a test for my app's project django in my app folder. When i want to run test file give a error . please help to solve this problem. my file test name in my app is '' my code in temp_tests_file file: from django.test import TestCase from .models import Author,Book from MyProj.forum.tests import SimpleTest import datetime class Author_Tests(TestCase): def setUp(self): obj1 = Author.objects.create(first_name='Brayan',last_name='Trisi',date_of_birth=datetime.date(2005, 5, 12),date_of_death=datetime.date(2020, 5, 12)) obj2 = Author.objects.create(first_name='Rayan',last_name='Blair',date_of_birth=datetime.date(2000, 5, 12),date_of_death=None) obj3 = Author.objects.create(first_name='Mahmoud',last_name='Sameni',date_of_birth=datetime.date(1995, 8, 13),date_of_death=None) obj4 = Author.objects.create(first_name='Alex',last_name='Denizli',date_of_birth=datetime.date(1500, 8, 20),date_of_death=datetime.date(1990, 1, 1)) def test_is_alive(self): br = Author.objects.get(first_name='Brayan') ra = Author.objects.get(first_name='Rayan') ma = Author.objects.get(first_name='Mahmoud') al = Author.objects.get(first_name='Alex') self.assertFalse(br.is_alive()) self.assertTrue(ra.is_alive()) self.assertTrue(ma.is_alive()) self.assertFalse(al.is_alive()) def test_get_age(self): br = Author.objects.get(first_name='Brayan') ra = Author.objects.get(first_name='Rayan') ma = Author.objects.get(first_name='Mahmoud') al = Author.objects.get(first_name='Alex') da = datetime.date.today() self.assertEqual(da - ra.date_of_birth, datetime.timedelta(days=7694)) self.assertEqual(br.date_of_death - br.date_of_birth, datetime.timedelta(days=5479)) self.assertEqual(da - ma.date_of_birth, datetime.timedelta(days=9429)) self.assertEqual(al.date_of_death - al.date_of_birth, datetime.timedelta(days=178738)) class Book_Tests(TestCase): def setUp(self): obj1 = Author.objects.create(first_name='Brayan',last_name='Trisi',date_of_birth=datetime.date(2005, 5, 12),date_of_death=datetime.date(2020, 5, 12)) obj2 = Author.objects.create(first_name='Rayan',last_name='Blair',date_of_birth=datetime.date(2000, 5, 12),date_of_death=None) obj3 = Author.objects.create(first_name='Mahmoud',last_name='Sameni',date_of_birth=datetime.date(1995, 8, 13),date_of_death=None) obj4 = Author.objects.create(first_name='Alex',last_name='Denizli',date_of_birth=datetime.date(1500, 8, 20),date_of_death=datetime.date(1990, 1, 1)) ### ob1 = Book.objects.create(title='Bitcoin',author=Author.objects.get(first_name='Brayan'),summary='Anything about bitcoin',date_of_publish=datetime.date(1998, 12, 5)) ob2 = Book.objects.create(title='litecoin',author=Author.objects.get(first_name='Rayan'),summary='Anything about litecoin',date_of_publish=datetime.date(2012, 8, 1)) ob3 = Book.objects.create(title='Teter',author=Author.objects.get(first_name='Mahmoud'),summary='Anything about Teter',date_of_publish=datetime.date(2015, 8, 1)) o4 = Book.objects.create(title='Doge',author=Author.objects.get(first_name='Alex'),summary='Anything about Doge',date_of_publish=datetime.date(2019, 1, 17)) o5 = Book.objects.create(title='Dollar',author=Author.objects.get(first_name='Alex'),summary='Anything about Dollar',date_of_publish=datetime.date(1568, 4, … -
Django forms with CSRF protection in IOS 14+
IOS 14 came out few months ago, which defaults to blocking all third party cookies unless the user enables them specifically by disabling this option: Settings -> Safari -> Prevent Cross-site Tracking This presents a problem for Django forms with csrf protection that is served inside an <iframe> from a third-party domain like this: -----Parent website----- | | | ----------------- | | | | | | | Django form | | | | inside | | | | iframe | | | | | | | ----------------- | | | ------------------------- Django form sets a csrfmiddlewaretoken as a hidden form variable and also sets a cookie called csrftoken, and does the form security verification when the form is submitted. The problem comes when attempting to set the cookie csrftoken while inside an <iframe>, being in a third-party website context. In IOS 14, this cookie is rejected. The form still submits without this cookie but django rejects the form as expected. The exact error I am getting: Forbidden (CSRF cookie not set.), which is correct from django's point of view. The form works correctly when we disable the Safari setting, to allow cross-site tracking. But this needs to be done at … -
leaflet dynamic map generation in django templates
I am pretty novice in javascript and django. I am trying to figure out this scenario. My models are like these: class Post(models.Model): plan = models.ForeignKey(Plan, to_field='id', on_delete=models.CASCADE, blank=True) user = models.ForeignKey(Company_User, to_field='id', on_delete=models.CASCADE, blank=True) creation_date = models.DateField(default=timezone.now) modification_date = models.DateField(default=timezone.now) title = models.CharField(max_length=85) description = models.TextField() gps_path = models.TextField() class Marker(models.Model): post = models.ForeignKey(Post, to_field='id', on_delete=models.CASCADE, blank=True) lat = models.FloatField() long = models.FloatField() img = models.TextField() classes = models.CharField(max_length=100) description = models.TextField() repair = models.ForeignKey(Repair_Log, null=True, to_field='id', on_delete=models.CASCADE, blank=True) Then I have a view like this: def viewPostByDate(request): if not request.session.has_key('name'): return redirect('rsca_login') if request.session["type"] != 1 and request.session["type"] != 2: return redirect('rsca_home') elif request.method == 'POST': start_date = datetime.strptime(request.POST.get('start_date'), "%Y-%m-%d").date() end_date = datetime.strptime(request.POST.get('end_date'), "%Y-%m-%d").date() # get all the posts posts = Post.objects.all() company_posts = [] paths = [] posts_markers = [] for post in posts: if post.user.company_id == request.session["company_id"] and start_date <= post.creation_date <= end_date: company_posts.append(post) path = post.gps_path path = path.replace("(", "") path = path.replace(")", "") path = path.split(',') path = [float(i) for i in path] path = to_matrix(path, 2) paths.append(path) context = {'posts': company_posts, 'paths': paths} return render(request, 'rsca/view_post_on_map_by_date_2.html', context) Here paths is an array of 2D matrices where each row is a gps lat and … -
How to add Blog replay in django?
Hello I am new in django. I created an comment system where user can post comment. Now I want to add replay to my comment. How to automatically select parent comment in my html replay froms?. here is my code: views.py class BlogDetail(DetailView): model = Blog template_name = 'blog_details.html' def get(self,request,slug): blog = Blog.objects.get(slug=slug) queryset = BlogComment.objects.filter(is_published="0",blog=blog) form = CommentFrom() context = {'form':form, 'blog':blog, 'queryset':queryset } return render(request,'blog_details.html',context) def post(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.save() messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return redirect(reverse('blog-detail', kwargs={'slug':slug})) else: form() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) #models.py class BlogComment(MPTTModel): blog = models.ForeignKey(Blog,on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') sno = models.AutoField(primary_key=True) author = models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=250) email = models.EmailField(max_length=2000) comment = models.TextField(max_length=50000) created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) updated_at = models.DateTimeField(auto_now=True,blank=True,null=True) CHOICES = ( ('0', 'published',), ('1', 'pending',), ('2', 'rejected',), ) is_published = models.CharField( max_length=1, choices=CHOICES,default='1' ) right now I can only add replay form my django admin panel by selecting parent comment. I want to add replay through my html replay froms. somethings like this: -
What is a NoReverseMatch error, and how can I solve it?
I'm making an Online shop using Django and trying to add quantity of each product from cart and it throws the error under : AttributeError at /order/add_cart_pro 'Order' object has no attribute 'order' What can I do and how can I solve it? this is my views : def add_cart(request) : pnum = request.GET.get("pnum") cart = Order.objects.get(prod_num_id = pnum) cart.save() # save 호출 return redirect( "add_cart_pro" ) def add_cart_pro(request): memid = request.session.get( "memid" ) cart = Order.objects.filter(order_id_id = memid) member = Sign.objects.get(user_id = memid) pnum = request.GET.get("pnum") template = loader.get_template("cart_view.html") for add in cart : cart += add.order.quan + 1 context = { "memid":memid, "cart":cart, "member":member, "pnum":pnum, } return HttpResponse( template.render( context, request ) ) -
How to Sort Nested QuerySet Objects using time stamp
I am new to Django restframework. I have an api, where I have to sort comments based on their of create.A comment can have multiple child comments in line. Whenever a comment(either child or parent) is created,that family should be displayed first. But ,I could able to sort only first layer of json as per timestamp. but I need to sort even by considering child created time ,and display that family firs. A sample Json is given for reference. [ { "id": 75, "comment_category": "technical", "comment": "", "x": null, "y": null, "children": [ { "id": 78, "comment": "Techni/..'\r\n.", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T10:07:28.281312Z", "time_since": "9 minutes ago" } ], "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:22:57.027836Z", "time_since": "53 minutes ago" }, { "id": 74, "comment_category": "technical", "comment": "Technical", "x": null, "y": null, "children": [ { "id": 76, "comment": "", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:23:32.079769Z", "time_since": "53 minutes ago" }, { "id": 77, "comment": "", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:37:41.266583Z", "time_since": "39 minutes ago" }, { "id": 79, "comment": "techhhhhhhh", "is_parent_comment_resolved": false, "timestamp": "2021-06-07T10:13:00.016222Z", "time_since": "3 minutes ago" } ], "is_parent_comment_resolved": false, "timestamp": "2021-06-07T09:22:34.390586Z", "time_since": "54 minutes ago" }, { "id": 74, "comment_category": "technical", "comment": "Technical", "x": null, "y": null, "children": [ { "id": 76, "comment": "", … -
Jinja template inherited but not able to modify it on other files
This is my base.html: {%load static%} <!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"> </head> <body> <style>/* Add a black background color to the top navigation */ .topnav { background-color: rgb(10, 113, 145); overflow: hidden; } /* Style the links inside the navigation bar */ .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* Change the color of links on hover */ .topnav a:hover { background-color: #ddd; color: black; } /* Add a color to the active/current link */ .topnav a.active { background-color: #04AA6D; color: white; } </style> <div class="topnav"> <a href="/">Home Page</a> <a href="/projects">Projects</a> <a href="/contact">Contact</a> </div> </body> </html> this is my projects.html: {% extends "important/base.html" %} {% block content %} <h1>Projects</h1> {% endblock content %} Iam not able to see anything on my projects pae even I did everything correctly this is my settings.py: INSTALLED_APPS = [ 'important', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Is there anything that I can change in this to make it work? please help … -
pymemcache with pickle django
I was trying to cache a Django model Instance like class MyModel(models.Model): ... several atributes, as well as foreign key attributes ... from pymemcache.client import base import pickle obj = MyModel.objects.first() client = base.Client(("my-cache.pnpnqe.0001.usw2.cache.amazonaws.com", 11211)) client.set("my-key", pickle.dumps(obj), 1000) # 1000 seconds # and to access I use obj = pickle.loads(client.get("my-key")) They both works fine, but sometimes executing the same line: client.get("my-key") generates very very strange errors like Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 791, in _extract_value key = remapped_keys[key] KeyError: b'some-other-cache-key' and sometimes I get: Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 833, in _fetch_cmd raise MemcacheUnknownError(line[:32]) and sometimes I get Traceback (most recent call last): File "/opt/python/current/app/proj/utils/Cache.py", line 93, in get_value return Cache.client.get(key, None) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 481, in get return self._fetch_cmd(b'get', [key], False).get(key, default) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 823, in _fetch_cmd prefixed_keys) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 790, in _extract_value buf, value = _readvalue(self.sock, buf, int(size)) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pymemcache/client/base.py", line 1234, in … -
Assigning same integer to specific string for table in database
I'm gathering errors to the table SystemErrors which now looks like this id error_msg system_id 1 error1 1123 2 error1 341 3 error2 1415 The message of errors though is too long, so i need another column to the later verification which error it is. And i want in the same table another column which will be connected with Error column. If the row with error1 is added, i want column error_id with integer 1. Like this id error_msg error_id system_id 1 error1 1 38 2 error1 1 112 3 error2 2 323 Now my code looks like this class SystemError(models.Model): report = models.ForeignKey(SystemReport, on_delete=models.CASCADE) error_msg = models.CharField(max_length=2000) Can i do this in this table by assigning any connection with error_msg -
Bokeh chart overflowing its div container
I am embedding a bokeh chart into a Django app template. Below is the template: home_board.html {% extends "base.html" %} {% load static %} {% block title %}Home-Board{% endblock %} {% block content %} <link href="{% static "css/home_board.css" %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bokeh/2.3.2/bokeh.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bokeh/2.3.2/bokeh-widgets.min.js"></script> <div id="nav-bar">&nbsp; </div> <div id="side-bar"> <button id="home-button" class="side-bar-button">Home</button> </div> <div id="content-container"> <div id="chart-container"> {{ div | safe }} </div> </div> {{ script | safe }} {% endblock %} Here is the view where the chart is created: def home_board(request): ... p = figure(x_axis_type="datetime", tools="", plot_width=300, plot_height=300, title=title,) p.xaxis.major_label_orientation = pi / 4 p.toolbar.logo = None p.grid.grid_line_alpha = 0.3 p.segment(source.date, source.high, source.date, source.low, color="black") p.vbar(source.date[increasing], w, source.open[increasing], source.close[increasing], fill_color="#D5E1DD", line_color="black") p.vbar(source.date[decreasing], w, source.open[decreasing], source.close[decreasing], fill_color="#F2583E", line_color="black") script, div = components(p) return render(request, 'homeboard/home_board.html', {'script': script, 'div': div}) However, this chart appears as overflowing outside of the chart-container div, overlapping with the nav-bar and the side-bar div elements. I don't think it is an CSS problem. How do I configure the chart so it sits squarely in the div that it is under? -
How to in Model.objects.get give attribute name?
I need choose which attribute i use for id getting. def get_object_id(attribute, attribute_value): URL.objects.get(attribute=attribute_value) -
Why my for i in range loop is not working? [closed]
I came into similar problem. Is for b in bottomwear not working? As there wasn't glown on syntax loop line. Is there a problem on loop on my home.html file? enter image description here -
Programming Error: With PhoneNumberField in Django
After pip install phone number field on global as well as in virtual env and importing in the models.py I am facing programming error. Details are as follows DB is POSTGRESQL models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Agent(models.Model): agency_name = models.CharField(max_length=200) prop_name = models.CharField(max_length=30) agency_address = models.CharField(max_length=300) agency_city = models.CharField(max_length=50) agency_country = models.CharField(max_length=50) email_address = models.EmailField(max_length=50) contact_nu = PhoneNumberField() def __str__(self): return self.agency_name admin.py @admin.register(Agent) class AgentAdmin(admin.ModelAdmin): list_display = ('agency_name', 'prop_name', 'agency_address', 'agency_city', 'agency_country', 'email_address', 'contact_nu') Error: [07/Jun/2021 09:52:34] "GET /admin/ HTTP/1.1" 200 5546 Internal Server Error: /admin/rk003/agent/ Traceback (most recent call last): File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column rk003_agent.contact_nu does not exist Thanks -
Django session_key not working in React app
views.py: @api_view(['GET']) def addToCartForSession(request, pk): product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'ok'}) models.py: class Cart(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) session_key = models.CharField(max_length=200, blank=True) product = models.ManyToManyField(Product, related_name='product_items', blank=True) urls.py: path('addToCartForSession/<str:pk>/', views.addToCartForSession, name='addToCartForSession'), if I go to this http://127.0.0.1:8000/addToCartForSession/8/ url directly from browser search bar, session_key works fine. But it I try to access this url from my React app, it shows server error. Reactjs: addToCart=()=>{ var id = this.props.id var url2 = 'http://127.0.0.1:8000/addToCartForSession/'+id+'/' fetch(url2,{ method:'GET', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrftoken } }).then(res=>res.json().then(result=>{ if(result.response === 'ok'){ this.props.dispatch({ type: 'itemInCart', }) this.setState({addedToCart: true}) } })) } Can you tell me, how can I use session_key in Django-rest_framework? yesterday I asked 3/4 question about this problem, but no one could answer this. -
how to change color from red to green if mobile verification status converted from unverified to verified?
from last few hours i have been finding the solution for below question and had spent lot of time but couldn't find the one. I am currently working on one project(based on django) which has a user profile where users can verify their mobile number. I am using twilio for that. what i want is when a user go to his/her profile then there should be a option of "verify your mobile number" right below to the mobile number field which will be in red color, as soon as the user verify his/her mobile number via some backend django(python) stuff and come back to profile page again, that message should be "verified"(in green color). i want css and javascript code to achieve that because for sms verification and all the backend stuff i already have the code. Any kind of help would be appreciated... -
How can i use influxdb in django project
i have some trouble about influxdb+django configurations. Firstly let me summarize my situation. I have an influxdb which is already collecting data from endnode(sensors). Data is transfering by LoraWan technology. I can read that datas from terminal by writing flux queries so database is working without any problem. Now my second phase of this project is visualizing that datas on an web page. I am using django framework for that i completed the frontend parts nearly. I looked on internet for the configurations for influxdb on django but i couldnt handle it. In django documentation page they are listed some databases like below: Django officially supports the following databases: PostgreSQL MariaDB MySQL Oracle SQLite How will i use/configure and get data from my influxdb ? Is it possible ? What are the alternative solutions. -
How to enforce automatic timestamp for django model in database level?
I have a django abstract model that goes like this: class AbstractAppendOnly(models.Model): created_at = models.DateTimeField(auto_now=True, editable=False) db_note = models.TextField(default=None, null=True) class Meta: abstract = True This model is extended to multiple other models so that a create_at field is automatically added to all of those. Now when an object is created and saved from django server end the created_at timestamp field is automatically produced, as expected. But it does not enforce it in database level, so anyone can insert a row with fake created_at value. As far as I am concerned django does not let user to set database level default value for model issue-470. What I have found that may solve the issue - I have found an way to customize the migration files using tool like django-add-default-value . But since migrations may sometimes needed to be pruned in big systems and we will have to write customized migrations every time we create a new model, it seems of huge error-prone. Another way I have thought of is to add trigger using django-pgtrigger like this @pgtrigger.register( pgtrigger.Trigger( name='insert_auto_created_at_timestamp', operation=pgtrigger.Insert, when=pgtrigger.Before, func=''' new.created_at = now(); return new; ''' ) ) class AbstractAppendOnly(models.Model): created_at = models.DateTimeField(auto_now=True, editable=False) db_note = models.TextField(default=None, null=True) …