Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When will the data in io.bytesIO() be lost?
I am a python beginner. At what point is the data in io.bytesio() erased? Are you able to erase with this code? I want to save RAM and have higher performance. This is my code, using Django. The code creates a thumbnail after detecting the PDF upload. def file_to_thumbnail(sender, instance, created, **kwargs): if created: thumbnail_name= instance.file_name()+'_thumbnail.jpeg' thumbnail_obj =Thumbnail(file=instance) make_thumbnail = convert_from_path(instance.file.path, dpi=150, first_page=1, last_page=1, fmt='jpeg') buffer = io.BytesIO() make_thumbnail[0].save(fp=buffer, format='JPEG') thumbnail_obj.thumbnail.save(name=thumbnail_name,content=buffer) buffer.close() I want to save RAM and have higher performance. Does this code delete the io.bytesIO() data in RAM? -
How to access the correct criteriaID in HTML template django
I have a form being generated by some html and I want to use a label which is not part of the actual form data, but related to it. In the current example there are 3 criteria for the assignment and a dropdown is generated to give a student a level for each criteria and a comment about their work. The criteria description however is causing problems, as I am not sure how to fetch the correct one for each form in the formset. The context includes a list of all the criteria and so I have tried to use something like criteria.forloop.counter0 But of course this does not work. Other than this I have also tried acessing the correct criteriaDescription through the other form inputs like form.criteriaLevelID.criteriaID But this also returns nothing. I'm not sure what else to try here, but it seems like the kind of thing that there should be a simple way to achieve. The whole form looks like the below for reference <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} <table> <thead> <tr> <th>Criteria</th> <th>Criteria Level</th> <th>Comment</th> </tr> </thead> <tbody> {% for form in formset %} <tr> <td>{{ criteria # problem here }}</td> <td>{{ … -
Django error "detail: Credentials were not provided" when trying to logout
I created a class-based LogoutAPIView but when I test it, it gives the "detail: Credentials were not provided error". views.py: class LogoutView(APIView): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] http_method_names = ['post'] def post(self, request): token = request.auth if token: Token.objects.get(token=token).delete() content = {'message': 'Logout successful'} else: content = {'message': 'No authentication token found'} return Response(content) serializer.py: class LogoutSerializer(serializers.Serializer): message = serializers.CharField(max_length=200) My LoginAPIView incase needed: views.py: class LoginAPIView(generics.CreateAPIView): permission_classes = (AllowAny,) serializer_class = LoginAPISerializer http_method_names = ['get', 'post'] def get(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) def post(self, request, format=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=status.HTTP_200_OK) serializers.py: class LoginAPISerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() http_method_names = ['get', 'post'] def validate(self, data): username = data.get('username') password = data.get('password') if not username or not password: raise serializers.ValidationError('Username and password are required') user = authenticate(username=username, password=password) if not user: raise serializers.ValidationError('Invalid credentials') data['user'] = user return data def create(self, validated_data): user = validated_data['user'] token, created = Token.objects.get_or_create(user=user) return {'token': token.key} I am new to Django, so I don't even know if I need a serializer class for LogoutAPIView. I also added DEAFULT_AUTHENTICATION_CLASSES but it didn't solve the issue. Please … -
Strange behaviour because of the order of URLs in urls.py django behaviour
I am doing a mini blog assignment using Django for learning purpose. I noticed a strange behavior in django urls.py when the order of lines is below I am able to make a successful GET call to http://127.0.0.1:8000/blog/blog/create path('blog/create', views.BlogPostCreate.as_view(), name='blogpost-create'), path('blog/<slug:slug>', views.BlogPostDetail.as_view(), name='blogpost-detail'), but when the above lines are reveresed Then I start getting 404 error. I am not sure why this error is happening. By just reading the Raised By in the message I did some shot in the air and the create form start loading. Can anyone explain the behavior? I am sure there must be some explanation for this. -
Django framework. There was a question concerning creation of the dynamic form on page
I am a beginner in django. I am currently writing a test form. There was a question about creating a dynamic form to answer a question. On the page I am creating a question, as well as answers. Questions are created normally, but with the creation of answers, I did not fully understand how to implement it correctly. views.py def index(request, id): question = Profile.objects.get(id=id) answer = Question.objects.filter(ProfileId_id=question) #answer_qs = answer.objects.all() question_form_set = inlineformset_factory(Profile, Question, fields=('text_of_question', 'Weight',), extra = 0) answer_form_set = inlineformset_factory(Question, Answer, fields=('text_of_answer', 'IsRight',), extra = 0) if request.method == 'POST': formset = question_form_set(request.POST, instance=question) formset2 = answer_form_set(request.POST, queryset=answer) if formset.is_valid(): formset.save() #formset2.save() return redirect('profile') else: formset=question_form_set(instance=question) formset2 = answer_form_set(instance=answer) form = QuestionForm(request.POST or None, instance=question) form2 = AnswerForm(request.POST or None, instance=answer) return render(request, 'main/question_ch.html', {'formset': formset, 'form': form,}) models.py class Question(models.Model): ProfileId = models.ForeignKey(Profile, on_delete=models.CASCADE) text_of_question = models.CharField(verbose_name='Текст вопроса', max_length=200) Weight = models.FloatField(default=1, verbose_name='Вес') class Meta: verbose_name = 'Вопрос' verbose_name_plural = 'Вопросы' def __str__(self): return self.text_of_question class Answer(models.Model): QuestionId = models.ForeignKey(Question, on_delete=models.CASCADE) text_of_answer = models.CharField(max_length=300) IsRight = models.BooleanField() class Meta: verbose_name = 'Вариант ответа' verbose_name_plural = 'Варианты ответа' def __str__(self): return self.text_of_answer -
Combined unique_field in bulk_create in without checking PK
I am trying to import data from multiple API's and there is a chance of duplicates. I am trying to bulk-create without duplication. All API sources do not provide me with a unique identifier. I am wondering what the best way to handle this situation is. What I have tried is as follows: if 'rounds' in response: print('=== Syncing Rounds ===') rounds = response.get('rounds') objs = [ Round( name = item.get('name'), season = Season.objects.get(id = item.get('seasonId')), competition = Competition.objects.get(id = item.get('competitionId')), round_number = item.get('roundNumber'), ) for item in rounds ] Round.objects.bulk_create( objs,update_conflicts=True, update_fields=['name','season','competition','round_number'], unique_fields=['id']) I tried setting ignore_conflicts = True but that approach didn't help me. The round numbers range from 1-30 and the season is the year. In the given situation, I cannot make one field unique such as round number, season, or competition. It has to look for all three. For example There can be only one row for Round 1, 2023, for competition 112. This entire combination is unique. The end goal is to either ensure no duplicate entries or update existing rows. One hack (as said by OP) solution is Bulk insert on multi-column unique constraint Django -
Celery Beat stops running tasks without any errors
Celery beat is spinning in a container in the Kubernetes (1 replica). Celery beat works for a few days, then it stops running scheduled tasks, and there are no errors in the logs, the logs look like this: 2023-04-08 13:56:57 [2023-04-08 04:56:57,544: DEBUG/MainProcess] Current schedule: 2023-04-08 13:56:57 [2023-04-08 04:56:57,532: INFO/MainProcess] beat: Starting... 2023-04-08 13:56:57 [2023-04-08 04:56:57,532: DEBUG/MainProcess] Setting default socket timeout to 30 2023-04-08 13:56:52 . maxinterval -> 5.00 minutes (300s) 2023-04-08 13:56:52 . logfile -> [stderr]@%DEBUG 2023-04-08 13:56:52 . db -> celerybeat-schedule 2023-04-08 13:56:52 . scheduler -> celery.beat.PersistentScheduler 2023-04-08 13:56:52 . loader -> celery.loaders.app.AppLoader 2023-04-08 13:56:52 . broker -> redis://192.168.68.4:6379/3 2023-04-08 13:56:52 Configuration -> 2023-04-08 13:56:52 LocalTime -> 2023-04-07 07:38:01 2023-04-08 13:56:52 __ - ... __ - _ 2023-04-08 13:56:52 celery beat v4.3.0 (rhubarb) is starting. When celery beat stops running tasks: [2023-04-08 00:05:00,081: DEBUG/MainProcess] beat: Synchronizing schedule... [2023-04-08 00:05:00,087: DEBUG/MainProcess] 2. <crontab: 0 0 * * * (m/h/d/dM/MY)> 86099.912976 > 0 [2023-04-08 00:05:00,087: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. [2023-04-08 00:10:00,187: DEBUG/MainProcess] beat: Synchronizing schedule... [2023-04-08 00:10:00,190: DEBUG/MainProcess] 2. <crontab: 0 0 * * * (m/h/d/dM/MY)> 85799.809269 > 0 [2023-04-08 00:10:00,191: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. [2023-04-08 00:15:00,290: DEBUG/MainProcess] beat: Synchronizing schedule... [2023-04-08 00:15:00,293: DEBUG/MainProcess] … -
country flag and country code not showing in django form and admin
I'm using django-phonenumber_field in my model, but when added a PhoneNumberField in my model, and add it to my forms.py file it does not show a country flag with their country code like this in template, how can i solve this problem? from phonenumber_field.modelfields import PhoneNumberField from django.core.validators import RegexValidator class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=1000) phone_number = PhoneNumberField(validators=[RegexValidator(r'^\d{3}-\d{3}-\d{4}$')]) from phonenumber_field.formfields import PhoneNumberField class ProductForm(forms.ModelForm): phone_number = PhoneNumberField() class Meta: model = Product fields = ['name', 'category', 'description', 'phone_number'] settings.py: PHONENUMBER_DB_FORMAT = 'INTERNATIONAL' PHONENUMBER_DB_FORMAT="RFC3966" -
How to make sure data is correct after two update for the same table in Django ORM?
I use mysql and InnoDB engine for my Django project. I have a table which is like following, the queue field default value is 0 class Task(models.Model): task_id = models.CharField(max_length=32, primary_key=True) queue = models.IntegerField(default=0) I have two process, one is to insert a record based on the max queue in the table. max_queue = Task.objects.all().annotate(data=Max('queue')).values('data') queue_number = max_queue[0]['data'] + 1 record = {'task_id':task_id, 'queue': queue_number} Task.objects.create(**record) Another process is to decrement the value of queue for each record by 1 which queue is not equal to 0 query_list = Task.objects.filter(~Q(task_queue=0)) for query in query_list: Task.objects.filter(task_id=task_id).update(queue=query.queue - 1) Here what I am concerned is if the two process happened at the same time. For example, if the later process is about to decrement every value. While at the same time, the first process inserts a new value. In this case, there woule be some mistakes. How should I do it? Anyone has a good idea, thx in advance. -
amqp gets prepended to celery broker url
Specifying broker_url with redis://redis:6379/0 is getting overwritten to amqp://guest:**@redis%2F%2Fredis%3A6379%2F0:5672/ logs Cannot connect to amqp://guest:**@redis%2F%2Fredis%3A6379%2F0:5672//: [Errno -2] Name or service not known. Setup Structure config/ settings/ common.py dev.py celery.py docker-compose.yml services: django: &django_container build: context: . dockerfile: docker/django/Dockerfile command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/facebook_scraper environment: DOTTED_SETTINGS_PATH: 'config.settings.dev' env_file: - ./dev.env depends_on: - postgres - redis - selenium redis: image: redis:7.0.8 ports: - "6379:6379" celery_worker: <<: *django_container ports: [] command: celery -A config.celery worker -l INFO celery.py import os from celery import Celery dotted_settings_path = os.environ.get('DOTTED_SETTINGS_PATH') os.environ.setdefault('DJANGO_SETTINGS_MODULE', dotted_settings_path) app = Celery( 'facebook_scraper', # backend='redis://redis:6379/0', # broker='redis://redis:6379/0', ) app.conf.update( broker_url='redis://redis:6379/0', ) # app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
Toggle theme problem is Django admin panel? [closed]
I have encountered a problem in the Django admin panel. This is running perfectly locally but not on the server. I have checked if django-extensions is installed but no its not. also, I tried setting debug to false but nothing changed... -
Django admin show only current user for User field as ForeignKey while creating and object
I'm working on a Django ( 4.0 +) project, where I have a model named Post in which we have a ForignKey field as Author, a user with is_staff and in Authors group can create an object of Post from admin. Now the problem is when user click on Add Post as the Author field it should only display the current user not the others. Here's what i have tried: From models.py: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) thumbnail = models.ImageField() category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, related_name='category') featured = models.BooleanField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title From admin.py: class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(author=request.user) How can I achieve that? -
Django QuerySet Not returning all data
I am trying to return all the data in queryset which is saved in my model. But when I try to print it only returns the title nothing else. Bellow are the screenshots attached for refrence. Please assist Code: enter image description here and here is the data which i have saved in my model enter image description here -
Django Test Error When Using Custom User Model & django-allauth
I've been creating a Django app and am trying to get the login and authentication working correctly. I have created a custom user model to override Django's default user model and am using a Postgres backend. When I try and add django-allauth to the INSTALLED_APPS and then try and run "manage.py test" I get an error. My project structure is as follows; project/ project_app/ settings.py urls.py accounts/ models.py #CustomUser model defined in here tests.py views.py managers.py admin.py A snippet of my settings.py is; INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'accounts', 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'dj_rest_auth', 'dj_rest_auth.registration', ] AUTH_USER_MODEL = "accounts.CustomUser" When I add the line allauth.account to my settings.py file and then run "manage.py test" I get the error ValueError: Related model 'accounts.customuser' cannot be resolved. Without this line added the tests run ok. This only seems to happen when I try and run tests and not in the development database. I wondered if this was something to do with the order in which the test database is applying migrations, but don't know how to change that or if anyone else had come across this scenario. Any help much appreciated as I'm running out of ideas! -
why the hell it's popping again n again: ModuleNotFoundError: No module named 'store.product'
making a project in pycharm , after running the command : python manage.py makemigrations , its showing something like File "", line 940, in exec_module File "", line 241, in call_with_frames_removed File "C:\Users\Nisha\PycharmProjects\eshop\store_init.py", line 1, in from .product import Product ModuleNotFoundError: No module named 'store.product' (venv) PS C:\Users\Nisha\PycharmProjects\eshop> expected product python in model python package created in my __init__py so that i can go with my eshop django project. -
Django: Add is_staff permission to user inside view based on a condition
I'm working on a Django (4.0+) project,, where I'm using the default User model for login, and a custom form for signup, and I have a Boolean field named: blogger in signup form, if user check this, i have to set is_staff true, otherwise it goes as normal user. Here's what I have: Registration Form: class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(max_length=101) last_name = forms.CharField(max_length=101) email = forms.EmailField() blogger = forms.BooleanField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'blogger', 'is_staff'] views.py: def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): print(form['blogger']) if form['blogger']: form['is_staff'] = True form.save() messages.success(request, f'Your account has been created. You can log in now!') return redirect('login') else: print(form.errors) else: form = UserRegistrationForm() context = {'form': form} return render(request, 'users/signup.html', context) Its giving an error as: TypeError: 'UserRegistrationForm' object does not support item assignment How can i achieve that? -
Redirect to previous page when login form submitted
How would I get the djangos built in LOGIN_REDIRECT_URL to redirect to previous page before logging in? I have tried: LOGIN_REDIRECT_URL = 'request.META.HTTP_REFERER' LOGOUT_REDIRECT_URL = 'request.META.HTTP_REFERER' -
how to write complex sql-constraints with django-db-models
I want to know how to write a complex sql-constraints like below with django . create table fiscalyeartable (fiscal_year integer not null primary key, start_date,date not null, constraint valid_start_date check((extract(year from start_date)=fiscal_year-1) and(extract (month from start_date)=10) and(extract (dat from start_date)=01)), end_date date not null, constraint valid_end_date check((extract(year from end_date)=fiscal_year) Is it possible? I find this constraint from first problems of『sql puzzles and Answers 』. I wrote code like this. class FiscalYear(models.Model): fiscal_year=models.IntegerField(unique=True) start_date=models.DateField(unique=True) end_date=models.DateField(unique=True) class Meta: db_table="fisical_year" constraints=[ models.CheckConstraint( check=Q(end_date__gte=F("start_date")+timedelta(days=365)), name="end_date constarint") , models.CheckConstraint( check=Q(end_date__month="9"), name="month constraint") ] -
Why my django project doesn't see the changes I made in my html file?
I'm working with "Web Development with Django" book where I'm building bookr project. It is a web page that shows books, their reviews and ratings. I am on chapter 5, where main thing that I am supposed to do is to add logo image to my page using static file serving and block brand. My main base.html in templates directory has everything required to call static image from another html file directory: bookr/templates/base.html {% load static %} <a class="navbar-brand" href="/">{% block brand %}Book Review{% endblock %}</a> Another base.html has block brand directory: bookr/reviews/templates/reviews/base.html {% extends 'base.html' %} {% load static %} {% block brand %}<img src="{% static 'static/logoo.png' %}">{% endblock %} the logo image is in this directory: bookr/reviews/static/logoo.png (it is not corrupted and working perfectly well) the setting.py for templates looks like this TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and finally the view.py def index(request): return render(request, "base.html") I want to note that any changes on html are not working, I tried to make the whole page red, django doesn't show any mistakes -
User Authorization with Djoser, DRF and Pinia
I've been facing difficulties with authorization for several days now. While my authentication appears to be functioning properly, I haven't been able to successfully implement posting data to my backend that uses DRF and Djoser. I think the issue is minor and I'm using Pinia, Nuxt3, Django, and DRF. my settings INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'djoser', 'corsheaders', 'blog', 'users', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } MIDDLEWARE = [ 'django.contrib.auth.middleware.AuthenticationMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] my main urls from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), path('user/', include('users.urls', namespace='user')), ] and user urls from django.urls import path, include from .views import CustomUserViewSet app_name = 'user' urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.authtoken')), path('auth/', include('djoser.urls.jwt')), path('custom/', CustomUserViewSet.as_view({'get': 'list'}), name='custom-list'), path('custom/<int:pk>/', CustomUserViewSet.as_view({'get': 'retrieve'}), name='custom-detail'), ] and my views from django.shortcuts import get_object_or_404 from rest_framework import generics, status, permissions from rest_framework.response import Response from .models import Category, Comment, Post from .serializers import PostSerializer, CommentSerializer, CategorySerializer User = get_user_model() class PostListCreateAPIView(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = "slug" permission_classes = [permissions.IsAuthenticated] def create(self, request, *args, **kwargs): … -
Resolve function resolving wrong view_name in django
Django 4.0 Python 3.9 I recently upgraded my django project from 3.14 to 4.0 and django.urls.resolve function seems broken. Resolve is always returning app_name.views.view instead of app_name.views.actual_function_name. Here is my code - path = request.path match = resolve(path) view_name = match.view_name after the above code "view_name" variable is always "view" irrespective of the url. Any help is appreciated. Thanks for your time. -
dynamic choice field got 'Select a valid choice. That choice is not one of the available choices'
I have 5 simple model class like this # Province class Provinsi(models.Model): id = models.CharField(max_length=3, primary_key=True) name = models.CharField(max_length=40) def __str__(self) -> str: return self.name # City class Kota(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=40) parent = models.ForeignKey(Provinsi, on_delete=models.CASCADE) def __str__(self) -> str: return self.name # District class Kecamatan(models.Model): id = models.CharField(max_length=8, primary_key=True) name = models.CharField(max_length=40) parent = models.ForeignKey(Kota, on_delete=models.CASCADE) def __str__(self) -> str: return self.name # Vilages class Desa(models.Model): id = models.CharField(max_length=12, primary_key=True) name = models.CharField(max_length=40) parent = models.ForeignKey(Kecamatan, on_delete=models.CASCADE) def __str__(self) -> str: return self.name # Locations class Lokasi(models.Model): name = models.CharField(max_length=10) provinsi = models.ForeignKey(Provinsi, on_delete=models.CASCADE) kota = models.ForeignKey(Kota, on_delete=models.CASCADE, blank=True) kecamatan = models.ForeignKey(Kecamatan, on_delete=models.CASCADE, blank=True) desa = models.ForeignKey(Desa, on_delete=models.CASCADE, blank=True) def __str__(self) -> str: return self.name All first 4 class don't have admin page, it's "injected" using custom manage command admin.py looks like class LokasiAdmin(admin.ModelAdmin): form = LokasiAdminForm change_form_template = 'lokasi_change.html' admin.site.register(Lokasi, LokasiAdmin) the template (lokasi_change.html) have some ajax call to update some choice fields based on change of other choice field. {% extends "admin/change_form.html" %} {% block after_field_sets %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> // add listeners document.getElementById("id_provinsi").addEventListener("change", changedProvinsi); document.getElementById("id_kota").addEventListener("change", changedKota); document.getElementById("id_kecamatan").addEventListener("change", changedKecamatan); function changedProvinsi(){ var myselect = document.querySelector('#id_provinsi'); var myvalue = myselect.value; var baseurl = window.location.origin; … -
TypeError: Field 'id' expected a number but got OrderedDict([('food', <FoodDetails: Nasi Goreng>), ('quantity', 2)])
I am trying to learn react and create a cart for my application I have two urls one for ordered items and one for the order in ordered items i store my multiple items and quantity and finally store the ordered items as items in my order here first i take ordereditems from my fooddetails url and then use that array of items for my order The food here is the id of ordered food, so that i can access its other properties if necessary The data i am sending seems okay as but the items array is empty in backend after i send the data const orderedItems = await Promise.all( cartItems.map(async (item) => { const response = await fetch( "http://127.0.0.1:8000/api/menu/fooddetails/" + item.id ); const food = await response.json(); const orderedItem: OrderedItem = { food: food.food_id, quantity: item.quantity, }; return orderedItem; }) ); const order: IOrderData = { items: orderedItems, total_price: totalAmount, total_items: totalQuantity, }; const response = await fetch("http://127.0.0.1:8000/api/order/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(order), }); const data = await response.json(); console.log(data); }; This is my models.py and serializers.py from menu.models import FoodDetails class OrderedItem(models.Model): food = models.ForeignKey(FoodDetails, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return … -
Trouble with login when gmail ALLAUTH and user's email coincide
models.py class MyUser(AbstractUser): username = None # remove username field email = models.EmailField(_("Email Address"), unique=True) full_name = models.CharField(verbose_name="Full Name",max_length=100) phone = PhoneNumberField(verbose_name="Phone Number", blank=True) is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # fields required when creating a new user in terminal objects = MyUserManager() def __str__(self): return self.full_name urls.py # gmail OAUTH path('accounts/', include('allauth.urls')), settings.py # Allauth Settings SITE_ID = 1 ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' SOCIALACCOUNT_LOGOUT_ON_GET=True SOCIALACCOUNT_LOGIN_ON_GET=True SOCIALACCOUNT_QUERY_EMAIL = True For your context, my app uses email instead of username to log the user in, and for OAUTH, I use gmail. At the moment, if I log in through gmail using an email that DID NOT REGISTER directly to the app, I will be able to log in like usual and redirected to the home page. But if I try to log in through gmail with an email that DID REGISTER to my app beforehand, I will be instead redirected to this url: http://127.0.0.1:8000/accounts/social/signup/ I am not sure why this is happening. Can someone help me with this? The desired result should be that for the latter scenario, the user should be redirected … -
How can I solve this ModuleNotFoundError: No module named 'core' error?
I am trying to deploy a django app using docker compose. I am currently having this error when the django app image is building. Two errors that stand out in the errors below is: noted_app | ModuleNotFoundError: No module named 'core' and postgres | 2023-04-08 00:44:43.169 UTC [50] FATAL: role "noted}" does not exist Please how can I resolve both errors. I am currently stuck with the deployment. postgres | postgres | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres | postgres | 2023-04-08 00:44:23.060 UTC [1] LOG: starting PostgreSQL 15.2 (Debian 15.2-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit postgres | 2023-04-08 00:44:23.061 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres | 2023-04-08 00:44:23.061 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres | 2023-04-08 00:44:23.069 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres | 2023-04-08 00:44:23.078 UTC [28] LOG: database system was shut down at 2023-04-08 00:43:52 UTC postgres | 2023-04-08 00:44:23.089 UTC [1] LOG: database system is ready to accept connections redis | 1:C 08 Apr 2023 00:44:23.465 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis | 1:C 08 Apr 2023 00:44:23.466 # Redis version=7.0.10, bits=64, …