Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What should Authenticate Fetch from a User?
I joined a group that has been using Django and I was just curious for some performance aspects of user fetching for Authentication. The User objects have some foreignkeys/manytomany fields attached to them. I learned about the prefetch_related / select_related. So if I want to get everything of a user instance, that would result to about 10 queries. So my question is about API / REST Design. Should my auth only do 1 Query ( select User) or should it fetch alle the stuff that could be useful for other endpoints? Each endpoint uses the CustomAuthentication, so the queries would be executed for each API call. Is ist better to let people take care of a second well designed query at the endpoint, or should I provide them with alle variables on each endpoint autmatically ? Thanks in advance. This question is performance related. I tracked the requests with SILK and was not happy about the performance for retrieving Users -
How to return a list of objects using a Django REST API post request?
I am new to using REST API's and am trying to create an API where I can make a POST request containing keywords, which should then return a list of articles related to that keyword. The reason I can't use a GET request is because I am not GETting anything from a database, I am creating the list of articles based on the keyword from the POST request. Views.py: def article_get(request): if request.method == 'POST': serializer = serializers.ArticleListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) classes.py: class Article: title = "" url = "" def __init__(self, url, title): self.title = title self.url = url class ArticleList: keywords = "" articles = [] def __init__(self, keywords, articles): self.keywords = keywords self.articles = articles self.articles.append(serializedArticle) The self.articles.append(serializedArticle) line appends a serialized article to the articles list, which I hoped would simply add an article in JSON format to the articlelist, but instead it produces the following error: Object of type ArticleSerializer is not JSON serializable serializers.py: class ArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=300) url = serializers.CharField(max_length=300) def create(self, validated_data): return classes.Article(**validated_data) class ArticleListSerializer(serializers.Serializer): articles = serializers.ListField() keywords = serializers.CharField(max_length=100) def create(self, validated_data): return classes.ArticleList(**validated_data) As I mentioned, I am FAR from being … -
How to create link in Djano?
here i was stuck to link this page to another page, bacause because here I use forloop to make a content. So, how i can solve this ? here my index.html {% extends 'main.html' %} {% block content %} <main> <section class="py-5 text-center container"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <h1 class="fw-light">Qatar's Album</h1> <p class="lead text-muted"> Something short and leading about the collection below—its contents, the creator, etc. Make it short and sweet, but not too short so folks don’t simply skip over it entirely. </p> <p> <a href="#" class="btn btn-primary my-2">Main call to action</a> </p> </div> </div> </section> <div class="album py-5 bg-light"> <div class="container"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for isi in listContent %} <div class="col-md-4 mb-3"> <div class="card" style="width: 18rem"> <div class="card-body"> <h5 class="card-title text-center">{{ isi.title }}</h5> <p class="card-text text-center">{{ isi.desc }}</p> <a href="{{ what should i write here ?}}/" class="btn btn-primary d-flex justify-content-center">Details</a > </div> </div> </div> {% endfor %} </div> </div> </div> </main> {% endblock %} here is my function in views.py def index(request): listContent = Table_Content.objects.all().values() data = { "listContent" : listContent } template = loader.get_template('index.html') return HttpResponse(template.render(data, request)) and here is my urls.py in app urlpatterns = [ path('', views.index, name='index'), … -
Field 'id' expected a number but got 'S' django
view.py `@login_required(login_url="signin") def editproduct(request,pk): if request.user.is_superuser == 1: category = Category.objects.all() product = Product.objects.get(id=pk) data = { "categories":category, "product":product, "url":"products" } if request.method == "POST": name = request.POST.get('product_name') description = request.POST.get('description') product_category = request.POST.get('category') homepage = request.POST.get('homepage') if name is None or name == "": return render(request,"admin/editproduct.html",{ "error":"Ürün Adı Boş Bırakılamaz!", "categories":category, "product":product, "url":"products" }) if description is None or description == "": return render(request,"admin/editproduct.html",{ "error":"Ürün Açıklaması Boş Bırakılamaz!", "categories":category, "product":product, "url":"products" }) if product_category is None or product_category == "": return render(request,"admin/editproduct.html",{ "error":"Kategori Boş Bırakılamaz!", "categories":category, "product":product, "url":"products" }) product.product_name = name product.description = description if homepage == "on": product.homepage = True else: product.homepage = False product.save() product.category.set(product_category) print(pk) return redirect('editproduct',pk) return render(request,"admin/editproduct.html",data) else: return redirect('/')` The category the product belongs to appears 2 times in the category selection section and if I choose the 2nd one, the pk value becomes the first letter of the category's name and gives this error, how is this possible? -
django rest framework serializer, create an object for some model field
I have a serializer which looks like this: class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing fields = '__all__' My Listing model have some field: name, price, description, etc.., street_address, postal_code, city, etc... I would like my serializer to return an object like this: { "name": "Prestige", "price": 12, "description": "lorem ipsum", "address": { "street": "123 Main St", "city": "New York", "state": "NY", "zip": "10001" }, ... } instead of the basic: { "name": "Prestige", "price": 12, "description": "lorem ipsum", "street": "123 Main St", "city": "New York", "state": "NY", "zip": "10001" ... } What I want is encapsulate all "address" field into an "address" object in my response. -
I want to automatic create new fields in a table | Django
I want to automatically add new fields in my table. So that the fields can be read from a csv file. Here is my current Code in my models.py: from django.db import models import django class UserInformation(models.Model): field_list = [ models.CharField(max_length=200, verbose_name="Lastname"), models.CharField(max_length=200, verbose_name="Firstname"), models.EmailField(verbose_name="E-Mail"), models.CharField(max_length=200, verbose_name="phone"), ] @classmethod def contribute_fields(cls): for field in cls.field_list: field.contribute_to_class(cls, field.name) def __str__(self): return self.Lastname + " " + self.Firstname UserInformation.contribute_fields(UserInformation) I already tried a lot of diffrent things but nothing worked. -
Receiving images with javascript readable stream
backend : Im using streaminghttpresponse (django) that yields image for every 5 seconds def gen(): while True: yield(getBase64Image) sleep(5) # post request def getImages(request): return StreamingHttpResponse(gen(), content_type='multipart/x-mixed-replace; boundary=frame') ` frontend : I'm using fetch(apiEndpoint) and getting readablestream but how can i print each image in console for every 5 seconds. -
While testing a Django form, I'm getting the following error: `Select a valid choice. That choice is not one of the available choices.`
Context I have a Django form to create events (which is working well in the UI) and now I am creating the unit test. My event model has two foreign key fields: category and location, pointing to the models Category and Venue respectively. The Category and Venue models have a property public_id to prevent exposing the real ID in the select form. The Issue When I try to test the form, I can't figure out how to make it pass. It fails in the assertion assert form.errors == {} with: {'category': ['Select a valid choice. That choice is not one of the available choices.'], 'location': ['Select a valid choice. That choice is not one of the available choices.']} != {} Code My model (a simplified version): class Event(BaseModel): # Event information name = fields.CharField(max_length=255) category = models.ManyToManyField(Category, related_name="events") location = models.ForeignKey(Venue, on_delete=models.CASCADE, related_name="events") start_date = models.DateTimeField() # more fields My form (a simplified version): class EventCreateForm(forms.ModelForm): category = forms.ModelChoiceField( widget=forms.Select(), to_field_name="public_id", label=_("Category"), ) location = forms.ModelChoiceField( widget=forms.Select(), to_field_name="public_id", label=_("Venue"), ) class Meta: model = Event fields = [ "name", "category", "location", # more fields... ] labels = { "name", # more fields... } widgets = { "name", # more fields... … -
Django merging or joining more then 30 models with same fields into one?
so i need to build rest api with django rest framework and the problem that i have is that I've got more then 30 models from already existing postgresql db with command inspect db. All these tables have exactly the same fields. They are collecting data in different countries so I can't change anything regarding db but i need to build api. Also there is more then 1 000 000 instances in all tables and the data is updating almost every day. Is there a way that i can join these tables into one. What would be the best way to serialize this and send it with view? Any idea is welcome. Thanks -
How to not let django create django_migrations table
After the first creation of my database I don't want to change it,I won't need to makemigrations or to migrate from my django project, and I don't want Django to create django_migrations table, How I could do that? -
I'd like to reduce SQL statements using consecutive/chained prefetch_related()
Please let me ask how I can reduce the number of SQL using chained prefetch_related(). I wrote item = Item.objects.prefetch_related('item_photo', 'item_stock', 'item_review',) # .prefetch_related('item_photo').prefetch_related('item_stock')... item (0.000) SELECT "item"."id", "item"."name", "item"."price", "item"."category_id", "item"."runs", "item"."wins", "item"."description", "item"."total_sales", "item"."created_at", "item"."updated_at", "item"."on_sale", "item"."note" FROM "item" LIMIT 21; args=(); alias=default (0.000) SELECT "item_photo"."id", "item_photo"."item_id", "item_photo"."photo", "item_photo"."priority", "item_photo"."note" FROM "item_photo" WHERE "item_photo"."item_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9) ORDER BY "item_photo"."priority" ASC; args=(1, 2, 3, 4, 5, 6, 7, 8, 9); alias=default (0.000) SELECT "item_stock"."id", "item_stock"."item_id", "item_stock"."stock", "item_stock"."note" FROM "item_stock" WHERE "item_stock"."item_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9); args=(1, 2, 3, 4, 5, 6, 7, 8, 9); alias=default (0.000) SELECT "item_review"."id", "item_review"."item_id", "item_review"."user_id", "item_review"."stars", "item_review"."comment", "item_review"."note" FROM "item_review" WHERE "item_review"."item_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9); args=(1, 2, 3, 4, 5, 6, 7, 8, 9); alias=default <QuerySet [<Item: Apple>, <Item: Banana>, <Item: Orange>, <Item: Lemon>, <Item: Tea>, <Item: Ginger>, <Item: Onion>, <Item: Banana>, <Item: Water>]> but, it displayed many SQL statements even if I bound tables with prefetch_related(). In addition, if I wrote following this in views.py, pk= 4 item = Item.objects.prefetch_related('item_photo', 'item_stock', 'item_review',).get(pk=pk) context = { 'form': form, 'item': item, 'photos': item.item_photo.values(), 'stock': … -
Django: Pass a variable back into views
I'm writing a sudoku webpage with Django and JS so I'm passing my unsolved sudoku list into the page via the context dictionary. In the page, I have 2 buttons in a simple HTML form. If 'NEW' is selected, it refreshes the page with a new sudoku. If 'SOLVE' is selected, I want it to send the current sudoku list back into views to go through the solver function and then sent back into the template. I currently have everything working except I have no idea how to send the unsolved sudoku list back into views. I've seen a lot of responses to questions like this saying to use request.POST.get() but how would I get the list into the queryDict? Also, I can't seem to find any posts on this topic within the last decade or so. Correct me if I'm wrong, but I think Python and Django may have changed slightly in the last 10 - 15 years. -
PostgreSQL doesn't work in ubuntu 20.04 Django Docker
My docker-compose works fine and runs on Windows 10 but when i tried to run it from ubuntu 20.04 i get the DB errors. My django settings.py file: DATABASES = { 'default': { 'ENGINE': env('SQL_ENGINE'), 'NAME': env('SQL_DATABASE'), 'USER': env('SQL_USER'), 'PASSWORD': env('SQL_PASSWORD'), 'HOST': env('SQL_HOST'), 'PORT': env('SQL_PORT'), } } my .env file: SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=my_db SQL_USER=my_admin SQL_PASSWORD=my_api SQL_HOST=db SQL_PORT=5432 My 'docker-compose.yml` file: version: '3.9' services: web: build: ./pets command: gunicorn pets.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - .env depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - "1337:80" depends_on: - web volumes: postgres_data: static_volume: media_volume: My Dockerfile: FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY requirements.txt . RUN pip install -r requirements.txt COPY entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $HOME RUN mkdir $APP_HOME WORKDIR $APP_HOME COPY .. $APP_HOME RUN mkdir $APP_HOME/staticfiles RUN mkdir $APP_HOME/mediafiles RUN chmod +x /usr/src/app/entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] First error i got: FATAL: role "my_admin" does not exist When i change the SQL_USER to postgres i've got … -
DJango eror: TypeError, Exception Value:__call__(): incompatible function arguments
I was trying to develop facial based attendance system, where user enter name,email and image in the database . tO Recognize, user enter image which recognise face endpoints using Python's face recognition library (https://pypi.org/project/face-recognition/). I defined database in models.py as class User(models.Model): name = models.CharField(max_length=255) email = models.EmailField() face_encodings = models.TextField(null=True, default=None) Similary, I have defened register and recognize function in views.py as def register(request): if request.method == 'POST': #name = request.POST['name'] #email = request.POST['email'] #image_file = request.FILES['image'] name = request.POST.get('name', '') # Use get method to get the value of 'name' key email = request.POST.get('email', '') image_file= request.FILES.get('image', None) image = face_recognition.load_image_file(image_file) face_encodings = face_recognition.face_encodings(image)[0] user = User(name=name, email=email,face_encodings=face_encodings) user.save() messages.error(request, 'User registered') return render(request, 'register.html') return render(request, 'register.html') def recognize(request): if request.method == 'POST': image_file = request.FILES.get('image', None) image = face_recognition.load_image_file(image_file) face_encodings = face_recognition.face_encodings(image) recognized_users = [] for face_encoding in face_encodings: users = User.objects.all() for user in users: user_face_encoding = face_recognition.face_encodings(user.face_encodings)[0] distance = face_recognition.face_distance([user_face_encoding], face_encoding)[0] if distance < 0.6: recognized_users.append({'name': user.name, 'email': user.email}) return JsonResponse({'status': 'success', 'recognized_users': recognized_users}) return render(request, 'recognize.html') I could register the user .But when i enter to recognize by uploading image . I got error: TypeError at /recognize/ __call__(): incompatible function arguments. The following … -
Python has stopped working when I import folium in my django project, why?
I'm facing a problem with my django project I'm creating a geolocation app with django 4.1, Python:3.11 Everything was working fine but when I import folium in my views, the local server crash, windows says "python has stopped working", and whenever I use the command "python manage.py" ,windows says "python has stopped working", and when I remove the "import folium inmy views" the project is running perfectly again. I don't know what is happening could someone help me please, I really need to solve the "folium" problem for my project These are all the packages installed in my virtual environment C:\Users\Neko>pip freeze asgiref==3.6.0 branca==0.6.0 certifi==2022.12.7 charset-normalizer==3.0.1 Django==4.1.7 folium==0.14.0 idna==3.4 Jinja2==3.1.2 MarkupSafe==2.1.2 numpy==1.24.2 Pillow==9.4.0 requests==2.28.2 sqlparse==0.4.3 tzdata==2022.7 urllib3==1.26.14 I checked in github and they said restart the pc: I already did Check if the package is installed in the right folder: I did, I installed it in a venv with all the dependencies Check if the version of python, django and folium was compatible: I did they all have the last version So what seems to be the problem please help me -
The right time to learn Django REST API
I would like to know what the right time is for learning django rest api , should I go for it after learning the basics ? thank you. nothing to show here -
Django Test Error: "1824, Failed to open the referenced table"
This is the flow of how my database is created: I already have a legacy MySql database with some tables. I create the django project and connect it to the legacy database. I run migrate, in order to create the django tables for sessions and authentication on the legacy DB. Then, directly from the DB I create the GeSession Table and the reference to the DjangoSession Table. Then I import all the tables models using "inspectdb" command. To be able to test, inside models.py, I set managed = True to every table except for the django ones. Then I run makeMigrations and migrate --fake-initial. If I try to use the django ORM to make queries it works without any problem, but during testing it keeps failing the test database creation giving me this error: MySQLdb.OperationalError: (1824, "Failed to open the referenced table 'django_session'") and then right after: django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'django_session'") Everytime I tweak something on the models.py file I delete the first migration file, I run makemigrations and then run: migrate --fake-initial. I dont understand what I'm doing wrong. Is it bad to keep the django tables and the other ones on the same … -
Is it impossible to apply view in authentication method?
I am trying to refresh jwt token during authentication method. (Because I want to handle tokens in server-side) I'm using Django, DRF. This is my authentication.py, which is included in 'DEFAULT_AUTHENTICATION_CLASSES' class CustomAuthentication(JWTAuthentication): def authenticate(self, request): header = self.get_header(request) if header is None: raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: # I want to apply CookieTokenRefreshView here # But if I apply view, it raises errors validated_token = self.get_validated_token(raw_token) enforce_csrf(request) return self.get_user(validated_token), validated_token When I try to apply CookieTokenRefreshView, (I overrided TokenRefreshView to set jwt as cookie) error raises. (Actually, error raises already when I just import view) Errors ImportError: Could not import 'account.authenticate.CustomAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'APIView' from partially initialized module 'rest_framework.views' (most likely due to a circular import) (\venv\lib\site-packages\rest_framework\views.py). Is it impossible to issue access token when access token expires in Django? Please let me know if there is another solution. -
Comments not registering into database when submitting form
When I try add a comment via my form, the page is redirected correctly but no comment is rendered/added. I am getting the following error in terminal when trying to add comment: Broken pipe from ('127.0.0.1', 55445) views def post_comment(request, slug): template_name = 'view-post.html' post = get_object_or_404(BlogPost, slug=slug) # Comment posted if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet user_comment = comment_form.save(commit=False) # Assign the current post to the comment user_comment.post = post # Assign comment to user user_comment.user = request.user # Save the comment to the database user_comment.save() else: # You may include extra info here from `comment_form.errors` messages.error("Failed to post comment") return redirect('viewpost', {'slug': slug,}) html <form method="POST" id="comment-form"> {% csrf_token %} {{comment_form|crispy}} <button class="btn btn-outline-secondary rounded-0 comment-button" id="form-submit" type="submit" onClick="window.location.reload();">Submit</button> </form> -
Like button not recording the data
I have implemented a like button onto my view_post page, but the like's aren't been registered. When the button is clicked the page is redirected correctly but no likes are added. views def get_post(request, slug): try: post = BlogPost.objects.get(slug=slug) except BlogPost.DoesNotExist: messages.error(request, 'This post does not exist.') post = None comment_form = CommentForm() return render(request, 'mhpapp/view-post.html', {'post': post, 'comment_form': comment_form,}) def like_post(request, slug): template_name = 'view-post.html' post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) messages.success(request, ("Thanks for the like...:-)")) liked = True return redirect('get_post', {'slug': slug,}) urls path('<slug:slug>/', views.get_post, name='viewpost'), path('<slug:slug>/',views.like_post, name='likepost'), html <strong>{{ post.total_likes }} Likes</strong> {% if user.is_authenticated %} <form action="{% url 'likepost' post.slug %}" method="POST"> {% csrf_token %} {% if request.user in post.likes.all %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="post-id" value="{{ post.slug }}"><i class="fa-solid fa-heart-crack"></i></button> {% else %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="post-id" value="{{ post.slug }}"><i class="fa-solid fa-heart"></i></button> {% endif %} </form> {% else %} {% endif %} -
No module named 'library'
I am trying to add a login system with Google-api-python-client that let's user login with their google account and my frontend is REACT JS. I was following a tutorial and was setting up my serializers.py accordingly but my serialzers.py can't find library and i can't use the googe, register_social_user from rest_framework import serializers from app.models import * from django.conf import settings from rest_framework import serializers from library.sociallib import google from library.register.register import register_social_user from rest_framework.exceptions import AuthenticationFailed class GoogleSocialAuthSerializer(serializers.Serializer): auth_token = serializers.CharField() def validate_auth_token(self, auth_token): user_data = google.Google.validate(auth_token) try: user_data['sub'] except: raise serializers.ValidationError( 'The token is invalid or expired. Please login again.' ) print(user_data['aud']) if user_data['aud'] != settings.GOOGLE_CLIENT_ID: raise AuthenticationFailed('oops, who are you?') user_id = user_data['sub'] email = user_data['email'] name = user_data['name'] provider = 'google' return register_social_user( provider=provider, user_id=user_id, email=email, name=name) I have installed library in my django project but ot still does't work. why is it cauing the problem and what to do? and can anyone suggest me the best way to create a login system with Google for my React-django project?? -
django-two-factor-auth[phonenumbers] got a redundant migration -> psycopg2.errors.DuplicateTable: relation "two_factor_phonedevice" already exists
I'm facing the following database creation table error when spinning up a django project from scratch when I have django-two-factor-auth[phonenumbers] in my requirements. When I run the migrate command, it raises a psycopg2.errors.DuplicateTable error: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, projectapplication, otp_static, otp_totp, sessions, two_factor Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying projectapplication.0001_initial... OK (... project application migrations) Applying projectapplication.0032_alter_foo_bar_baz_and_more... OK Applying otp_static.0001_initial... OK Applying otp_static.0002_throttling... OK Applying otp_totp.0001_initial... OK Applying otp_totp.0002_auto_20190420_0723... OK Applying sessions.0001_initial... OK Applying two_factor.0001_initial... OK Applying two_factor.0002_auto_20150110_0810... OK Applying two_factor.0003_auto_20150817_1733... OK Applying two_factor.0004_auto_20160205_1827... OK Applying two_factor.0005_auto_20160224_0450... OK Applying two_factor.0006_phonedevice_key_default... OK Applying two_factor.0007_auto_20201201_1019... OK Applying two_factor.0008_delete_phonedevice... OK Applying two_factor.0009_initial...Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "two_factor_phonedevice" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 21, in <module> main() File "/app/manage.py", line 17, … -
i cant use node modules package
i have a js file: <script type="module" src="{% static 'admin_panel/assets/js/sendAxios.js' %}" > I use it in this way: import axios from "axios"; But it gives the following error Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../". When I chnage to : import axios from '../../../node_modules/axios'; It gives me the following error http://127.0.0.1:8000/static/node_modules/axios net::ERR_ABORTED 404 (Not Found) I always had these problems for import and require commands.. How can I use node modules of a package? -
How to loop over the items in Django?
I was stuck to loop my table in template and put only 4 teams in each table. Here i want to create table groups stage of football. My Table_Team has 8 teams. So, i want my table in template looping where the table each has 4 teams. So,how to do it? Here is my Table class Table_Team(models.Model): code = models.CharField(max_length=10, default="") team = models.CharField(max_length=50) group = models.CharField(max_length=1) play = models.IntegerField(default=3) win = models.IntegerField() draw = models.IntegerField() loss = models.IntegerField() goalDiff = models.IntegerField() points = models.IntegerField() And here is my Template <div class="container"> <div class="row"> <div class="col-md-4 mb-3"> <div class="ptable"> <h1 class="headin">Standings</h1> <table> <tr class="col"> <th>#</th> <th></th> <th>Team</th> <th>P</th> <th>W</th> <th>D</th> <th>L</th> <th>GD</th> <th>PTS</th> </tr> <tr class="wpos"> <td>&nbsp;</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> </div> </div> </div> </div> Sorry for my english. I hope you understand what i mean. Thank you. -
Swagger is using schema host instead of current server
I am working with swagger , Django. I have used drf-spectural library. I have created one schema.yaml using openApi docs. And i have one docs/api/ API Url for swagger documentation . When i am executing API from documentation it is taking Host url of static file instead of my current server. for example :- my schema file is place of s3 bucket, The Url is https://bucket.awss-s3.com/folder/schema.yaml and my server url is https://sub-domain.example.com/docs/api/ and my example api url is https://sub-domain.example.com/api/get-product/ but when executing from swagger it is taking https://bucket.awss-s3.com/api/get-product/ So my swagger config are SPECTACULAR_SETTINGS = { "SWAGGER_UI_SETTINGS": { "url": "/static/schema.yaml" } }