Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO Templates dont share static files
I have a currently have a problem. I got two django templates:cart.html and index.html. In the cart.html there is a javascript file linked. Both of these files should acces the static files in the static folder. The problem now is that, when I try to acces the static files from the linked cart.html javascript file it gives me this error: [15/Aug/2022 20:14:40] "GET /cart/images/fruits/Kornknacker.jpg HTTP/1.1" 404 2419 These are my settings: STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) Here is the project structure: Project Here is the javascript file: {% load static %} function loadCart() { let productsSection = document.getElementById("products_section"); productsSection.innerHTML = ''; let productHTML = ''; let totalPrice = 0; let cartItems = JSON.parse(localStorage.getItem('cart')); if (cartItems && cartItems.length > 0) { for (let item of cartItems) { totalPrice = totalPrice + (item.quantity * item.price); productHTML = productHTML + ` <div class="product-card" data-name="${item.itemName}" data-price="${item.price}" data-id="${item.itemId}"> <div> <img src="{%static '/images/fruits/${item.itemName}.jpg'%}" alt="FRUIT" width="180"> </div> <h3> ${item.itemName} </h3> <div> Anzahl: ${item.quantity} </div> <div> Preis: ${item.quantity * item.price}€ </div> </div> `; } document.getElementById("total_price_container").style.display = 'block'; document.getElementById("total_price").innerHTML = totalPrice; document.getElementById("no-products_section").style.display = 'none'; document.getElementById("checkout-section").style.display = 'flex'; document.getElementById("order-process_section").style.display = 'none'; productsSection.innerHTML = productHTML; } else { document.getElementById("no-products_section").style.display = 'block'; document.getElementById("checkout-section").style.display = 'none'; document.getElementById("total_price_container").style.display = 'none'; } }; … -
Cannot login to django admin panel after changing password
I hope you are fine. I have a superuser in django admin and the problem is that when this superuser changes his password, he will be redirected to the django admin login page and when the superuser enters correct username and password in the admin login page, it gives an error that is “Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.”, but I am sure that both of the username and password fields are filled correctly; I will thank if anyone help me to solve this problem. Thanks. -
Creating a form with input for 2 models django
I have create 2 models, models.py class Integrations(models.Model): subscription_id = models.UUIDField( primary_key=True, default=uuid.uuid4, unique=True, editable=False ) subscription_name = models.CharField(max_length=256) subscription_type = models.CharField( max_length=256, choices=SUBSCRIPTION_TYPE, default="mqtt" ) def __str__(self): return self.subscription_name class Meta: ordering = ["subscription_name"] verbose_name = "Integration" verbose_name_plural = "Integrations" class Subscription(models.Model): url = models.CharField(max_length=256) port = models.IntegerField() username = models.CharField(max_length=256) password = models.CharField(max_length=256) topics = ArrayField(models.CharField(max_length=256)) subscription_id = models.ForeignKey(Integrations, default=None, on_delete=models.CASCADE) admin.py class MQTTSubscriptionAdmin(admin.ModelAdmin): fields = [ 'subscription_id', 'mqtt_url', 'port', 'username', 'password', 'subscribed_topics'] add_form = NewMQTTCreationForm fieldsets = None add_form_template = 'integrations/add_new_integration.html' add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('subscription_id', 'subscription_name', 'subscription_type'), }), ) forms.py from django import forms from django.core.exceptions import ValidationError class NewMQTTCreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(NewMQTTCreationForm, self).__init__(*args, **kwargs) self.fields['url'].required = True self.fields['port'].required = True self.fields['username'].required = False self.fields['password'].required = False self.fields['subscription_id'].required = True self.fields['subscribed_topics'].required = False add_new_integration.html {% extends "admin/change_form.html" %} {% load i18n admin_urls static admin_modify jazzmin %} {% get_jazzmin_settings request as jazzmin_settings %} {% block form_top %} <!-- empty block to remove default user create text --> {% endblock %} {% block field_sets %} <div class="col-12 col-lg-9"> <div class="card"> <div class="card-body"> {% get_changeform_template adminform as changeform_template %} {% include changeform_template %} </div> </div> </div> {% endblock %} Here I want to … -
space in url Django
I am creating a search bar on my site, everything is fine if I pass the names without spaces, being that I pass the word of the search bar directly in the url, as you can imagine the problem arises when the user enters words with space. I also convert the url into utf-8, but I think django does it automatically because even without the conversion in the url if you pass the space it appears at its post% 20, I wanted to clarify that the problem persists if you enter characters like:! ?can someone help me? Thanks in advance. urls.py: from django.urls import path from dac import views from django.conf.urls.static import static from django.conf import settings from django.urls import re_path #include from django.contrib import admin app_name = 'dac' urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('doctors/<slug:slug>', views.doctor, name='doctors'), path('doctors/search/<slug:slug>/<slug:slug2>', views.doctor_search, name='doctors_search'), re_path(r'^doctors_search/search/(?P<slug>.)/(?P<slug2>\d+)$', views.doctor_search, name='doctors_search'), path('<slug:slug>', views.doctor_detail, name='doctor_detail'), path('signup/', views.sign_up, name="sign_up"), path('login/', views.log_in, name='log_in'), path('logout/', views.log_out, name='log_out'), path('reports/', views.reports, name='reports'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: def doctor(request, slug): print("slug: ",slug) if request.method == 'POST': print("slug: ",slug) risposta=request.POST.get("textAnswer") risposta=risposta.upper() risposta_list=risposta.rsplit() print(risposta_list) actual_url=request.build_absolute_uri() url=re.sub("\d+$", "search/%s/1"%(risposta), actual_url) return HttpResponseRedirect(url.encode('utf-8')) slug=int(slug) max_slug=int(round(doctors.objects.count()/28,0)) if slug==1: prew_slug=slug else: prew_slug=slug-1 if slug==max_slug: nxt_slug=max_slug else: nxt_slug=slug+1 … -
Filtering pages by fields of child pages of the nested level in Wagtail
There is the following page structure: ServiceCategoryPage -> ServicePage -> TariffPage and TariffPagePrices(Orderable): page = ParentalKey(TariffPage, on_delete=models.CASCADE, related_name='tariff_prices') .... How to filter the results of page ServiceCategoryPage on page ServicePage by the properties of model TariffPagePrices? -
Django Model Field to Count Other Field
I have these models class HatchingBatch(models.Model): hatch_date = models.DateField() incubator = models.CharField(max_length=32) rhode_island_red = models.IntegerField(default=0) barred_plymouth_rock = models.IntegerField(default=0) black_australorp = models.IntegerField(default=0) class Reservations(models.Model): date = models.DateField() hatch = models.ForeignKey(HatchingBatch, related_name="reservation", on_delete=models.CASCADE) is_done = models.BooleanField() is_delivery = models.BooleanField() shipping_fee = models.IntegerField() amount = models.IntegerField() class Stocks(models.Model): hatch = models.OneToOneField(HatchingBatch, on_delete=models.CASCADE, related_name="stock") I want to add a field to the Stocks model that would be the number of the reserved chicks (easily done through ForeignKey) however, I also want to add a "sold" field that would correspond to the sum of the Reservations with "is_done" : True -
Uncaught SyntaxError: Expected property name or '}' in JSON at position 1 at JSON.parse (<anonymous>)
Hi Im trying to execute python from javascript .So I'm trying to use the below code example views.py from django.shortcuts import render from json import dumps def send_dictionary(request): # create data dictionary dataDictionary = { 'hello': 'World', 'geeks': 'forgeeks', 'ABC': 123, 456: 'abc', 14000605: 1, 'list': ['geeks', 4, 'geeks'], 'dictionary': {'you': 'can', 'send': 'anything', 3: 1} } dataJSON = dumps(dataDictionary) return render(request, 'main / landing.html', {'data': dataJSON}) landing.html <!DOCTYPE html> <body> <div style="width: 40%; border: 1px solid black; background-color: lightcyan; font-family: Helvetica, sans-serif;"> <div style="margin: 5%;"> <h2> <u>Data</u> </h2> <h4 id='data'></h4> </div> </div> </body> </html> <script> var data = JSON.parse('{{data|escapejs}}') var dataNode = document.getElementById('data'); for(var x in data){ dataNode.innerHTML+=x+' : '+data[x]+'<br><br>'; } </script> When I try to run ,I got this syntax error but doesn't really seem to be a syntax error. Uncaught SyntaxError: Expected property name or '}' in JSON at position 1 at JSON.parse () Im referring to the example in the below link. https://www.geeksforgeeks.org/how-to-pass-data-to-javascript-in-django-framework/ -
Ajax call run by form submission and will pass data to a separate views.py template
I am building a web application using Django. I have a search function on my index page. When a user submits the form an AJAX call should be executed. This AJAX call should take all the needed data from the form and pass it over to a completely separate views.py template that will make API GET requests using that data and build a new page using that separate template. As of right now it is not loading the separate views.py template, I am unsure if I am passing the data correctly however I do see /searchresults?searchType=data1&amp;executeLocation=data2 in my console because my AJAX call is returning on success currently. It is safe to assume that I have all the data needed in the data1 and data2 variables, I just need help redirecting to the new page and passing the data along with the redirect. My code: urls.py # The home page path('', views.index, name='home'), # Search results page path('searchresults', views.search_results, name='searchresults'), AJAX function getSearchResults(searchType,executeLocation,csrf_token) { $.ajax( { type: $(this).attr('method'), url: "searchresults", //The URL you defined in urls.py data : { searchType: searchType, executeLocation: executeLocation, csrfmiddlewaretoken: csrf_token }, dataType: 'text', success: function(response) // currently executes success (but not correct outcome) { console.log(response); … -
Local dependency not editable poetry
Just pulled this library to my django project to modify it. Installed it as a local dependency using poetry add ./django-rest-framework-passwordless. The develop mode is set to true. drfpasswordless = {path = "django-rest-framework-passwordless", develop = true} [[package]] name = "drfpasswordless" version = "1.5.8" description = "Passwordless auth for Django Rest Framework Token Authentication." category = "main" optional = false python-versions = ">=3" develop = true Whenever I'm trying to change something (for example urls) urlpatterns = [ path(api_settings.PASSWORDLESS_AUTH_PREFIX + 'emaillllll/', ObtainEmailCallbackToken.as_view(), name='auth_email'), ... ] the state keeps unchanged. Do you know what could be a reason? -
How to connect redis for celery to a django app deployed in digital ocean
I hae recently deployed a django app in digitalocean. My app uses celery and redis for several email sending puposes and scheduled tasks. I have been searching for a documentation on how to connect redis and how to det the celery worker running for my app in digital ocean, but I am unable to find any proper way or documentation. Please can someone tell me how to exactly setup this in digital ocean. -
Images are not displaying in Django production server
I uploaded a few icons to the static/img/ directory in my Django project, which is based on the Django Admin interface. I have one testing server and one production server. Both are using https://fra1.digitaloceanspaces.com to store static project files. To display specific icons, I created custom field in Django ModelAdmin: def get_type(self, obj): return format_html( '<img alt="type" src="{static_url}/img/type_icons/type-{type}.png">', static_url=settings.STATIC_URL, type=obj.type ) project/settings.py When developing locally STATIC_URL = '/collected-static/'. In development and production mode STATIC_URL = '{}/{}/static/'.format(AWS_S3_ENDPOINT_URL, AWS_STORAGE_BUCKET_NAME). AWS_S3_ENDPOINT_URL is https://fra1.digitaloceanspaces.com. AWS_STORAGE_BUCKET_NAME is either project-develop (testing) or project (production). These variables are configured in deployment YAML file. Locally and in development(testing) mode images are displayed perfectly fine this way, but inside production mode images are not displayed at all. I've tried changing the location of the files and even changing the deployment configuration, but nothing seems to help getting the icons to show up in production. /collected-static/img/type-object_type.png (example of icon img src on localhost - OK) https://fra1.digitaloceanspaces.com/project-develop/static/img/type-object_type.png (example of icon img src on testing server - OK) https://fra1.digitaloceanspaces.com/project/static/img/type-object_type.png (example of icon img src in production - NOT DISPLAYING) I would like to hear your opinion on this problem I am having. I've been struggling with this for quite some time. Perhaps … -
My django app is Not activating after shutting down my PC
when I start a new django Project it works perfectly well but after I shutdown or restart my pc it does not work again. even though I have activated my virtual environment it keeps giving me errors. this what the error says: Traceback (most recent call last): File "C:\Users\SUCCESS-AKINYEMI\Desktop\studybud\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\SUCCESS-AKINYEMI\Desktop\studybud\manage.py", line 22, in main() File "C:\Users\SUCCESS-AKINYEMI\Desktop\studybud\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I tried it on another person laptop and it work, but it is not working on my on laptop. -
how to get both ID and names from Many to Many field in Django
i'm creating a messaging app like Whatsapp. i have a Profile model that has Rooms as Many to many relationship. meaning every user will have a list of rooms in which he is added in their profile database. i'm using Rest Framework to fetch the Room info. i'm getting only ID's of the room every time i fetch from the API's. but it would be much easier & optimized for my app if i could also get Names of the Rooms & ID through the profile's Api which has rooms as many to many relation. How can i save both Name & id into a Many to Many field?? #model.py from django.db import models # Create your models here. class Room(models.Model): name = models.CharField(max_length=100,unique=True,blank=True,null=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) rooms = models.ManyToManyField(Room) def __str__(self): return self.user.username Serializers.py from django.contrib.auth.models import User from rest_framework import serializers from App.models import * class roomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' class userSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class profileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' views.py from rest_framework.response import Response from rest_framework.decorators import api_view from App.models import * from .serializers import * … -
the field is not shown in the model // Django-rest-framework restfullAPI
I serialized the CustomUser model and I don't output the 'city' key and the 'like' key, and also don't output the 'week_days' key, which contains a list with datetime. How to solve this problem? (it seems like it is possible through extra context and methodfield) My serializers: class CanWorkStaffSerializerLike(serializers.ModelSerializer): class Meta: model = GameTheme fields = '__all__' class CanWorkStaffSerializerCity(serializers.ModelSerializer): class Meta: model = City fields = '__all__' class CanWorkStaffDaysSerializer(serializers.ModelSerializer): class Meta: model = CanWorkDays fields = '__all__' class CanWorkStaffSerializerUser(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['phone', 'email', 'avatar', 'city', 'first_name', 'last_name', 'like', 'is_legionary', 'is_staff', 'is_active', 'date_joined', 'comfortable_time', 'role', 'updated_at', 'future_notification_last_seen_id', 'developing_notification_last_seen_id'] class CanWorkStaffSerializerWeekDays(serializers.Serializer): datetime = serializers.DateTimeField() class CanWorkStaffSerializerFinal(serializers.Serializer): user = CanWorkStaffSerializerUser() week_days = CanWorkStaffSerializerWeekDays(many=True) convenient_day = CanWorkStaffDaysSerializer() My View: class CanWorkStaffAPIView(APIView): def get(self, request, week, token): context = {} try: user = User.objects.get(auth_token__key=token) except User.DoesNotExist: return HttpResponse('некорректная ссылка') todays_date = datetime.date.today() start_week = todays_date - datetime.timedelta(todays_date.weekday()) first_week_day = datetime.datetime.strptime(week + '-1', '%Y-%W-%w') staff_member = StaffMember.objects.get(user=user) if first_week_day.date() < start_week.today(): return HttpResponse('то что было, то прошло...') week_days = [first_week_day + timedelta(x) for x in range(7)] initial = {} for week_day in week_days: if staff_member.can_work.filter(date=week_day): initial[week_day.strftime('%a')] = True if request.method == 'GET': form = CanWorkForm(initial=initial) else: form = CanWorkForm(request.POST) if form.is_valid(): … -
django makemigrations: makemigrations add only id field from model
i'm learning django and python and mongodb. i tried to makemigrations myapp. i get a 0001_initial.py but this file create Id field and not my model fields this is my settings.py content: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig' ] 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 = 'myapi.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 = 'myapi.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'apidb', } } my models.py file: from django.db import models # Create your models here. class Student(models.Model): first_name: models.CharField(max_length=100, null=True) last_name: models.CharField(max_length=300, null=True) def __str__(self): return self.first_name + ' ' + self.last_name I'm looking for a solution, but I don't get anything -
Form doesn't appear and work in Django project
I'm relatively new to Django, so I faced one small problem. I read the documentation and decided to make my own comment form that displays at the same page (DetailView), where I display a question detail and all answers related to this question. I tried to make it as documentation says, but it didn't work. I wrote some functions, but they didn't help as well. Then I copied some styles from bootstrap, something appeared, but I still can't post anything. Seems like POST method doesn't work. It was working, when I add the button that leads to the specific page, where users cand leave comments, but I want to show form, display it at the same page, where all answers are displayed. I will appreciate any help, reccomendations and explanations how it works. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=250) slug = models.SlugField(max_length=255, db_index=True, verbose_name="URL") detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name="forum_question") def total_likes(self): return self.likes.count() def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name="forum_answer") def total_likes(self): return self.likes.count() … -
Is there a way to Verify return a form Validation error back to the UI in Django within an Ajax request
I currently have an issue where i am sending formData from the UI through Ajax to the backend, however, i also created an helper function within the form to allow Image compression whilst it receives the data from the frontend. When the form encounters an exception while compressing, it doesn't return the error to the User until the AJAX request has gotten a response from the server and then i reload the page, I am thinking of using JS to reload the page if the response if false to display the error. Is this a better implementation or how should i go about it? -
How can I get data from a user's social network profile in Django
I have a Django project with settings for authorization in social networks, gmail and telegram. Also there are scopes listed for them: Gmail: SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ] VK: SOCIAL_AUTH_VK_OAUTH2_SCOPE = ["email"] OK: SOCIAL_AUTH_ODNOKLASSNIKI_OAUTH2_SCOPE = ["GET_EMAIL"] For telegram it hasn't scopes I'm interesting to get data: user.id, mail, etc. after authorization for example to make a link to the social network's page or "mailto:"-link -
manage.py makemigrations ignores models.py
Lately I've been working on a Django 4.1 app, and I've got a model with following fields: from django.db import models from django.utils.translation import gettext_lazy as _ import datetime class CarArticle(models.Model): class manufacturers(models.TextChoices): BMW = 'BMW', _('BMW') AUDI = 'AUDI', _('AUDI') LEXUS = 'LEX', _('LEXUS') MERCEDES = 'BENZ', _('MERCEDES') VOLKSWAGEN = 'VW', _('VOLKSWAGEN') VOLVO = 'VOLVO', _('VOLVO') FORD = 'FORD', _('FORD') SAAB = 'SAAB', _('SAAB') id = models.BigAutoField(primary_key=True) articleId = models.CharField(max_length=10) manufacturer = models.CharField( max_length=5, choices=manufacturers.choices ) series = models.CharField(max_length=255) gen = models.CharField(max_length=255) year = models.CharField(max_length=20) mileage = models.CharField(max_length=20) engSize = models.CharField(max_length=255) fuelType = models.CharField(max_length=255) price = models.CharField(max_length=255) createdAt = models.DateField(auto_created = True,default=datetime.date.today) updatedAt = models.DateField(auto_now=True) Upon changing any field and running py manage.py makemigrations, I'm presented with No changes detected. My admin.py looks like that: from django.contrib import admin from .models import * admin.site.register(CarArticle) Previously, I removed migrations files and folder since I've been remodeling the database over and over. When I migrate with newly set database, I'm presented with these tables only: mysql> show tables; +----------------------------+ | Tables_in_capi_tool | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | … -
Getting unauthorized(401) while passing token to API call in react redux saga
I am trying to get patient details by in frontend This is my backend function in Django (DRF) @api_view(['GET']) @permission_classes([IsAuthenticated]) def getPatientProfile(request): user = request.user try: patient = Patient.objects.get(user_id=user) print(type(patient)) response = PatientSerializer(patient, many=False) return Response(response.data) except Exception as e: print(e) return Response(e) This is my test call which is working fine in backend GET http://127.0.0.1:8000/profiles/getPatientProfile/ HTTP/1.1 Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjYwNTgzMjU2LCJpYXQiOjE2NjA1NzYwNTYsImp0aSI6ImY3ZGU2OGEwNTI2ZTRmNzBiZjU2MDExYzgzMjFhODI1IiwiZW1haWwiOiJhbGlzaGJhaHJpYXouc0BnbWFpbC5jb20ifQ.BLjghVEhSjizpuP9BAJHdjGreKMvl5Y1xOmhsQ2lQLM Now this is how I am trying to call API in saga.js but I keep gettig Unauthorized error, I think the issue is in the way I am writing the Authorization: Bearer token line, can anyone help how I can fix this and what the issue is export const getDetailAPIfunction = async token => { try { const response = await axios.get( "http://127.0.0.1:8000/profiles/getPatientProfile/",{ Authorization: 'Bearer ',token, } ); console.log("data recieved = " + response.data); return response.data; } catch (error) { console.log("error = " + error); throw error; } }; function* fetchUserDetail({ payload: token }) { try { const response = yield call(getDetailAPIfunction, token); yield put(getProfileDetailSuccess(response)); } catch (error) { yield put(getProfileDetailFail(error)); } } -
Django - How to copy schema of existing database into test database?
In my django project, I am using an existing database (Postgres) and with python manage.py inspectdb I created models. now I want to write unit tests and my problem is django just creates an empty test database for it, but it doesn't create schemas. I need to django copy the schema of this database into the test database and then I will insert mock data into it. -
Django user login and registration with Github and Google
I want to create a Google and GitHub login and register with Django on the site, Previously I implemented the register and login with email, and I do not use username on this website, and I customized the user model for this. Can someone help me how to do this? -
How do I test django?
I want to unit test my django view and model. I want to test this views.py and model.py. How can I test them on a practical level? Please give me specific code. I would like to code a test that may make errors in more detail, but I am new to django so how do I do it? views.py def view_tv_and_movie_detail(request, type_movie_or_tv, id): """TVかMovieがデータにあったらgetなかったら登録してget""" tv_or_movie_object, _ = TVAndMovie.objects.get_or_create( tmdb_id=id, judge_tv_or_movie=type_movie_or_tv ) detail_tv_or_movie = TvAndMovieDetailhelp(request, tv_or_movie_object, 3) if request.method == "POST": detail_tv_or_movie.post_comment_action() context = detail_tv_or_movie.send_contexts_detail() template_place = "Movie/movie_detail.html" if type_movie_or_tv == "movie" else "Movie/tv_detail.html" return render(request, template_place, context) models.py class TVAndMovie(models.Model): tmdb_id = models.IntegerField( verbose_name="", blank=False, null=False, ) judge_tv_or_movie = models.CharField( blank=False, null=False, default="movie", max_length=20 ) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) def get_comments(self) -> object: return Comment.objects.prefetch_related("tv_or_movie").filter( tv_or_movie_id=self.id ) def average_stars(self) -> float: comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = round( sum([comment.stars for comment in comments]) / n_comments, 3 ) else: self.stars = 0 self.save() return self.stars class Comment(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) tv_or_movie = models.ForeignKey(TVAndMovie, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ("user", "tv_or_movie") indexes = [models.Index(fields=["user", … -
Show / Hide a particular field based on custom button click in Django Admin
I have a Django model like this: class Webhook(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) url = models.CharField(max_length=256) credentials = models.JSONField(null=True, blank=True, default=dict) @admin.register(models.Webhook) class WebhookAdmin(admin.ModelAdmin): list_display = ("id", "uuid", "url") fields = ("uuid", "url", "toggle_credentials_button", "credentials") readonly_fields = ("uuid", "toggle_credentials_button") def toggle_credentials_button(self, obj): return format_html("""<a class="button">Toggle Credentials</a>&nbsp""") toggle_credentials_button.allow_tags = True The Toggle Credentials button shown in the screenshot is a custom button. I want to show/hide credentials field based on the click/toggle of the Toggle Credentials button, i.e. if the credentials field is currently being shown, then hide the field after the button is clicked and vice-versa. By default, the credentials field should always be hidden whenever a user visits the page shown in the screenshot, i.e. the showing of the credentials field shouldn't persist. If the user clicked the Toggle Credentials button to show the credentials field, then goes back to some other pages and again comes to this same page, then he should have to again click the button to view the credentials field. Also please note that I won't be using this in any UI or Frontend, so I need the functionality to work in Django Admin only. How can I achieve this requirement ? Any kind of … -
What is the difference between "return HttpResponseRedirect(reverse("index"))" and "return render(request, "bidder/index.html")"
The instructor prefers the redirect function on that line instead of return render but hasn't clarified why and the differences between the two.