Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The Django admin site
I start the development server and explore it. When I open the Web browser and go to “/admin/” on my local domain, http://127.0.0.1:8000/admin/.I face this screen: enter image description here -
Django: Query .all() not hitting the database
THe django docs says: Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you’ll definitely have a QuerySet to work with. When a QuerySet is evaluated, it typically caches its results. If the data in the database might have changed since a QuerySet was evaluated, you can get updated results for the same query by calling all() on a previously evaluated QuerySet. I am using Django-Debug-Toolbar to optimize a query. If I have code like this (returning an empty list to ensure .all() is hitting the DB at this point in time: def get_querysets(): foo_list = Foo.objects.filter(...).all() bar_list = Bar.objects.filter(...).all() caz_list = Caz.objects.filter(...).all() return [] then Django debug toolbar won't register those queries, i.e. DB was not querried. However if I change it to: def get_querysets(): foo_list = Foo.objects.filter(...).all() bar_list = Bar.objects.filter(...).all() caz_list = Caz.objects.filter(...).all() print(foo_list) print(bar_list) print(caz_list) return [] Now in the toolbar I can see the queries. I know querysets are lazy, but the whole point of .all() is to make it hit the … -
Not viewing file in flutter
I have converted my Django website into flutter app. in that website, view file link is there. but in APK file, it is not viewing when I click on it. How to solve this problem. Please tell. -
created virtual environment , but cant access it
it shows created virtual environment. But it is not redirect to virtual environment . after I upgraded the pip no changes where appear . please help me to get that. enter image description here -
Django regex not working when adding other branches to url
I am a complete beginner in Django, and I have encountered a problem while trying to set up a url for each "room". Here is the code: from django.conf.urls import url from . import views urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^room/<str:pk>/$', views.room, name='room'), ] Everything was working perfectly, until I add /<str:pk>/$. I have also add this code in the views.py section: def room(request,pk): return render(request, 'base/room.html') However I still get an error when loading the website. Image of the error message Does someone know how to make it work? -
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser
I'm trying to use Django REST Framework with ModelSerializer to handle user authentication, but I haven't found an elegant way to add the user to my entry. Here is my models class Entry(models.Model): slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=200) description = models.TextField() publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) these are the serializers used to create the user and entry class EntrySerializer(serializers.ModelSerializer): class Meta: model = Entry fields = ['slug', 'author', 'created', 'modified', 'title', 'description'] read_only_fields = ['code', 'author', 'slug', 'created', 'modified'] def create(self, validated_data): if self.request.user.is_authenticated: validated_data['author'] = self.request.user return super().create(validated_data) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = {'password':{ 'write_only':True, 'required':True }} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user these are the ModelViewSets to render the models into views class PostUserWritePermission(BasePermission): def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.author == request.user class EntryViewSet(viewsets.ModelViewSet, PostUserWritePermission): queryset = Entry.objects.all() serializer_class = EntrySerializer lookup_field = 'slug' permission_classes = [PostUserWritePermission] authentication_classes = (TokenAuthentication,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
What happens to other attributes after Django queryset distinct is used?
On this query set what will happen to the score attribute if I do something like: myqset.distinct('Name')? Does it just take one of the score values or is there something I can do to get the average of the scores? Name Score John 100 John 90 Adam 80 Adam 70 -
ProgrammingError at /products/ or 500 error when i click to another app in Heroku but it works locally
My project works locally but i get 500 errors on heroku when trying to press a link to another app which was products in my project. I gProgrammingError at /products/ relation "products_product" does not exist LINE 1: ...uct"."image_url", "products_product"."image" FROM "products_... "2022-02-19T01:51:05.415919+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/loader_tags.py", line 150, in render 2022-02-19T01:51:05.415919+00:00 app[web.1]: return compiled_parent._render(context) 2022-02-19T01:51:05.415920+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 162, in _render 2022-02-19T01:51:05.415920+00:00 app[web.1]: return self.nodelist.render(context) 2022-02-19T01:51:05.415920+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 938, in render 2022-02-19T01:51:05.415921+00:00 app[web.1]: bit = node.render_annotated(context) 2022-02-19T01:51:05.415921+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 905, in render_annotated 2022-02-19T01:51:05.415922+00:00 app[web.1]: return self.render(context) 2022-02-19T01:51:05.415922+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/loader_tags.py", line 62, in render 2022-02-19T01:51:05.415923+00:00 app[web.1]: result = block.nodelist.render(context) 2022-02-19T01:51:05.415923+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 938, in render 2022-02-19T01:51:05.415923+00:00 app[web.1]: bit = node.render_annotated(context) 2022-02-19T01:51:05.415924+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 905, in render_annotated 2022-02-19T01:51:05.415924+00:00 app[web.1]: return self.render(context) 2022-02-19T01:51:05.415924+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 988, in render 2022-02-19T01:51:05.415924+00:00 app[web.1]: output = self.filter_expression.resolve(context) 2022-02-19T01:51:05.415924+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/base.py", line 698, in resolve 2022-02-19T01:51:05.415925+00:00 app[web.1]: new_obj = func(obj, *arg_vals) 2022-02-19T01:51:05.415925+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/template/defaultfilters.py", line 550, in length 2022-02-19T01:51:05.415925+00:00 app[web.1]: return len(value) 2022-02-19T01:51:05.415925+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/db/models/query.py", line 269, in len 2022-02-19T01:51:05.415926+00:00 app[web.1]: self._fetch_all() 2022-02-19T01:51:05.415926+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages /django/db/models/query.py", line 1303, in _fetch_all 2022-02-19T01:51:05.415926+00:00 app[web.1]: … -
Django database deployment issue regarding database
When I run app server locally through "python manage.py runserver" I am able to register users into my postgresql database but when I open my website with the url it is hosted with, it doesn't do anything when I submit the register. It just returns me to the home page with no new user in the database. Any obvious reasons for such behavior? -
Django forms: object has no attribute cleaned data
I'm fairly new to Django. I have been getting this error when I try to use form.cleaned_data. Everywhere I've checked online says that this is because you might not be using the is_valid function which I am. My objective is to create a set of records which stores the student ID and the subject ID as foreign keys in a model called Sub_and_stu. I'm open to any other (as simple?) ways of achieveing this. views.py @csrf_protect def select_subs(request): form1 = Sub_selection1(request.POST) form2 = Sub_selection2(request.POST) form3 = Sub_selection3(request.POST) form4 = Sub_selection4(request.POST) user = request.user if form1.is_valid and form2.is_valid and form3.is_valid and form4.is_valid: data1 = form1.cleaned_data sub1=data1['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub1) data2 = form2.cleaned_data sub2=data2['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub2) data3 = form3.cleaned_data sub3=data3['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub3) data4 = form4.cleaned_data sub4=data4['subject_id'] Sub_and_stu.objects.create(student_id=user,subject_id=sub4) context={'form1':form1,'form2':form2,'form3':form3,'form4':form4} return render(request,'select_subs.html',context) models.py class Subject(models.Model): subject_id=AutoSlugField(unique=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Sub_and_stu(models.Model): record_id=AutoSlugField(unique=True) student_id=models.ForeignKey(User,on_delete=models.CASCADE) subject_id=models.ForeignKey(Subject,on_delete=models.CASCADE) class Sub_and_teachers(models.Model): record_id=AutoSlugField(unique=True) teacher_id=models.ForeignKey(User,on_delete=models.CASCADE) subject_id=models.ForeignKey(Subject,on_delete=models.CASCADE) forms.py class Sub_selection1(ModelForm): class Meta: model = Sub_and_stu fields=['subject_id'] #Other subject selection forms are basically a copy of this. I need the user to pick multiple subejcts at the same time snippet from select_subs.html <form> {%csrf_token%} <h3>Subject 1</h3> {% render_field form1.subject_id class='pure-input-1 pure-input-rounded' } <h3>Subject 2</h3> {% render_field form2.subject_id class='pure-input-1 pure-input-rounded' } <h3>Subject 3</h3> {% … -
How to Nest URL routes in Django Rest Framework (DRF) RetrieveUpdateDestroyAPIView without router
I am using the Django rest framework and RetrieveUpdateDestroyAPIView and trying to Implement nested URL patterns. # my current URLs structure is like /api/v1/kitchens/ - ListCreateAPIView /api/v1/kitchens/1/ - RetrieveUpdateDestroyAPIView /api/v1/orders/ - ListCreateAPIView /api/v1/orders/1/ - RetrieveUpdateDestroyAPIView /api/v1/items/ - ListCreateAPIView /api/v1/items/1/ - RetrieveUpdateDestroyAPIView The above structure works fine with all the operations but to get the list of items or orders under a single kitchen I am trying to achieve something live below. the views.py has something like below. class KitchenListView(generics.ListCreateAPIView): queryset = Kitchen.objects.all() serializer_class = KitchenSerializer pagination_class = LimitOffsetPagination permission_classes = (permissions.IsAuthenticatedOrReadOnly,) authentication_classes = (TokenAuthentication,) filter_backends = (DjangoFilterBackend,) filter_fields = ("user",) class KitchenDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Kitchen.objects.all() serializer_class = KitchenDetailsSerializer permission_classes = ( permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, ) authentication_classes = (TokenAuthentication,) # I want to create this structure. /api/v1/kitchens/ - List /api/v1/kitchens/1/ - Details /api/v1/kitchens/1/orders/ - Orders List /api/v1/kitchens/1/orders/1/ - Order Details /api/v1/kitchens/1/items/ - Items List /api/v1/kitchens/1/items/1/ - Item Details I am trying to achieve something like this. Please suggest to me the better solution if anyone has and what would be better to go with generic API views or Viewsets as my project is a large-scale project. Thanks in Advance. -
Access to XMLHttpRequest at 'http://localhost:8000/api/auth/jwt/create/' from origin 'http://localhost:63342' has been blocked by CORS policy:
I am trying to connect django and Vue API to login. I am using JWT with simple jwt and djoser library, and I have already created user. As you can see the postman, it works fine. Does anyone know how to fix this error?? However, I cannot connect from index.html (ajax) This is the ajax. .... var app = new Vue({ el: '#app', data: { email: '', password: '' }, mounted: function() {}, methods: { login(){ if (this.email == ''||this.password == '') { alert("Email or password cannot be empty"); location. reload(); } var data_l = {}; data_l.email = this.email; data_l.password = this.password; var formData = JSON.stringify(data_l); console.log(formData); $.ajax({ url: "http://localhost:8000/api/auth/jwt/create/", type: "post", dataType: "json", data: formData, contentType: "application/json", success: function(rs) { console.log(rs); if (rs.code == "0") { console.log(rs); alert("Login successful!"); window.location.href = ""; } else { alert(rs.msg); } }, error: function() {} }); }, jump_to_signup() { window.location.href = "signup.html"; }, jump_to_Fpwd(){ window.location.href = "forgotpassword.html"; } } }) </script> </body> </html> This is settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'fitness_app', 'user', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'fitness.urls' CORS_ORIGIN_ALLOW_ALL = True -
django-celery-beat loading task but not executing?
I have an application structured as follows. - api -api settings.py celery.py -core tasks.py -scripts cgm.py On running the following command I can see my task get loaded into the database however it does not actually run and I'm trying to understand why. celery -A api beat -l debug -S django_celery_beat.schedulers.DatabaseScheduler Here is my code. settings.py (relevant parts) INSTALLED_APPS = ( ..., 'django_celery_beat', ) CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') app = Celery('api') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py from django_celery_beat.models import PeriodicTask, IntervalSchedule schedule, created = IntervalSchedule.objects.get_or_create( every=10, period=IntervalSchedule.SECONDS, ) PeriodicTask.objects.get_or_create( interval=schedule, name='Import Dexcom Data', task='core.scripts.cgm.load_dexcom', ) cgm.py from monitor.models import GlucoseMonitor def load_dexcom(): from core.models import User user = User.objects.get(username='xxx') from pydexcom import Dexcom dexcom = Dexcom("xxx", "xxx", ous=True) # add ous=True if outside of US bg = dexcom.get_current_glucose_reading() data = GlucoseMonitor.objects.create( user = user, source = 1, blood_glucose = bg.mmol_l, trend = bg.trend, created = bg.time ) data.save() I can run the load_dexcom() manually and it works. My guess is I'm not dot-walking the task properly and it's not finding it but it's not showing any errors in the code. When I run the celery command I can see it load the record … -
Distinct not working in DRF sqlite database
Distinct not working.I am using sqlite in backend class getPatient(generics.ListAPIView): def list(self, request): queryset = Patient.objects.distinct() serializer = PatientSerializer(queryset, many=True) return Response({'patient': serializer.data}) -
Issue with django request,get user from bd
I have little problem with request to bd. I cant get users from bd.Maybe I didnt something wrong.I think,problem in request. Maybe, I think, I have error in views.py. view.py def registerform(request): ##registerform form = SightUp(request.POST or None) if form.is_valid(): user_obj = form.save()#Сохранение значений в датабазе методом .save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') email = form.cleaned_data.get('email') user = authenticate(username=username,password =raw_password,email=email) login(request,user) return redirect('/userprofile/')# ЗАМЕНИТЬ context = {'form':form } return render(request,'user.html',context) #def userprofiles(request): # userall = detailsuser.objects.all() # context = { # 'objects':userall # } # return render(request,'userprofile.html', context) class UserView(ListView): model = User template_name = 'userprofile.html' context = 'detailsuser' def get_queryset(self): return detailsuser.objects.filter(user = self.request.user) forms.py class SightUp(UserCreationForm): first_name = forms.CharField( widget = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name') last_name = forms.CharField( widget = forms.TextInput(attrs={'class':'form-control','placeholder':'Last name'}), max_length=32) email = forms.EmailField(widget =forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Email'}), max_length =64,help_text='Enter valid Email') username = forms.CharField(widget =forms.TextInput(attrs={'class':'form-control','placeholder':'Username'})) password1 = forms.CharField(widget =forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password1'})) password2 = forms.CharField(widget =forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password2'})) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('first_name','last_name','email') user.html {% for i in detailsuser %} <h1> yourname: i.email </h1> {% endfor %} <h1>Your last name:</h1> <h1>Your nickname:</h1> models.py class detailsuser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) -
Errno 5 Input/output error when closing console
I have a video converter which is converting audio and video files. Everything works but if I close my terminal from my server the audio file convert doesnt work anymore. I use PyTube for converting and moviepy for converting the mp4 from pytube into mp3. (I think the problem has something to do with moviepy bc. before I didnt have it.) This is my code for converting audio: if format == "3": yt = YouTube(videolink) downloads = MEDIA_ROOT + "/videos/" ys = yt.streams.filter(file_extension='mp4').first().download(downloads) base, ext = os.path.splitext(ys) basename = os.path.basename(base + uuid + '.mp3') videoclip = VideoFileClip(ys) audioclip = videoclip.audio audioclip.write_audiofile(base + uuid + ".mp3") audioclip.close() videoclip.close() maybe something with the os code is wrong. But I cant figure out why it works if I leave the console open. Im thankful for every help I get. -
REST Django - How to Modify a Serialized File Before it is Put Into Model
I am hoping that I can find a way to resize an uploaded image file before it is put into the database. I am new to Django with REST, so I am not sure how this would be done. It seems that whatever is serialized is just kind of automatically railroaded right into the model. Which I suppose is the point (it's certainly an easy thing to setup). To clarify, I already have a function tested and working that resizes the image for me. That can be modified as needed and is no problem for me. The issue really is about sort of "intercepting" the image, making my changes, and then putting it into the model. Could someone help me out with some ideas of tactics to get that done? Thanks. The Model: class Media(models.Model): objects = None username = models.ForeignKey(User, to_field='username', related_name="Upload_username", on_delete=models.DO_NOTHING) date = models.DateTimeField(auto_now_add=True) media = models.FileField(upload_to='albumMedia', null=True) file_type = models.CharField(max_length=12) MEDIA_TYPES = ( ('I', "Image"), ('V', "Video") ) media_type = models.CharField(max_length=1, choices=MEDIA_TYPES, default='I') user_access = models.CharField(max_length=1, choices=ACCESSIBILITY, default='P') class Meta: verbose_name = "MediaManager" The View with post method: class MediaView(APIView): queryset = Media.objects.all() parser_classes = (MultiPartParser, FormParser) permission_classes = [permissions.IsAuthenticated, ] serializer_class = MediaSerializer def post(self, … -
how to add new option for select tag in select2 - remote data
I've implemented an application, in one the forms there are alot of data in its drop down field, it takes some time to load that page, so i want to load it in ajax call, but the calling back data not creating new option tag and append to select tag, here is what i tried i tried all of these codes but non of them worked ! $(document).ready(function () { $('#guestinfo').select2({ ajax: { url: '{% url "booking:return_ajax_guests" %}', dataType: 'json', processResults: function (data) { console.log(data.length) if(data.length > 0){ for(i=0;i <= data.length;i++){ //var options = data[i].full_name //console.log(options) //$('#guestinfo').append("<option value='"+options+"'>"+options+"</option>") //$('#guestinfo').trigger('change'); //var opts = new Option("option text", "value"); //$(o).html("option text"); //$("#guestinfo").append(o); $('#guestinfo').append($('<option>', { value: options, text : options })); } } //return { // results: $.map(data, function (item) { // $('#guestinfo').append("<option value='"+item.full_name+"' selected>"+item.full_name+"</option>") // $('#guestinfo').trigger('change'); // return {full_name: item.full_name, city: item.city__name}; // }) //console.log(results) //}; } }, minimumInputLength: 0 }); }) <div class="col-span-5 groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "full names" %}</label> <select name="guestinfo" id="guestinfo" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white"> <option value="------">---------</option> </select> </div> select2 version : 2.0.7 and here is my server side code (django) @login_required def return_ajax_guests(request): if request.is_ajax(): term … -
CSRF verification failed: is token not persisting between GET and POST? Django
I checked a lot of the older CSRF questions, but they seem to be from 5+ years ago and a lot of the solutions aren't applicable due to now being handled with render() or other built-in methods. So, here's my question: I'm rendering a form template from a class-based view. It loads fine when I hit the initial GET request, but when I try to submit, it throws a 403: CSRF verification failed error. I'm not sure why this is happening - I feel like I'm doing everything right. Could it have something to do with saved cookies that override the CSRF token getting changed every time render is called? Here's my code: class Intake(View): form_class = IntakeFormSimple template_name = "intake.html" def get(self, req: HttpRequest): form = self.form_class(None) return render(req, self.template_name, {"form": form}) def post(self, req: HttpRequest): form = self.form_class(req.POST) if form.is_valid(): return HttpResponse("submitted form!") return render(req, self.template_name, {"form": form}) and the form template (boilerplate removed for clarity): <body> <section class="section"> <div class="container"> <form action="" method="post" novalidate> {% csrf_token %} {{ form.non_field_errors }} {% for field in form %} <div class="field"> <label class="label" for="{{field.id_for_label}}" >{{field.label}}</label > <div class="control">{{field}}</div> {% if field.help_text %} <p class="help">{{field.help_text}}</p> {% endif %} <ul class="errorlist"> {% … -
Why we write this, form = StudentForm(request.POST) in django?
This is my views function, def studentcreate(request): reg = StudentForm() string = "Give Information" if request.method == "POST": reg = StudentForm(request.POST) string = "Not Currect Information" if reg.is_valid(): reg.save() return render('http://localhost:8000/accounts/login/') context = { 'form':reg, 'string': string, } return render(request, 'student.html', context) Here first we store form in reg variable then also we write reg = StudentForm(request.POST) why? acutally why we write this? -
AWS elastic beanstalk Linux 2 with Django application failed to deploy
I am in this strange situation where I could not deploy the same code base to elastic beanstalk Linux 2 server after first time. The first deployment(after intentionally crashed server or new environment) works with no error but if I deploy the same code base again, It would fail at python manage.py migrate command in my .config file. I tried to put all my eb container commands in .config into .platform/hooks as .sh scripts, the deployment works, but I would get 502 Bad Gateway error and unable to see my site. Any insight? -
Read a uploaded excel file that have equations and images in cells django and store it in db
Read a uploaded excel file that have equations and images in cells using django and store it in db -
Getting Module not found error on terminal
I am building a react-django app for which I have created a css folder to add external css to my components and a image folder which has all the images which are required in the components but when I run the app I get this error on my terminal which shows module not found: ERROR in ./src/components/HomePage.js 5:0-39 Module not found: Error: Can't resolve './images/insta.png' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components' resolve './images/insta.png' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components' using description file: C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\package.json (relative path: ./src/components) Field 'browser' doesn't contain a valid alias configuration using description file: C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\package.json (relative path: ./src/components/images/insta.png) no extension Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png doesn't exist .js Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png.js doesn't exist .json Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png.json doesn't exist .wasm Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png.wasm doesn't exist as directory C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png doesn't exist @ ./src/components/App.js 3:0-34 10:90-98 @ ./src/index.js 1:0-35 ERROR in ./src/components/css/Homepage.css (./node_modules/css-loader/dist/cjs.js!./src/components/css/Homepage.css) 5:36-149 Module not found: Error: Can't resolve '"C:UsersKuldeep PÞsktopRAMANGymWebsite☼rontendsrc♀omponentspublicSergi2.jpeg"' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\css' resolve '"C:UsersKuldeep PÞsktopRAMANGymWebsite☼rontendsrc♀omponentspublicSergi2.jpeg"' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\css' Parsed request is a module using description file: C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\package.json (relative path: ./src/components/css) using description … -
Attempted relative import beyond top-level package in django
Trying to build a Django app with a signup app within the main app itself I receive this error message: from ..signup import views as signup_views ValueError: attempted relative import beyond top-level package This is the structure of my app ---PeerProgrammingPlatform ------peerprogrammingplat --------->peerprogrammingplat --------->signup This is my views (in signup): from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm # Create your views here. def signup(request): if request.method == 'POST': form = UserCreationForm() if form.is_valid(): form.save() username = form.cleaned.data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'signup/register.html', {'form':form}) my urls.py (peerprogrammingplat): from django.contrib import admin from django.urls import path from ..signup import views as signup_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', signup_views.register, name="register"), ] -
React app won't connect to django-rest database
I'm to update the frontend of this site https://github.com/ildebr/store-repository it has a react frontend and a django backend, auth is made with django-rest-framework. Originally the database was using PostrgreSql but due to some trouble with my pc I changed it to sqlite. When I try to register I'm unable to do it, I get error 200. I don't know what could be causing trouble cause it should not be having trouble functioining. When trying to register I get Internal server error: /auth/users I already have cors implemented and set like: CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ]