Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
annotate is adding an extra object to my queryset
I'm using DRF. I've got the following code where I annotate a queryset of Company objects with an additional joined field. It seems annotate is adding an extra object to my queryset. views.py def get(self, request, **kwargs): user = request.user companies = Company.objects.all() print(companies) user_in_queue = When(queue__users=user, then = True) companies = Company.objects.annotate(joined=Case( user_in_queue, default = False )) print(companies) the first print gives me <QuerySet [<Company: kfc>, <Company: kfc>]> With a json of [ { "name": "kfc", "id": 1, }, { "name": "kfc", "id": 2, } ] The second gives me <QuerySet [<Company: kfc>, <Company: kfc>, <Company: kfc>]> With a json of [ { "name": "kfc", "id": 1, "joined": null }, { "name": "kfc", "id": 1, "joined": true }, { "name": "kfc", "id": 2, "joined": null } ] I want a json of [ { "name": "kfc", "id": 1, "joined": true }, { "name": "kfc", "id": 2, "joined": null } ] -
How can i remove any allauth page?
I want to remove signup, reset password, and change password page from allauth django app. what should i do? because I need only login page. enter image description here enter image description here -
Django - How to manipulate Form data before it gets saved to model?
here is my views.py ` def CreateCourseView(request): TeeFormSet = inlineformset_factory(Golf_Course, Golf_Tee, form=AddTeeForm, extra=1,) if request.method == "POST": course_form = AddCourseForm(request.POST) teeformset = TeeFormSet(request.POST, instance=course_form.instance) if course_form.is_valid(): course_form.save() if teeformset.is_valid(): teeformset.save() return redirect("/") else: course_form = AddCourseForm() teeformset = TeeFormSet() return render(request, "Courses/add_course_form.html", {'teeformset': teeformset,'course_form': course_form,}) ` here is a shortened view of my models.py ` class Golf_Tee(models.Model): # choice list of index values INDEX = [ (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), ] # choice list of par values PAR = [ (3, 3), (4, 4), (5, 5), ] course = models.ForeignKey(Golf_Course, on_delete=models.CASCADE) tee_name = models.CharField(max_length=255, unique=True) course_par = models.IntegerField() slope = models.DecimalField(decimal_places=2, max_digits=5) rating = models.DecimalField(decimal_places=2, max_digits=5) yardage = models.IntegerField() hole_1_par = models.IntegerField(choices=PAR, default = PAR[1][1]) hole_1_yardage = models.IntegerField(default = 0) hole_1_index = models.IntegerField(choices=INDEX, default = INDEX[0][0]) hole_2_par = models.IntegerField(choices=PAR, default = PAR[1][1]) hole_2_yardage = models.IntegerField(default = 0) hole_2_index = models.IntegerField(choices=INDEX, default = INDEX[0][0]) ` I'm trying to not have users enter in the total yardage, when they are already entering yardage for each hole. What I would like … -
Cannot configure pytest in my simple project
i have the folowing project structure, but when trying to run pytest in console i get error. Is the problem in pytest.ini? ERROR backend/tests/test_user.py - django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call backend |-foodgram |-foodgram |-manage.py |-api |-users |-tests |-pytest.ini in my pytest.ini [pytest] python_paths = foodgram/ DJANGO_SETTINGS_MODULE = foodgram.settings norecursedirs = env/* addopts = -vv -p no:cacheprovider testpaths = tests/ python_files = test_*.py -
Url with <int:pk> or <slug:slug> DJANGO
Stumped with this one, I need to be able to call an article via a pk or slug, for example user can do https://www.website.com/1 or https://www.website.com/article-slug both show the same article/page. And if neither 1 or slug exist show default article or nothing found. path('/', views.index, name='index’), path('slug:slug/', views.index, name='index’) Not sure how to proceed. -
Why am I getting "This field may not be null" errors when populating decimal and char fields from serialized data via Serializer in Django Model?
I am trying to populate DecimalField and CharField fields in a Django Model from serialized data via DRF Serializer, but I am getting strange errors of This field may not be null. Here is my model definition: class Product(BaseModel): product = models.CharField(max_length=255) recommended_action = models.CharField(max_length=255) recommended_action_value = models.DecimalField(max_digits=12, decimal_places=8) recommended_price = models.DecimalField(max_digits=12, decimal_places=8) rrp = models.DecimalField(max_digits=12, decimal_places=8) iam_price = models.DecimalField(max_digits=12, decimal_places=8) iam_index = models.DecimalField(max_digits=12, decimal_places=8) factor = models.DecimalField(max_digits=12, decimal_places=8) avg_in_stock = models.DecimalField( null=True, blank=True, max_digits=12, decimal_places=8 ) Here is my model serializer definition: class ProductSerializer(serializers.ModelSerializer): class Meta: model = models.Product fields = "__all__" And here is my view: @api_view(['POST']) def migrate_data(request, *args, **kwargs): if request.method == "POST": data = json.loads(request.body) product_serialized_data = serializers.ProductSerializer( data=data, many=True, context={"request": request}, ) if not product_serialized_data.is_valid(): print(product_serialized_data.errors) product_serialized_data.save() return Response(data={"detail": "Success"}) This is the data that I am passing to the POST request: { "product": "DE_Ford_2095160", "recommended_action": "increase", "recommended_action_value": 0.0315553, "recommended_price": 14.5862, "rrp": 14.14, "iam_price": 6.56898, "iam_index": 0.464567, "factor": 2.15254, "avg_in_stock": 1 } When I run this code, I get the following errors: [{'recommended_action': [ErrorDetail(string='This field may not be null.', code='null')], 'recommended_action_value': [ErrorDetail(string='This field may not be null.', code='null')], 'recommended_price': [ErrorDetail(string='This field may not be null.', code='null')], 'rrp': [ErrorDetail(string='This field may not be null.', code='null')], … -
sqlite3.OperationalError: foreign key mismatch during the creation of test DB
During the creation of the test database, I got an error sqlite3.OperationalError: foreign key mismatch - "history_message" referencing "history_device". This error is caused by the 1st migration file: import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Device', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('description', models.TextField(blank=True, null=True)), ('username', models.CharField(max_length=100)), ('client_id', models.CharField(max_length=100)), ], options={ 'verbose_name': 'Device', 'verbose_name_plural': 'Devices', }, ), migrations.CreateModel( name='Message', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField()), ('message', models.TextField()), ('client_id', models.CharField(max_length=100)), ('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='history.device')), ], options={ 'verbose_name': 'Message', 'verbose_name_plural': 'Messages', }, ), ] I don't understand because I don't have any issues with the "prod db" but only with the "test db". -
Django - 'This field is required on form' load
I have a Django view that shows two create forms. Whenever the page loads all of the input fields display - 'This field is required". enter image description here Template code {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ listing_create_form.as_p }} {{ listing_media_form.as_p }} <button type="submit">Submit Form</button> </form> {% endblock %} views.py @login_required def createListing(request): listing_create_form = ListingCreateForm(request.POST or None, request.FILES) listing_media_form = ListingMediaForm(request.POST or None, request.FILES) if request.method == 'POST': if listing_create_form.is_valid() and listing_media_form.is_valid(): listing_create_form.instance.created_by = request.user form = listing_create_form.save() form.save() new_listing_id = form.pk # loop over images to upload multiple for image_uploaded in request.FILES.getlist('image'): image_instance = ListingMedia.objects.create(listing=form, image=image_uploaded) image_instance.save() return redirect('boat_listings') context = {'listing_create_form': listing_create_form, 'listing_media_form': listing_media_form} return render(request, 'listings/listing_create_form.html', context) forms.py class ListingCreateForm(forms.ModelForm): class Meta: model = Listings widgets = { "featured_image": forms.FileInput( attrs={ "enctype": "multipart/form-data" } ), } fields = "__all__" exclude = ("created_by", "created_on", "last_modified",) class ListingMediaForm(forms.ModelForm): class Meta: # image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) widgets = { "image": forms.ClearableFileInput( attrs={ "multiple": True } ), } model = ListingMedia fields = ['image'] Django template should render without field required message before user has inputted invalid inputs. -
How do I access the request object in a form_class, django, CBV
I am trying to pass the data from the request to my form. Currently, that is resulting in an error: 'NoneType' object has no attribute 'user' My view: class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task template_name = "tasks/task_form.html" form_class = DateInputForm My view (get_form_kwargs function): def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs() form_kwargs['request'] = self.request return form_kwargs Init from my form : def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) request = kwargs.pop('request', None) self.fields['tags'].queryset = Tag.objects.filter(user=request.user.id) -
Passing a variable to include in extends in Django templates
I have the following structure of templates: main.html <html> <body> <p> This works: {% block title %}{% endblock %} </p> {% include 'heading.html' with title=title %} {# but this does not work since it is not a variable #} </body> </html> heading.html <p> {{ title }} </p> page.html {% extends 'main.html' %} {% block title %}test title{% endblock %} How can I pass the title from page.html to heading.html? Ideally, it should be defined as a block like now, but alternatives are also welcome. I'd like to contain the solution within the templates if possible. -
In Django, how do I remove a permission from my site?
I added a permission to a model using the way recommended in the Django docs. E.g. class Car(Model): class Meta: permissions = ( ('can_drive', 'User is allowed to drive this car'), ) I then decided I don't want that permission so I removed the class Meta... code and ran: ./manage.py makemigrations ./manage.py migrate ./manage.py told me it removed the class Meta... code but the permission is still in Django admin. -
Need Help Regarding This Query in django model
class Post(models.Model): post_uuid = models.UUIDField(default=uuid.uuid4, editable=False) user = models.ForeignKey( User, related_name='post_model', on_delete=models.CASCADE) post_categories = models.ManyToManyField( 'Categories', through='PostCategories', blank=True) created_on = models.DateTimeField(default=timezone.now) updated_by = models.DateTimeField(null=True, blank=True) updated_on = models.DateTimeField(null=True, blank=True) deleted_by = models.DateTimeField(null=True, blank=True) deleted_on = models.DateTimeField(null=True, blank=True) class Meta: ordering = ["-created_on"] indexes = [ models.Index(fields=['post_uuid',]), models.Index(fields=['created_on',]), ] def __str__(self): return '{}'.format(self.id) class PostInLanguages(models.Model): post_in_language_uuid = models.UUIDField( default=uuid.uuid4, editable=False) post = models.ForeignKey( Post, related_name='post_language', null=False, on_delete=models.CASCADE) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_language = models.BooleanField(default=True) parent_post_language_id = models.PositiveIntegerField(null=True) description = models.CharField(max_length=400, null=True, blank=True) like = models.ManyToManyField( 'User', through='PostLanguageLike', related_name='post_like', blank=True) hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return '{}'.format(self.post.id) class Meta: indexes = [ models.Index(fields=['post_in_language_uuid', 'parent_post_language_id', 'is_post_language']), ] recouch_obj = PostInLanguages.objects.annotate(Count('parent_post_language_id')).filter(parent_post_language_id__count__gte=minimum_recouch,is_post_language=False).values_list("parent_post_language_id") Can anyone help to figure out what will this query return I just need postinlanguage object query set with minimum recouch filter Is_lang_post = True means this is a post If false means this is post of another post that means recouch -
404 error on new pages with wordpress blog ( on mysql) with django (postgres) using nginx on the same server
Condition : I have set up my server as follows : my wordpress blog ( on mysql) with django (postgres) using nginx on the same server. Error I am getting 404 error for new pages I create on the blog. ( it works when permalink settings is like this : https://www.example.com/blog/?p=1 It does not work when permalink setting contains post name New pages I create also behave in similar fashion - do not work with name slug My analysis is that it has something to do with ssl conf or nginx conf. Basically routing issue. I am a newbie. Here is the Nginx Conf: upstream app_server { server unix:/home/user/opt/env/run/gunicorn.sock fail_timeout=0; } #wordpress php handler upstream wordpress-prod-php-handler { server unix:/var/run/php/php7.0-fpm.sock; # serve wordpress from subdirectory location /blog { alias /home/user/opt/blog; index index.php; try_files $uri $uri/ /blog/index.php?$args; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_pass wordpress-prod-php-handler; } } Please help.. As specified, I was trying to get my blog and app on the same domain. www.example.com -> opens django app www.example.com/blog -> opens wordpress blog Now it works fine, but if anything comes after /blog -- such as example.com/blog/test will result in a 404 error. Nginx error log shows this … -
custom django form field (django-recaptcha) is not added to AuthenticationForm class
objective: adding a new field from (captcha field) within Django Admin Login Form. enabling below method (google captcha v2 - I'm not robot checkbox): https://github.com/torchbox/django-recaptcha Django: Tested on 4.0.X, 4.1.X, 3.2.X versions. project name: ea_games app name: ea_app ea_games\ea_app\froms.py: from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import get_user_model from django import forms from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV2Checkbox class CustomLoginForm (AuthenticationForm): #class Meta: # model = get_user_model() # fields = ('required_checkbox',) ## comment/un-comment didn't work. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) required_checkbox = forms.BooleanField(required=True) ## added to test but it's not showed in django admin login form. username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Username or Email'}), label="Username or Email") password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password'}), label="Password") captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox()) ea_games\ea_app\views.py: class CustomLoginView (LoginView): form_class = CustomLoginForm template_name = "ea_app/login.html" def form_invalid (self, form): print ("form_invalid:::::", form) ## it's not called to print :/ return self.render_to_response (self.get_context_data(form=form)) def form_valid (self, form): print ("form_valid::::::", form) ## it's not called to print :/ checkbox = form.cleaned_data['required_checkbox'] return super().form_valid(form) ea_games\ea_app\templates\ea_app\login.html: {% extends "admin/login.html" %} Also for project's urls.py file, i checked many solutions and they didn't work: ea_games\urls.py: from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings … -
How to get id from another table in django?
I am writing a script to populate database tables. I need to get foreign key from city table. There are 3 fields in the City table: id, name, reference. I need a foreign key for the Warehouses table with fields id, name,reference, city_id (foreign key). I take all the data from the API. def refresh_warehouses(): api_domain = 'https://api.novaposhta.ua' api_path = '/v2.0/json/Address/getWarehouses' api_data = { "modelName": "Address", "calledMethod": "getWarehouses", "methodProperties": { "Limit": "5" }, 'apiKey': settings.NOVA_POSHTA_API_KEY } response = requests.post(api_domain + api_path, json=api_data).json() if not response.get('success'): raise Exception(','.join(response.get('errors'))) Warehouse.objects.all().delete() warehouses = [] for item in response.get('data'): params = { 'name': item.get('Description'), 'reference': item.get('Ref'), 'city_id': City.objects.get(name=item.get("CityDescription")).id, 'delivery_method_id': 1 } warehouses.append(Warehouse(**params)) Warehouse.objects.bulk_create(warehouses) After executing the script, django throws a FOREIGN KEY constraint failed error. Tell me how best to take the id from the City table? -
How to get all items related to a Foreign Key in django?
My aim is to get all the items with a particular category from the model I created. For example, if I should get a category with an ID, I want to get all the products that is in that category. Below is my model class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, on_delete=models.SET_NULL) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.name class Category(models.Model): #product = models.ForeignKey('Product', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200, blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.name Below is my view def getCategory(request, pk): category = Category.objects.get(id=pk) # product = Product.objects.all() products = Product.category_set.all() # Product.category_set.all() context = {'category': category, 'products':products} return render(request, '*.html', context) I tried using Product.category_set.all() and I have tried to flip it over, getting the products relaed to the category that I got the ID but I dont know how I can do that. I used this loop below in my template and it worked but I wonder if there is a better way to do it. Template {% for product in products %} {% if product.category.id == category.id %} View def getCategory(request, pk): category = Category.objects.get(id=pk) products = Product.objects.all() context = {'category': category, 'products':products} return render(request, … -
User can't login because of "Invalid password format or unknown hashing algorithm."-Django
I'm learning Django and tried to write my own custom user model. I'm not using DRF and serializers and stuffs I have no idea about :) I am using createView to create users but I can't login because "Invalid password." I checked the user's password in admin and the user's password is "Invalid password format or unknown hashing algorithm." . here are the codes: Custome User and User Manager in models class UserManager(UserManager): def create_user(self, username, email, password, **extra_fields): if not email: raise ValueError('User must have email') if not username: raise ValueError('User must have username') user = User.objects.create_user( username=username, email=self.normalize_email(email), ) user.set_password(password) user.save() return user def create_superuser(self, username, email, password, **extra_fields) : user = self.create_user(username, email, password) user.is_staff = True user.is_superuser = True user.is_admin = True user.is_active = True user.save() return user class User(AbstractBaseUser): username = models.CharField(unique=True, max_length=200) email = models.EmailField(unique=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(auto_now=True) objects = UserManager() REQUIRED_FIELDS = ["username","email", "password"] USERNAME_FIELD = "username" def __str__(self): return self.email def has_perm(self, perm, object=None): "Does the user have a specific permission?" return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # … -
django: modelChoiceField form not working in template
I am confronted for the first time to a situation where I want the user to select model column values based on some constraint. The goal is to have the user select something and then output the result below the form on the same page. I am not sure what I am doing wrong but submiting the form output: Select a valid choice. That choice is not one of the available choices. Here is what I have been able to do: forms.py class SelectBuildingForm(forms.Form): filename = forms.ModelChoiceField(queryset=Building.objects.none()) def __init__(self, *args, **kwargs): us = args[1] or None forms.Form.__init__(self, *args, **kwargs) self.fields['filename'].queryset = Building.objects.filter(project=us).values_list('filename',flat=True) views.py @login_required @owner_required def FileSelectionView(request,pk): form = SelectBuildingForm(request.POST or None, pk) # if form.is_valid(): # filename = form.cleaned_data('filename') # print(filename) # return redirect('comparator_test') return render(request,'files_selection.html', {'form':form}) and template <div class="mt-5 md:col-span-2 md:mt-0"> <form method="POST" id="my-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" value="Select">GOOOO</button> </form> {% if form.is_valid %} {% for choice in form.cleaned_data.choices %} <p>{{ choice }}</p> {% endfor %} {% endif %} </div> I have tried a couple options to validate the selection but none of them work. Can a pair of fresh eyes see where I am messing up? -
How can I call an asynchronous function inside my synchronous Consumer?
In my django quiz project I work with Channels. My consumer QuizConsumer is synchronous but now I need it to start a timer that runs in parallel to its other functions and sends a message after the timer is over. class QuizConsumer(WebsocketConsumer): def configure_round(self, lobby_id): # Call function to send message to begin the round to all players async_to_sync(self.channel_layer.group_send)( self.lobby_group_name, { 'type':'start_round', 'lobby_id':lobby_id, } ) self.show_results(lobby_id, numberVideos, playlength) def start_round(self, event): self.send(text_data=json.dumps({ 'type':'start_round', 'lobby_id': event['lobby_id'] })) def show_results(self, lobby_id, numberVideos, playlength): async_to_sync(self.channel_layer.group_send)( self.lobby_group_name, { 'type':'show_results_delay', 'lobby_id':lobby_id, 'numberVideos':numberVideos, 'playlength':playlength, } ) def show_results_delay(self, event): time.sleep(event['numberVideos']*event['playlength']+5) self.send(text_data=json.dumps({ 'type':'show_solution', 'lobby_id': event['lobby_id'] })) I tried to work with async functions and await, but I did not get it to work as I expected yet. I tried to work with async functions but so far it disconnected from the websocket or it did not send the "start_round" until the timer was finished. -
Postgresql : Global replace all foreign key references to a row with another
I am using postgres with Django. I have a table of users. The rows are referenced in other tables as foreign keys. Some times, we want to merge two user rows into one. We want to replace all references to a particular row with another. Is this possible? -
How to save 1 information to 2 tables on Django
How can I save 1 information to 2 tables on Django, when user register he entres his username, and I need to save this username in table "users" and in table "authors", how can i realize it? views.py def register(request): if request.method == 'POST': nick = request.POST.get('nick') email = request.POST.get('email') password = request.POST.get('password') ppassword = request.POST.get('ppassword') if password == ppassword: new_user = User.objects.create_user(nick, email, password) new_user.nick = nick new_user.email = email new_user.save() return redirect('../login/') else: return HttpResponse("Пароль и повтор пароля не совподают") return render(request, 'main/register.html') models.py class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) username = models.CharField(max_length=40, blank=True) slug = slug = models.SlugField(max_length=400, unique=True, blank=True) bio = HTMLField() profile_pic = ResizedImageField(size=[50, 80], quality=100, upload_to="authors", default=None, null=True, blank=True) def __str__(self): return self.username @property def num_posts(self): return Post.objects.filter(user=self).count() def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.username) super(Author, self).save(*args, **kwargs) Regards, Idris. -
Reverse for 'login' not found. 'login' is not a valid view function or pattern name
[Reverse for 'login' not found. 'login' is not a valid view function or pattern name.[Main.urls[Views.pyUrls.py](https://i.stack.imgur.com/Q88iG.png)](https://i.stack.imgur.com/MPxwl.png)](https://i.stack.imgur.com/9KYhw.png) NoReverseMatch at /user/signup/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Request Method:POSTRequest URL:http://127.0.0.1:8000/user/signup/Django Version:4.1.4Exception Type:NoReverseMatchException Value:Reverse for 'login' not found. 'login' is not a valid view function or pattern name.Exception Location:C:\Users\JOSHI\OneDrive\Desktop\Watch Store\Venv\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefixRaised during:User.views.signupPython Executable:C:\Users\JOSHI\OneDrive\Desktop\Watch Store\Venv\scripts\python.exePython Version:3.9.0Python Path:['C:\\Users\\JOSHI\\OneDrive\\Desktop\\Watch Store\\Online_Shop', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\JOSHI\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\JOSHI\\OneDrive\\Desktop\\Watch Store\\Venv', 'C:\\Users\\JOSHI\\OneDrive\\Desktop\\Watch Store\\Venv\\lib\\site-packages']Server time:Sat, 31 Dec 2022 06:39:18 +0000 -
How to upload multiple images to Django?
I am trying to send some data from the client side (react native) that includes a few images so I append them to formdata and successfully send it through a post request but I am having trouble figuring out how to handle it on the server side. My react code: const post = async () => { const token = await getToken(); const [description, setDescription] = useState(''); const formData = new FormData(); images.forEach((image) => { formData.append(`images`, { uri: image, type: 'image/jpeg', name: image, }); }); formData.append('description', description); console.log('formdata:', formData); try { await axios.post(URL, formData, { headers: { 'Content-Type': 'multipart/form-data', Authorization: token, }, }); } catch (e) { console.log(e); } }; when i console log formdata on client side i get: formdata: [["images", {"name": "/Library/Developer/CoreSimulator/Devices/123.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/123.jpg"}], ["images", {"name": "/Library/Developer/CoreSimulator/Devices/456.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/456.jpg"}], ["description", "Test"]] on my server side (django/drf): models.py: class Post(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE, default=None ) images = models.FileField( max_length=3000, default=None, null=True, blank=True, upload_to='media/post_images') description = models.TextField(null=False, default=None) date = models.DateTimeField(editable=False, auto_now_add=True) serializers.py: class PostSerializer(serializers.ModelSerializer): images = serializers.FileField() class Meta: model = Post fields = "__all__" views.py class PostView(APIView): serializer_class = PostSerializer parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None): form_data = request.data images … -
RollupError: "default" is not exported by "node_modules/react-infinite-scroller/index.js"
Using v1.2.6 of react-infinite-scroller in a reactjs .tsx bumps into the following build error: [!] RollupError: "default" is not exported by "node_modules/react-infinite-scroller/index.js", imported by "src/core/DataTable.tsx". https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module src/core/DataTable.tsx (6:7) 6: import InfiniteScroll from 'react-infinite-scroller'; What do I miss? -
Django Application CPanel Internal Server Error 500
I am getting a Internal Server Error in my Django Application hosted in Cpanel . I have tables with Links and sublinks associated with those links . so the url is like https://[domain]/links/ and https://[domain]/links// . Everything works fine on local host but whenever i go to the Sublink in the live website I get 500 Error. I am really lost as I dont know how to debug this . I dont know how to start to look at the error . I looked at the log file and this is the ouput . Can anyone tell me how to start debug this error since its running properly on the localhost so I cant find anything .