Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference in API Calls in Production and Development?
Background: I have a backend server of a personal project, which makes call to a Third Party API. I have made this call in my own server instead of the React Front-End to avoid the CORS Error. Problem: When the backend is in Development, and the API call is done, it returns Correct Data. But once hosted, the API returns Incorrect Data. By Incorrect, I mean response is of same format, but main content required (which is a URL) is incorrect. I wanted to more about what difference is between the two API calls my server does, one in localhost and the other in Production. What I have figured out yet: I have used different hosting services, Heroku and Vercel, so, the Host is probably not the problem here. I have created the backend in two Tech Stacks, Django and Node - Express, so that also checks out, as both return same incorrect Data in Production, whereas, both return Correct Data in Development. Hence, I wanted to know about what data does API calls send over as request headers etc. and the difference between them when done in Development and Production. Here's the Express Code: const express = require('express'); const … -
My template is not rendering the form as method='post' (Django template)
I was implementing a search functionality for a college web site. The problem is when i submit my form it's always sends a get request instead of post request . I've done every test as i can , but did't find a way out of this . Please help me to fix why the form is not sending a post request. The view, The form: , when i inspect in browser , The request logs when i submit the form -
Django-CMS : Unexpected keyword argument 'providing_args'
I have installed a vanilla django-cms on a new server. I installed all requirements. It all went fine, up untill the point where I wanted to migrate to the database (Postgres). So this is what I did : Tried reinstalling and installing it all again. Didn't change it. Used google to try and find people with the same error. Try editing the signals file on which the error(shown below) fires, but that meant rewriting it all, which still made it unresponsive. Traceback: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/websites/fl/flvenv/lib/python3.8/site-packages/django/core/management/_ _init__.py", line 425, in execute_from_command_line utility.execute() File "/websites/fl/flvenv/lib/python3.8/site-packages/django/core/management/_ _init__.py", line 401, in execute django.setup() File "/websites/fl/flvenv/lib/python3.8/site-packages/django/__init__.py", lin e 24, in setup apps.populate(settings.INSTALLED_APPS) File "/websites/fl/flvenv/lib/python3.8/site-packages/django/apps/registry.py" , line 114, in populate app_config.import_models() File "/websites/fl/flvenv/lib/python3.8/site-packages/django/apps/config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/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 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/websites/fl/flvenv/lib/python3.8/site-packages/cms/models/__init__.py", line 12, in <module> from cms import signals as … -
Django serializer doesn't save in db
i want to save a model in the sqlite test-db but the saved result is an empty row in the db with the auto incremened index of the row. the rest of the row is NULL. i spended a lot of time to solve the problem but i have found nothing . after the method call save() the data is gone -> see print below. its clear that the response throws this error - i thougt the dictObj will be converted automatically in a json. and i bet when the serilized.data has the correct form of the object it will work. Here is the code: class Hopper(models.Model): # Relationships id = models.IntegerField open_positions_count = models.TextField name = models.TextField exchange = models.TextField hopper_id = models.TextField subscription_id = models.TextField plan_id = models.TextField payment_term = models.TextField payment_method_id = models.TextField ... # shortened class HopperSerializer(serializers.ModelSerializer): class Meta: model = Hopper fields = ['id', 'open_positions_count', 'name', 'exchange', 'hopper_id', 'subscription_id', 'plan_id', 'payment_term', 'payment_method_id', ... # shortened ] The Views.hopper gets the hopperObject as a jsonObject: @api_view(('POST', 'GET')) @csrf_exempt def hopper(request): if request.method == 'POST': data = request.data serializer = HopperSerializer(data=data) print(serializer.initial_data) if serializer.is_valid(): serializer.save() print(serializer.initial_data) print(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) # Throws -> TypeError: Object of type … -
Use a variable that can be accessed by two functions in views.py - Django
I am making a post and get API call to a third-party application using requests.post and requests.get respectively. The POST request is to authenticate and get the token and the get request is to use the token and access data from the third-party application. My code snippet : class Robot(APIView): common_var="" def post(self, request, *args, **kwargs): res = requests.post(API,headers=header,data=body) res=res.json() common_var=common_var+res['t'] def get(self, request, *args, **kwargs): header={'Authorization': common_var} payload = {'$top': '3','$filter':"abs"} res = requests.get(url, params=payload,headers=header) res=res.json() return Response(res, status=status.HTTP_200_OK) I am not able to access the "common_var" inside get() method. I sthere an alternative method to do this? Thank you -
AttributeError: 'Clients' object has no attribute 'is_authenticated' in django-restframework
I want to implement custom client authorization in Django-restframework project but I face the following error: File "D:\Projects\Python Projects\blog_posts\backend\venv\lib\site-packages\rest_framework\permissions.py", line 137, in has_permission return bool(request.user and request.user.is_authenticated) AttributeError: 'Clients' object has no attribute 'is_authenticated' [15/Dec/2021 17:10:23] "GET /api/admin/postList HTTP/1.1" 500 102946 I want to implement this authorization as a global rule for my project. Here I'm stuck here please help me out from this problem... I'm using: Django==3.2.9 djangorestframework==3.12.4 I'm getting the client id from the client request header as like: from users.models import Clients from rest_framework import authentication from rest_framework import exceptions from rest_framework import permissions class ClientAuthentication(authentication.BaseAuthentication): def authenticate(self, request): clientID = request.headers.get('client') print("client id: ", clientID) if not clientID: # no username passed in request headers raise exceptions.AuthenticationFailed('Client ID is Required') try: client = Clients.objects.get(id=clientID) # get the client id except Clients.DoesNotExist: # raise exception if user does not exist raise exceptions.AuthenticationFailed('Client ID is Not Valid') return (client, None) # authentication successful My setting.py config file is like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # custom apps adding from here... 'blog', 'blog_api', "rest_framework", "corsheaders", "users", # authentication apps "rest_framework_simplejwt.token_blacklist", ] # django rest-framework settings... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'core.authorization.ClientAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': … -
TypeError: '_SentinelObject' object is not callable
I am upgrading my Django application from version 2.2 to 3.2. while upgrading i am facing below issue, i have spent a lot of time to resolve this but didn't get any solution yet. here's the traceback of issue which i am facing: File ".../abc/test.py", line 85, in setUp self.MODEL_A.save() File ".../abc/models.py", line 470, in save super(MODEL_A, self).save(*args, **kwargs) File ".../lib/python3.8/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File ".../lib/python3.8/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File ".../lib/python3.8/site-packages/django/db/models/base.py", line 842, in _save_table values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False))) File ".../lib/python3.8/site-packages/django/db/models/base.py", line 842, in <listcomp> values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False))) File ".../lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1396, in pre_save value = timezone.now() TypeError: '_SentinelObject' object is not callable Any help would be highly appreciated. Thanks in advance. -
SQL/DJANGO query cannot make left JOIN
Previous SQL Related Reference To my Question Heres My model.py: class Product(models.Model): product_name = models.CharField(max_length=500) ... class Meta: managed = False db_table = 'product' class Stock(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_id') quantity = models.IntegerField() ... class Meta: managed = False db_table = 'stock_50644' Im doing this simple query: queryset = Product.objects.all().order_by('stock__quantity') print(len(queryset)) and getting django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') When i print(queryset.query) Its always left join (product to stock) that getting stuck. What could possibly be problem here? -
javascript isn't reading correctly a static json file
I have been working on a project, where I have to get data from a database with its own server. For that I have used Django as a tool to combine both backend and frontend. Also I created a function that connect python to odbc so I can get the information from the database. My logic was that I want to convert all the information into JSON file, so that javascript (frontend) would have acccess to it to convert it into graphs. To make myself more clear, here are the main components: views.py def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TextForm(request.POST) # check whether it's valid: if form.is_valid(): # From this we get the result of POST method date = form.cleaned_data['date'] splitdate = date.split(sep='-') # Here we call the class created in Functions.py x = GetData(int(splitdate[2]), int(splitdate[1]), int(splitdate[0])) x.getInfo() context = { 'text': date, 'form': form, } return render(request, 'index.html', context) # if a GET (or any other method) we'll create a blank form else: form = TextForm() return render(request, 'index.html', {'form': … -
Users are not added to the database in Django [closed]
I am trying to create an extend User model but when I register a new account, it is not displayed in the admin panel and the users table itself is not. How to fix it? Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users … -
Unable to start server due Templates issues
hi all, I tried to build Django page using this post: djangocentral.com/building-a-blog-application-with-django/ Seems I completed all steps but I am getting this error when running server. Do you know what can be reason for error message I am getting? TemplateDoesNotExist at / index.html, blog/post_list.html Request Method: GET Request URL: http://127.0.0.1:8080/ Django Version: 3.2.9 Exception Type: TemplateDoesNotExist Exception Value: index.html, blog/post_list.html Exception Location: C:\Download\Development\NowaStrona_Django\lib\site-packages\django\template\loader.py, line 47, in select_template Python Executable: C:\Download\Development\NowaStrona_Django\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\\Download\\Development\\NowaStrona_Django\\mysite\\my_site', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts\\python37.zip', 'C:\\Download\\Development\\NowaStrona_Django\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django\\lib', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts', 'c:\\program files (x86)\\python37-32\\Lib', 'c:\\program files (x86)\\python37-32\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django', 'C:\\Download\\Development\\NowaStrona_Django\\lib\\site-packages'] Server time: Wed, 15 Dec 2021 10:54:46 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\T\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\E\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\M\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\P\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\L\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\A\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\T\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\E\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\S\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\_\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\D\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\I\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\R\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\S\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Download\Development\NowaStrona_Django\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: … -
How do I dynamically filter fields returned in django rest api get request based on the user making the request?
I have a photoshoot api that allows photographers to post shoot photos from which preview and watermarded versions are derived. Editors and clients can both select which photos will be edited, but the editor should only see the preview without watermark and the clients should only see the watermarked versions. I was wondering how these different distincitons can be made in the DRF queryset. My model: class Unedited(models.Model): shoot = models.ForeignKey( Shoot, on_delete=models.CASCADE, null=True, related_name="shoot_photo" ) original = models.ImageField(null=True, blank=False, upload_to=shoot_upload_to) preview = models.ImageField(null=True, blank=True, upload_to=shoot_upload_to) watermarked = models.ImageField(null=True, blank=True, upload_to=shoot_upload_to) upload_time = models.DateTimeField(auto_now_add=True) My Serializer: class UneditedSerializer(serializers.ModelSerializer): class Meta: model = Unedited fields = "__all__" def create(self, validated_data): validated_data["preview"] = reduce_resolution(validated_data["original"]) validated_data["watermarked"] = add_watermark(validated_data["preview"]) img_obj = Unedited.objects.create(**validated_data) img_obj.save() return img_obj My view: class UneditedViewSet(viewsets.ModelViewSet): if not TESTING: permission_classes = (PhotosPermission,) serializer_class = UneditedSerializer def get_queryset(self): return Unedited.objects.filter(**self.request.query_params) -
Unable to run vscode's debugger with dockerized django project
Every time when I run a debugger there happen many things but not what I expect. I'm running a project with docker-compose up Checking the localhost if backend backend is okay. It's down. What's funny the container is running because I'm attached to this with vscode's remote containers. The debugpy library is installed. The first approach to run a debugger end with such info in debug console: Attached! System check identified some issues: WARNINGS: workflow.State.additional_values: (fields.W904) django.contrib.postgres.fields.JSONField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use django.db.models.JSONField instead. Operations to perform: Apply all migrations: accounts, auth, contenttypes, files, mambu, otp_totp, sessions, token_blacklist, workflow, zoho Running migrations: No migrations to apply. and it's down. Backend is also down. Second try: Attached! System check identified some issues: WARNINGS: workflow.State.additional_values: (fields.W904) django.contrib.postgres.fields.JSONField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use django.db.models.JSONField instead. Zoho Configuration failed, check that you have all variables ZOHO_TOKEN_URL, ZOHO_REST_API_KEY, ZOHO_CURRENT_USER_EMAIL and it's down but backend is up - I'm able to login etc. The third try ends with such an error connect ECONNREFUSED 127.0.0.1:5678. Any tips? Code: manage.py #!/usr/bin/env python """Django's command-line … -
how can i search in django for multiple values like the ( werkstoffbezeichnung and the werkstoffnummer )
This cod I made only works for one values, when I try to add other one it stops working. how can i fix it? def search_post(request): if request.method == "POST": searched = request.POST.get('searched') posts = Post.objects.filter(werkstoffnummer=searched) posts = Post.objects.filter(werkstoffbezeichnung=searched) return render(request, 'Blog/search_post.html', {'searched': searched, 'posts': posts}) else: return render(request, 'Blog/search_post.html', {}) -
Django - How can I restrict a url access basing on the environment where the app is running
I have the local and staging environment which I set using DJANGO_SETTINGS_MODULE. I want this URL to only be accessible in the staging environment. How can I know that the current environment is staging and restrict the URL to it. Here is my url path("testing_page/", views.testing_page_view, name="testing_page"), The staging base url is https://myapp-staging.domain.com/ The view is def testing_page_view(request): if request.method == "GET": return render(request, "testing_page.html") else: values = request.POST.dict() return HttpResponseRedirect(login_link) -
Django: Performance issues with query sets using m2m
I have about 1,400,000 rows of Video and Tag through models. There are about 300,000 Videos and 5,000 Tags. Issuing a query set like the one below takes about 500-700ms. #models.py class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, max_length=30) class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField( max_length=300) #queryset Tag.objects.annotate(count=Count("video")).order_by("-count")[:100] Queries issued SELECT "videos_tag"."id", "videos_tag"."name", COUNT("videos_video_tags"."video_id") AS "count" FROM "videos_tag" LEFT OUTER JOIN "videos_video_tags" ON ("videos_tag"."id" = "videos_video_tags"."tag_id") GROUP BY "videos_tag"."id" ORDER BY "count" DESC LIMIT 100 QUERY PLAN ---------------------------------------------------------------------------------------------------- Limit (cost=35140.11..35140.36 rows=100 width=37) -> Sort (cost=35140.11..35153.96 rows=5539 width=37) Sort Key: (count(videos_video_tags.video_id)) DESC -> HashAggregate (cost=34873.02..34928.41 rows=5539 width=37) Group Key: videos_tag.id -> Hash Right Join (cost=173.63..28189.98 rows=1336608 width=45) Hash Cond: (videos_video_tags.tag_id = videos_tag.id) -> Seq Scan on videos_video_tags (cost=0.00..24505.08 rows=1336608 width=32) -> Hash (cost=104.39..104.39 rows=5539 width=29) -> Seq Scan on videos_tag (cost=0.00..104.39 rows=5539 width=29) As far as the execution plan is concerned, I think the cause is that index is not used. How can I improve this? -
Work around for handling CPU Intensive task in aws ec2?
I have created a django application (running on aws ec2) which convert media file from one format to another format ,but during this process it consume CPU resource due to which I have to pay charges to aws. I am trying to find a work around where my local pc (ubuntu) takes care of CPU intensive task and final result is uploaded to s3 bucket which I can share with user. Please note :- I have decent internet connection and computer which can handle backend very well but i not in state to pay throttle charges to aws. Solution :- One possible solution is that when user upload media file (html upload form) it goes to s3 bucket and at the same time via socket connection the s3 bucket file link is send to my ubuntu where it download file, process it and upload back to s3 bucket. Please suggest me better solution as it seems to be not efficient. -
How to use a single axis for labels in chart.js and djang?
How to use a single axis for labels in chart.js and django. I have data from several models that I want to present by ordering them by date on the same canvas chart.js. The X axis represents the number of data by name for each model and the Y axis represents the year of each data for each model. Here is the method I used for tow models but it doesn't work. Models.py class Even1(models.Model): name = models.CharField(max_length=20) description = models.TextField(max_length=250, null=True) date = models.DateField() time=models.TimeField() def __str__(self): return self.name class Even2(models.Model): name = models.CharField(max_length=20) description = models.TextField(max_length=250, null=True) date = models.DateField() time=models.TimeField() def __str__(self): return self.name views.py def even_area_chart(request): labels1 = [] labels2 = [] data1 = [] data2 = [] q1 = Even1.objects.values('date').annotate(date_name=Count('name')).order_by('- date') q2 = Even2.objects.values('date').annotate(date_name=Count('name')).order_by('-date') for rm in q1: labels1.append(rm['date']) data1.append(rm['date_name']) for rm in q2: labels2.append(rm['date']) data2.append(rm['date_name']) return JsonResponse(data={ 'labels1': labels1, 'labels2': labels2, 'data1': data1, 'data2': data2, }) #script <script type="text/javascript"> $(document).ready(function(){ $.ajax({ url: "{% url 'even_area_chart' %}", dataType:"json", type:"GET", contentType:"application/json", success: function(response){ if(response){ var config = { type: 'line', data: { datasets: [{ data: response['data1'], lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", borderColor: "rgb(196,88,80)", pointRadius: 3, pointBackgroundColor: "rgba(78, 115, 223, 1)", pointBorderColor: "rgba(78, 115, 223, … -
Django cant find static(css) folder
My Django template cant seem to find my css file in my static folder which is structured at the root dir. Here is my settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j@g&qm&20_oct_3f*sn-7n117si&1x4+m9cjao%g_&88gtmk9&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'maintenance', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'nitrofleet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', ], }, }, ] WSGI_APPLICATION = 'nitrofleet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # … -
django-treebeard Materialized Path tree depth ended up being zero
I found a problematic node with id 633. tree.find_problems() ([], [], [], [633], [35, 9, 50, 291, 464]) After running tree.fix_tree() It does not find any problems. tree.find_problems() ([], [], [], [], []) But actually 633 is still in some wierd state. >>> node633.depth 0 >>> node633.path '' Problem: node633.depth is 0 which means its not root but it does not have parent as well. Path is empty too. This means my code will try to find parent from a node that does not have a parent. Running fix_tree again does not fix it. Moving node633 is not an option too because: treebeard.exceptions.InvalidMoveToDescendant: Can't move node to a descendant. Question: How can i fix this broken node66? -
Mat-icon display based on condition in for loop
I have an angular-django app which makes an aPI call to a third-party application and returns json response. I am looping through the response and displaying the data in a table. <tr *ngFor="let item of job_list"> <td style="text-align:center">{{item?.ReleaseName}}</td> <td style="text-align:center">{{item?.Source}}</td> <td style="text-align:center"><mat-icon *ngIf="Successful" style="color:green;">check circle icon</mat-icon> <mat-icon *ngIf="Faulted" style="color: red;">error icon</mat-icon> <mat-icon *ngIf="Stopped" style="color: grey;">cancel icon</mat-icon> {{item?.State}} </td> <td style="text-align:center">{{item?.StartTime | date:'dd-MM-yyyy HH:mm:ss'}}</td> <td style="text-align:center">{{item?.EndTime | date:'dd-MM-yyyy HH:mm:ss'}}</td> </tr> Here, I want to display mat-icon based on {{item?.State}} value. For example if the value is Successful, I want to display the "check circle icon", if it's "Faulted", I want to display "error icon" etc. Is this possible? Thank you -
How to show that the lesson is done from related model?
I have list of lessons and i need to highlight the done ones by current person. I tried my version below, but it's showing only done lessons. I have 2 models: lessons and donelessons related with user and lessons with foreignkey. models class Lessons(models.Model): theory = models.TextField(blank=True) words = models.TextField(blank=True) question1 = models.CharField(max_length=255) answer1 = models.CharField(max_length=255) class DoneLessonsModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) lessons = models.ForeignKey(Lessons, on_delete=models.CASCADE, null=True, related_name="releases") done = models.BooleanField(default=False) views class News(ListView): model = Lessons template_name = 'static/news.html' context_object_name = 'posts' def get_queryset(self): return Lessons.objects.all().prefetch_related( Prefetch('releases', queryset=DoneLessonsModel.objects.filter(user=self.request.user))).all() html ... {% for p in posts %} {% for release in p.releases.all %} <div class="col-md-3 mt-3"> <div class="card mb-4 box-shadow {% if release.done == True %} bg-success text-white btn-outline-light {% else %} border-dark {% endif %} "> <div class="card-body"> <p class="card-text">Lesson №{{ p.pk }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a href="{% url 'theory' p.pk %}" > <button type="button" class="btn btn-sm {% if release.done == True %} btn-outline-light {% else %} btn-outline-dark {% endif %} ">Start</button> </a> </div> </div> </div> </div> </div> {% endfor %} {% endfor %} ... -
Cannot resolve file 'signup'
I am newbie to Django and i need help to solve this problem. It states that cannot resolve file'signup'. <h3>Create your account!</h3> <form method="post" action="/signup"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Create A Username (use only letters and numbers)" Required> </div> -
Django: How to log user in right after they had registered with somewhat default UserCreationForm?
I'm trying to log the user in right after they had registered with the app, so that they don't have to manually log in right after. I have created RegisterForm from django's UserCreationForm and it works as it should - it creates an User object if the form is valid, but I don't know how to access that created User object to log it it using the login function, which requires, aside from request, also an user object. Note: I have edited the default User in models.py. This is my code: class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','id':'username', 'aria-describedby':'usernameHelp'}) self.fields['password1'].widget.attrs.update({'class':'form-control','id':'password1', 'aria-describedby':'password1Help'}) self.fields['password2'].widget.attrs.update({'class':'form-control','id':'password2','aria-describedby':'password2Help'}) class Meta: model = User fields = ['username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'photo', 'amazon', 'twitter', 'facebook', 'instagram', 'youtube'] widgets = { 'email':EmailInput(attrs={'class':'form-control', 'id':'email', 'aria-describedby':'emailHelp'}), 'first_name':TextInput(attrs={'class':'form-control', 'id':'first_name',}), 'last_name':TextInput(attrs={'class':'form-control','id':'last_name', 'aria-describedby':'nameHelp'}), 'photo':ClearableFileInput(attrs={'class':'form-control','id':'photo', 'aria-describedby':'photoHelp'}), 'amazon':URLInput(attrs={'class':'form-control', 'id':'amazon', 'aria-describedby':'amazonHelp'}), 'twitter':URLInput(attrs={'class':'form-control', 'id':'twitter', 'aria-describedby':'twitterHelp'}), 'facebook':URLInput(attrs={'class':'form-control', 'id':'facebook', 'aria-describedby':'facebookHelp'}), 'instagram':URLInput(attrs={'class':'form-control', 'id':'instagram', 'aria-describedby':'instagramHelp'}), 'youtube':URLInput(attrs={'class':'form-control', 'id':'youtube', 'aria-describedby':'youtubeHelp'}) } And here is the view: def register(request): # POST if request.method == "POST": # In addition to our form we must make sure to get the files too, if photo is uploaded form = RegisterForm(request.POST, request.FILES or None) if form.is_valid(): form.save() #user = User.objects.get() ??? #login(request, user) return HttpResponseRedirect(reverse('index')) else: … -
Can't mock a third party api call
I have a view that perform a third party API call: from .atoca_api_calls import atoca_api_call def atoca_api_call_view(request): # some code data = atoca_api_call(**params) # the actual API call happens in this func # some code My intention is to mock just the atoca_api_call() func and not the whole view. class AtocaTestCase(TestCase): def setUp(self): # some code @patch('crm.atoca_api_calls.atoca_api_call') def test_atoca_call(self, mock_atoca_api_call): mock_atoca_api_call.return_value = MagicMock( status_code=200, response=some_json # just returns some json ) url = reverse('crm:atoca-api-call') # url related to `atoca_api_call_view` response = self.client.post(url, some_others_params) # various asserts The test works fine but atoca_api_call() is not mocked. I'm aware of where to patch: @patch('crm.views.atoca_api_call', autospec=True) Raises a ValueError: ValueError: Failed to insert expression "<MagicMock name='mock.__getitem__().__getitem__().__getitem__()().resolve_expression()' id='140048216397424'>" on crm.Company.atoca_id. F() expressions can only be used to update, not to insert. It's probably a simple issue I don't catch for inexperience, any help is really appreciated.