Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add a "snooze" button in Django with Ajax?
In my Django app I want to have a snooze button, which I want to use in order to postpone a deadline for an object. The corresponding model has a datefield called alarm and I want to pass the snooze command together with a number x of days that should be added to the current setting. So far I found out that I cannot do this directly from the template and multiple sites suggested the use of Ajax. I have never used that. My files look like this. views.py def Operation_Snooze_Method(request): print(request) if request.POST: if request.is_ajax(): print("Ajax") # I guess here I would handle the alarm if I could bring the Ajax call to work at all. else: print("no ajax") print(request.POST) return render(request, templ_folder_name + landingpage) part of my models.py class Operation(models.Model): title = models.CharField(max_length=255, blank=False, null=False, verbose_name="Title of the operation") alarm = models.DateField(verbose_name="Date of the alarm", null=True, blank=True) [...] def Operation_Snooze(self,x): self.alarm = datetime.now() + timedelta(days=x) urls.py path('snooze/', views.Vorgang_Snooze_Method, name="snooze"), my base.html, which is the template that I extend with my other templates $document.ready(function(){ $("#snooze").submit(function(event){ event.preventDefault(); $ajax({ type:"POST", url:"{% url 'app_name_myproject:snooze' %}", data:{ 'id':$('#snooze').val() 'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val() }, }); return false; };) }); </script> [...] {% if urgent_operations %} # this … -
why does my django project keep showing no assignment even after upload them?
I' unable to show the error as there is no traceback, there seems to be a problem in my code that I am unable to sort. My project is assignment submissions platform, and in the student submission page it shows that there are no assignments even though I ahve created alot of them. I'm pasting my code below, please do have a look and any sort of help would be really appreciated. Views.py # for Teacher to create assignment. @login_required def upload_assignment(request): assignment_uploaded = False teacher = request.user.Teacher students = Student.objects.filter(user_student_name__teacher=request.user.Teacher) if request.method == 'POST': form = AssignmentForm(request.POST, request.FILES) if form.is_valid(): upload = form.save(commit=False) upload.teacher = teacher students = Student.objects.filter(user_student_name__teacher=request.user.Teacher) upload.save() upload.student.add(*students) assignment_uploaded = True else: form = AssignmentForm() return render(request,'upload_assignment.html',{'form':form,'assignment_uploaded':assignment_uploaded}) # for students to view all the assingments @login_required def class_assignment(request): student = request.user.Student assignment = SubmitAssignment.objects.filter(student=student) assignments_list = [x.submitted_assignment for x in assignment] return render(request,'class_assignment.html',{'student':student,'assignment_list':assignment_list}) Models.py class logger(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Student') name=models.CharField(max_length=250) roll_no = models.CharField(max_length=50) email = models.EmailField(max_length=254) def __str__(self): return self.name class Meta: ordering = ['roll_no'] class Teacher(models.Model): username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Teacher') name = models.CharField(max_length=250) subject_name = models.CharField(max_length=250) email = models.EmailField(max_length=254) students = models.ManyToManyField(Student, related_name="teachers", through="StudentsInClass") def __str__(self): return self.name … -
Drf throttling restart when POST
I created some app and want to set up different throttling for GET/POST,PUT,PATCH. When I make a GET request, it works fine. But when I perfom POST/PUT/PATCH it looks like cache is restarted. I want to create also extra headers so that's why I think this is actually the problem. Throttling.py class SetHeaders: def throttle_success(self): self.history.insert(0, self.now) self.cache.set(self.key, self.history, self.duration) print(self.key, self.history, self.duration) print(f"REMAIN TIME {self.duration - (self.now - self.history[-1])}") print(f'LIMIT {self.get_rate()}') print(f'REMAIN RATE {self.num_requests - len(self.history) + 1}') return True class UserPostRateThrottle(SetHeaders, throttling.UserRateThrottle): scope = "user_post" def allow_request(self, request, view): if request.method == "GET": return True return super().allow_request(request, view) class UserGetRateThrottle(SetHeaders, throttling.UserRateThrottle): scope = "user_get" def allow_request(self, request, view): if request.method in ("POST", "PUT", "PATCH"): return True return super().allow_request(request, view) views.py class TruckViewSet(viewsets.ModelViewSet): queryset = Truck.confirmed.all() serializer_class = TruckSerializer filterset_class = TruckFilter permission_classes = ( permissions.DjangoModelPermissions, IsOwnerOrReadOnly, ) throttle_classes = (UserGetRateThrottle, UserPostRateThrottle) def _get_images(self, request): for img in request.data.getlist("image"): image_serializer = TruckImageSerializer(data={"image": img}) image_serializer.is_valid(raise_exception=True) def create(self, request, *args, **kwargs): if request.data.get("image"): self._get_images(request) return super(TruckViewSet, self).create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(owner=self.request.user) def update(self, request, *args, **kwargs): if request.data.get("image"): self._get_images(request) return super(TruckViewSet, self).update(request, *args, **kwargs) serializers.py class TruckSerializer(serializers.ModelSerializer): location = LocationSerializer( read_only=True, ) owner = serializers.PrimaryKeyRelatedField( read_only=True, ) name = … -
Hot re return a costume error mesage in graphene?
I created the following class to update the post in spesfic conditions but if the contitions ==False the I need to return {"message": "Only the owner of the post and the admin(website's wonr) can edit and delet this post"} But the JsonResponse don't work likt it is with RestFramework! class UpdatePost(graphene.Mutation): # owner(added_by)+admin can update and delete class Arguments: id = graphene.Int(required=True) description = graphene.String() post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, id, description): post = models.Post.objects.get(id=id) if (info.context.user == post.added_by): post.description = description post.save() return CreatePost(post=post) else: JsoneResponse({"message": "Only the owner of the post and the admin(website's wonr) can edit and delet this post"}) -
Reverse for '' not found. '' is not a valid view function or pattern name - django fix
When trying to create the get_absolute_url. Am geting this error, am not sure why since i searched and i saw many tutorials but couldnt figure out why. -
Chaining multiple filter() in Django returning nothing
I was trying to filter two conditions but it's not returning anything That's the function that has the condition i'm using def airport_view(request, code): airport = Airport.objects.get(code=code) flights = Flight.objects.filter(origin=airport).filter(destination=airport) context = { 'airport':airport, 'flights':flights } return render(request, "flights/airport.html", context) The airport works normally but the multiple filter chain doesn't work, even that i got three flights which has one of both conditions That's the related models if it helps you class Airport(models.Model): code = models.CharField(max_length=64) name = models.CharField(max_length=64) class Flight(models.Model): origin = models.ForeignKey('Airport', on_delete=models.CASCADE, related_name="From") destination = models.ForeignKey('Airport', on_delete=models.CASCADE,related_name="To") passengers = models.ManyToManyField('Person', blank=True) -
Get Bounding Box from Django PolygonField
I am trying to get the bounding box for a PolygonField in a Django model. I read here that you can use extent but when running the below as per the extent documentation: qs = newJob.objects.filter(pk=1).aggregate(Extent('loc')) print(qs['loc__extent']) I get the error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: function st_extent(geography) does not exist LINE 1: SELECT ST_Extent("app_newjob"."loc") AS "loc__ext... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. My model (simplified) looks like this: class newJob(models.Model): name = models.CharField(max_length=64) desc = models.CharField(max_length=64) loc = models.PolygonField() And in my test: from django.contrib.gis.db.models import Extent newJob.objects.create( name="test", desc="test", loc="SRID=4326;POLYGON ((0.9063720703125029 52.32023207609735, 0.8239746093749998 52.10819209746323, 1.170043945312496 52.14191683166823, 1.170043945312496 52.31351619974807, 0.9063720703125029 52.32023207609735))" ) qs = newJob.objects.filter(pk=1).aggregate(Extent('job_loc')) I'm running a PostGIS database on the back. Any ideas what I'm doing wrong? -
Django create field in ModelForm if condition is True
I am going to have a Product, which can have some variations, and also Product, which has no variants. So for the first case, there should be fields 'quantity' and 'variant' select box rendered. For the second case, only a field with 'quantity' should be rendered because the product has no variants. Is possible to do that somehow with ModelForms? This is my form, where now quantity and variant is mandatory to fill: class AddToCartForm(forms.ModelForm): variant = forms.ModelChoiceField( queryset=ProductVariant.objects.none(), ) quantity = forms.IntegerField(min_value=1, initial=1) class Meta: model = OrderItem fields = ['quantity', 'variant'] def __init__(self, *args, **kwargs): self.product_id = kwargs.pop('product_id') product = Product.objects.get(id=self.product_id) super().__init__(*args, **kwargs) self.fields['variant'].queryset = product.variant.all() def clean(self): product_id = self.product_id product = Product.objects.get(id=self.product_id) quantity = self.cleaned_data['quantity'] if product.stock < quantity: raise forms.ValidationError( f'The maximum stock available is {product.stock}') Thanks for any help! -
Django Choices field to add to cart function
I have an app with a choices field for prices. Two of the categories have a Choices field. I tried to get the desired size of the customer by using the request.POST.get script on the views.py to get the value of the price, but it's not showing up. Views.py @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, customer=request.user, ordered=False, price = request.POST.get('inlineRadioOptions') ) order_qs = Order.objects.filter(customer=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.price = request.POST.get('inlineRadioOptions') order_item.price order_item.item_quantity += 1 order_item.save() messages.success(request, "This item was updated to your cart." ) else: messages.success(request, "This item was added to your cart." ) order.items.add(order_item) order.save() else: order = Order.objects.create( customer=request.user) order.items.add(order_item) order.save() messages.success(request, "This item was added to your cart." ) return redirect("featured-food", slug=slug) On Views.py, I added price as a parameter and use the script request.POST.get('inlineRadioOptions') to get the value of the selected radio button, but it does not work. Models.py class Item(models.Model): name = models.CharField(max_length=50) categories = models.CharField(choices=CATEGORY_CHOICES, max_length=50) sizes = models.CharField(choices=SIZES_CHOICES, max_length=50, null=True, blank=True) cake_size = models.CharField(choices=CAKE_CHOICES, max_length=50, null=True, blank=True) img = models.ImageField(upload_to=get_upload_path, null=True, blank=True) description = models.TextField() beverage_s_price = models.FloatField(null=True, blank=True) beverage_t_price = models.FloatField(null=True, blank=True) beverage_g_price = models.FloatField(null=True, blank=True) beverage_v_price = models.FloatField(null=True, blank=True) … -
Django - make signal wait for file to be ready
Im experiencing a wired issue using Django signals. Each time a user saves a new avatar onto his profile also a thumbnail version of the picture gets saved beside the high quality version. This is working fine until the image should get changed or delted, here I have written two signals to handle both fileds, the avatar and the avatar_tn field. For some reason my signals are working sometimes and sometimes not, especially they have problems if the underlining filesystem is remote, like NFS, CIFS or iSCSI. It seems that the signal always expects that the file is ready and already written, which is obviously not the case due to network and I/O-Delay ... signals.py # Runs on avatar deletion @receiver(models.signals.post_delete, sender=User) def avatar_auto_delete_files(sender, instance, **kwargs): if instance.avatar: if os.path.isfile(instance.avatar.path): os.remove(instance.avatar.path) if instance.avatar_tn: if os.path.isfile(instance.avatar_tn.path): os.remove(instance.avatar_tn.path) # Runs on avatar change @receiver(models.signals.pre_save, sender=User) def avatar_auto_delete_files_on_change(sender, instance, **kwargs): if not instance.pk: return None try: old_avatar = sender.objects.get(pk=instance.pk).avatar old_avatar_tn = sender.objects.get(pk=instance.pk).avatar_tn except sender.DoesNotExist: return None if not old_avatar: return None new_avatar = instance.avatar new_avatar_tn = instance.avatar_tn if not old_avatar == new_avatar: if os.path.isfile(old_avatar.path): os.remove(old_avatar.path) if old_avatar_tn == new_avatar_tn: if os.path.isfile(old_avatar_tn.path): os.remove(old_avatar_tn.path) Is there any way I can make the signal wait for … -
How pass parameter in this method?
Hello I'm newbie Python user. I study now django queryset. but query.pyi in _BaseQuerySet's method def values(self, *fields: Union[str, Combinable], **expressions: Any) -> ValuesQuerySet[_T, Dict[str, Any]]: ... I want to pass a parameter to that function, but the first code runs, but the second code does not. error code not error code Full code Run with response error What should I do to get it running normally? -
how to save converted json data into database column in django
so basically, i request to develop a upload function allow the user upload a dataset, in the same time, the backend will convert the dataset into json format and save to database column. For example, the database design be like ['id', 'name', 'file', 'json_format']. However i can't do that while upload the file it will show error for it. this is my models.py: class Document(models.Model): name = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='') uploaded_at = models.DateTimeField(auto_now_add=True) json_format = models.JSONField() This is my forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('name', 'document') This is my view.py: def home(request): file_data = Document.objects.all() error_message = False #Upload CSV FILE if request.method == 'POST': form = DocumentForm(request.POST,request.FILES) if form.is_valid(): if form.data['name']: # Check existing data if Document.objects.all().filter(name=form.cleaned_data.get("name")).exists(): form = DocumentForm() error_message = True return render(request,'home.html', {'form':form, 'file_data': file_data,'error_message':error_message}) else: #form.save() get_name = form.name get_file = Document.objects.get(name=get_name) read_file = p.read_csv(get_file) #read file convert_to_json = read_file.to_json #convert the dataset to json form.save(update_fields=['json_format']) #update the json to column return redirect('/') else: form = DocumentForm() return render(request,'home.html', {'form':form, 'file_data': file_data}) -
Should graphene classes be repetitive like this?
I have the following mutation classes to for CRUDing a model. However, I have another model that I need to do the exact same classes on it. Should I create the exact same classes again with other names like class CreateComment, class UpdateComment and class DeleteComment or there is a way to make reusable classes with graphene? class CreatePost(graphene.Mutation): class Arguments: description = graphene.String(required=True) post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, description): post = models.Post(description=description,added_by=info.context.user) post.save() return CreatePost(post=post) class UpdatePost(graphene.Mutation): # owner(added_by)+admin can update and delete class Arguments: id = graphene.Int(required=True) description = graphene.String() post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, id, description): post = models.Post.objects.get(id=id) if (info.context.user == post.added_by): post.description = description post.save() return CreatePost(post=post) else: "Only the owner of the post and the admin(website's wonr) can edit and delet this post" class DeletePost(graphene.Mutation): # owner(added_by)+admin can update and delete class Arguments: id = graphene.Int(required=True) post = graphene.Field(schema.Posts) @classmethod def mutate(cls, root, info, id): post = models.Post.objects.get(id=id) if (info.context.user == post.added_by): post.delete() return f"{'ID':ID}" else: return {'partial': True} -
Filter only normal users not staff or superusers in Django
I want get only normal users not staff or superusers, how can i add option to this code users = User.objects.filter() thanks for helping me -
Puzzled with datetime.datetime axis data on chartjs with Django app in views.py
I'm currently using MQTT to transfer temperature data from an ESP32 using a broker to a Django app. I have a view retrieving data from a Table with id,date,message,topic. I can create the chartjs line graph with the ('id') as x axis but the datetime.datetime('createdat) row doesn't work. **models.py** class Mqtt(models.Model): createdat = models.DateTimeField(db_column='createdAt') topic = models.CharField(max_length=255) message = models.CharField(max_length=255, blank=True, null=True) qos = models.IntegerField() class Meta: managed = False db_table = 'mqtt' **views.py** def chart_red(request): labels = [] data = [] chart_red_obj = Mqtt.objects.order_by('createdat')[:2] for mqtt in chart_red_obj: labels.append(mqtt.createdat) data.append(mqtt.message) return render(request, "chart_red.html", { 'labels':labels, 'data':data, }) }) **html and js** <canvas id="myChart"></canvas> <script> var temp = { type: 'line', data: { datasets: [{ data: {{ data|safe }}, label: 'Trend' }], labels:{{ labels|safe }}, }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('myChart').getContext('2d'); window.myLine = new Chart(ctx, temp); }; ** the output is as below with no Chartjs chart created. before coming here I've tried momentjs, datetime.parse and datetime.strptime python solutions but my skills are lacking and have not unlocked the answer as yet. ** </script> var config = { type: 'line', data: { datasets: [{ data: ['65.3', '65.3'], label: 'Trend' }], **labels:[datetime.datetime(2021, … -
Ajax is not saving data in DataBase
I am building a BlogApp and I am stuck on a Problem. What i am trying to do I am trying to access user's location via JavaScriptand saving in the Model's instance in DataBase. Accessing location is working fine. BUT saving is not working The Problem Location's city is not saving in DataBase. When i refresh the page then it doesn't save in DataBase. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') city = models.CharField(max_length=30,default='') views.py def func(request): city = request.GET.get('city') city.save() message = 'Updated' return HttpResponse(message) template (.html) # Getting city name ( first javascript code ) through IP is working. <script> $.ajax({ url: "https://geolocation-db.com/jsonp", jsonpCallback: "callback", dataType: "jsonp", success: function(location) { $('#city').html(location.city); } }); </script> #This code is for send data to Django. <script> $("city").change(function)(){ const city = 'city'; $.ajax({ url ="{% url 'mains:func' %}", data = { 'city':city, } , success.function(data){ console.log("Update"); } }); }; </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div>City: <span id="city"></span></div> I don't know where is the Problem. Any help would be Appreciated. Thank You in Advance. -
get values from checkboxes in django
I have several checkboxes from bootstrap and I need to get their vaules in my django app. I've tried to read them by using request.GET.get_list but all it does is returning an empy list. POST doesn't work either. Any suggestions? persl.html: {% for l in pl %} <tr> <td><div class="form-check"> <input class="form-check-input" type="checkbox" name="checks" value="value" id="fs"> <label class="form-check-label" for="checks"> </label> </div> </div> </td> <td><a href="pupdate/{{l.pk}}"><i class="bi bi-pencil-square"></i></a></td> <td><a href="pdelete/{{l.pk}}"><i class="bi bi-trash"></i></a></td> <td>{{l.pk}}</td> <td><a href="detail/{{l.padress.pk}}">{{l.fname}}</a></td> <td>{{l.lname}}</td> <td>{{l.mobil}}</td> <td>{{l.mail}}</td> <td>{{l.padress}}</td> </tr> {% endfor %} views.py: class PDelete(DeleteView): template_name='kammem/delete.html' model=Person success_url=reverse_lazy('personer') def get_queryset(self): if self.request.method == 'GET': v=self.request.GET.getlist('checks') return v -
Unable to get user.id from into django form
I'm unable to get user.school.id into the form shown below. I have not been able to know the reason as to why this is happening. Below is my forms.py class StudentsForm(forms.ModelForm): class Meta: model = StudentsModel fields = ("school","adm","name","kcpe","form","stream","gender","notes") widgets = { 'school':forms.TextInput(attrs={"class":'form-control','value':'','id':'identifier','type':'hidden'}), "adm":forms.TextInput(attrs={"class":'form-control'}), "name":forms.TextInput(attrs={"class":'form-control'}), "form":forms.Select(choices=class_forms,attrs={"class":'form-control'}), "stream":forms.Select(choices=streams,attrs={"class":'form-control'}), "gender":forms.Select(choices=gender, attrs={"class":'form-control'}), } Below is the script from the template where the id is to reflect. <script> document.getElementById('identifier').value = '{{ user.school.id }}'; </script> And this is the Students model class StudentsModel(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) adm = models.CharField(max_length=200) name = models.CharField(max_length=200) form = models.ForeignKey(FormModel, on_delete=models.CASCADE) stream = models.ForeignKey(StreamModel,on_delete=models.CASCADE) gender = models.ForeignKey(GenderModel,on_delete=models.CASCADE) def __str__(self): return "%s | %s" % (self.name,self.adm) Please help me out. If there's anything else I need to add let me know. class School(models.Model): name = models.CharField(max_length=100,default='default') def __str__(self): return str(self.name) class User(AbstractUser): school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True,default=1) #role = models.CharField(max_length=10, choices=ROLES, blank=False, null=False) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) def __str__(self): return (str(self.school) + ' | ' + self.username) The view class AddStudentView(LoginRequiredMixin,CreateView): model = StudentsModel form_class = StudentsForm template_name = 'students.html' success_url = reverse_lazy('students') def get_context_data(self, *args, **kwargs): streams = StreamModel.objects.filter(school=self.request.user.school) students = StudentsModel.objects.filter(school=self.request.user.school) forms = FormModel.objects.filter(school=self.request.user.school) context = super(AddStudentView,self).get_context_data(*args, **kwargs) context["streams"] = streams context["students"] = … -
Same Question for all users at a particular time
I want to create a quiz website with Django where all users get the same question at a particular time and after the timer ends all users get the next question. As I am new to this I just wanted to know is this possible, and if yes what do I search for on the internet -
Table doesn't exist, when in reality it does
So, I have created a database called build1, the name of the project is building_access. I have created tabled in the database(build1) called product +----------------------------+ | Tables_in_build1 | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | building_access_contact | | contact | | django_admin_log | | django_content_type | | django_migrations | | django_session | | order | | product | | review | +----------------------------+ 15 rows in set (0.00 sec) I did python manage.py makemigrations I did python manage.py migrate sessions I did python migrate --run-syncdb, which said that table building_access_contact already exists, which I know, which is suppose to synchronize not create a new one. Anyways, when i go to main page it says this (1146, "Table 'build1.building_access_product' doesn't exist") So my reaction would be to go to admin and make a product. And so I did, but it gave me the same error. So i went over to database to check if IT DOESN'T EXISTS, and as you can see from show tables;. It does exists.. So, any ideas? -
fixtures Pytest in django module scope vs function scope
class TestShowOrderApi: @pytest.fixture(scope="module") def order(self, django_db_setup, django_db_blocker): with django_db_blocker.unblock(): return Order.objects.create() @pytest.fixture() def setup(self, order): self.url = "%s://%s/v1/management/order/%s" % (PROTOCOL, settings.API_HOST, order.number) self.headers = {'X-API-KEY': 'secret'} return self @pytest.mark.django_db(transaction=False) def test_it_should_return_200_when_merchant_show_his_order_via_api_v1(self, setup, order): order_json = OrderSchema().dump(order) response = requests.get(self.url, headers=self.headers) assert order_json == response.json()["payload"]['order'] this test is pass once the order fixture scope is module , when i change it to function scope the response return 404 of non finding the order object why is that ? -
OSError at /account/reset_password/ and also OSError at /student/register/ [Errno 99] Cannot assign requested address
The problem The error occurs when a user resets a password or when the user registers an account. The user gets the error during registration after setting email.send(fail_silently=False) This error occurs only in production environment, the project is working well in development environment Password Reset Error details myapp/urls.py from django.urls import path from django.contrib.auth import views as auth_views urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view( template_name="accounts/password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name="accounts/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name="accounts/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name="accounts/password_reset_done.html"), name="password_reset_complete"), ] settings.py ... other settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my email address' EMAIL_HOST_PASSWORD = 'my email password' -
My React app is repeating the same error when using socket.io
I'm putting together a React web-app that uses Django for the backend server, coded in Python. At the moment, I'm attempting to change the data on a page when a new user joins. This is everything I have on the frontend to get this working: import io from 'socket.io-client'; let socket = io('http://127.0.0.1:8000'); class Room extends Component { constructor(props) { super(props); this.state = { chat: [{message:'Hello everyone'}] }; } componentDidMount() { socket.on('receive', data => { console.log(data); this.setState({chat:[...this.state.chat,data]}); }) } msgthreads = () => { return this.state.chat.map((msg, index)=>{ return <div key={index}> <p>{msg.message}</p> </div> }); } sendmessage =()=> { console.log(this.textInput.value); socket.emit('send',{message:this.textInput.value}); } some irrelevant code... render(){ return ( <div> {this.msgthreads()} </div> <div> <input type="text" className="form-control" ref={(input) => { this.textInput = input; }}/> <button onClick={this.sendmessage}>testbutton</button> </div> } export default Room; But this is the error that I'm getting: GET http://127.0.0.1:8000/socket.io/?EIO=4&transport=polling&t=NWlvd71 404 (Not Found) The error just keeps happening every few seconds, even when I'm doing anything. Is there something I have to do on the backend to get this working or is this a problem with the code above? -
Bootstrap 'row's not working but 'col's do
As the title says, I am pretty sure I set up bootstrap correctly and everything but running this page it shows me all the correct divs and and sized columns, however all the 'row' tags are ignored. they are just thrown all over the place. Shouldnt they be stacked one ontop of the other? I really dont want to hard code positions, i want this to be responsive. I have some CSS attatched to this but its the bootstrap giving me issues. <body> {% block body %} <div class='row banner'></div> <div class='row header'> <div class='col-4 image'></div> <div class='col-8 bio'></div> </div> <div class='row profile'> <div class='col-3' style='justify-content: center; align-items:flex-start;'></div> Followers <div class='followers'></div> <div class='col-6'></div> <div class='feed'></div> <div class='col-3' style='justify-content: center; align-items:flex-start;'> Following <div class='following'></div> </div> {% endblock %} </body> -
send Data from react to django rest api
after a lot of searching i keep finding how to send Data from react to django api using classes not functions so how would i convert this for exmaple to a functional component (this is not my code, just an example) export default class CreateRoomPage extends Component { constructor(props) { super(props); this.state = { guestCanPause: this.props.guestCanPause, votesToSkip: this.props.votesToSkip, errorMsg: "", successMsg: "", }; this.handleRoomButtonPressed = this.handleRoomButtonPressed.bind(this); this.handleVotesChange = this.handleVotesChange.bind(this); } handleGuestCanPauseChange(e) { this.setState({ guestCanPause: e.target.value === "true" ? true : false, }); } handleRoomButtonPressed() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ votes_to_skip: this.state.votesToSkip, guest_can_pause: this.state.guestCanPause, }), }; fetch("/api/create-room", requestOptions) .then((response) => response.json()) .then((data) => this.props.history.push("/room/" + data.code)); } renderCreateButtons() { return ( <Grid container spacing={1}> <Grid item xs={12} align="center"> <Button color="primary" variant="contained" onClick={this.handleRoomButtonPressed} > Create A Room </Button> </Grid> </Grid> ); } }