Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I make one user can give only one rating to an item?
How can I make one user can give only one rating to an item? I read about UniqueConstraint but I can't understand how to use it here. models.py #... User = get_user_model() class Item(models.Model): id = models.PositiveIntegerField( primary_key=True, validators=[MinValueValidator(1)]) is_published = models.BooleanField(default=True) name = models.CharField(max_length=150) text = models.TextField(validators=[validate_correct]) tags = models.ManyToManyField('Tag', blank=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name #... class Rating(models.Model): id = models.PositiveIntegerField( primary_key=True, validators=[MinValueValidator(1)]) EMOTION_TYPES = ( (1, 'Hatred'), (2, 'Dislike'), (3, 'Neutral'), (4, 'Adoration'), (5, 'Love'), ) star = models.IntegerField(null=True, choices=EMOTION_TYPES) -
Django app with Heroku with a virtual display
I have an app that uses Python Turtle to draw images. I use tkinter to create a window and PIL to do an ImageGrab to save a PNG. How do I run this on Heroku where I cannot directly access the server and specify a virtual display? I can make this work with Xvfb on my own server, but I don't know how to use Xvfb with Heroku. Everything I can find online about this is from 2015, so I highly doubt the solutions presented there are still relevant. -
Send information with the post method in the rest framework
I want to add a new comment with the post method, but it gives an error {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got ModelBase.', code='invalid')]} Serializers : from rest_framework import serializers from .models import Products,ProductsComments class ProdcutsSerializers(serializers.ModelSerializer): colors = serializers.SlugRelatedField(many=True,read_only=True,slug_field='name') category = serializers.SlugRelatedField(many=True,read_only=True,slug_field='name') sizes = serializers.SlugRelatedField(many=True,read_only=True,slug_field='name') class Meta: model = Products fields = '__all__' class ProductsCommentsSerializers(serializers.ModelSerializer): user = serializers.SlugRelatedField(many=True,read_only=True,slug_field='id') product = serializers.SlugRelatedField(many=True,read_only=True,slug_field='id') class Meta: model = ProductsComments fields = '__all__' Views : from rest_framework.decorators import api_view,permission_classes from rest_framework.response import Response from rest_framework import status from .serializers import * from .models import * @api_view(['GET']) def products_list(request): products = Products.objects.all() data = ProdcutsSerializers(products,many=True).data return Response(data) @api_view(['GET']) def products_comments_list(request): products_comments = ProductsComments.objects.all() data = ProductsCommentsSerializers(products_comments,many=True).data return Response(data) @api_view(['POST']) def products_comments_add(request): data = ProductsCommentsSerializers(data=ProductsComments) if data.is_valid(): print('Ok') else: print('not') #print(data) print(data.errors) return Response({"M": "not"}) -
Django Trying to render the data that i added to a DetailView via get_context_data()
I'm making a simple real estate app where users can create Estates. The Estate model has one main image, but the user can upload multyple images using another model and form for that. On the estate details page which is a DetailView I want to display the images and info about the user who is the owner of the current Estate. I'm passing the above info using get_context_data(). While debugging everything seems fine to me the context contains the info about the user and the images but this information is not rendered. Can you please help me with this issue? my user model is linked to the current estate with the following: class Estate(models.Model): user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) This is the EstateImagesModel class EstateImages(models.Model): IMAGE_UPLOAD_TO_DIR = 'estates/' estate = models.ForeignKey( Estate, related_name='images', on_delete=models.CASCADE, ) image = models.FileField( upload_to=IMAGE_UPLOAD_TO_DIR, ) and the detail view is class EstateDetailsView(views.DetailView): model = Estate template_name = 'main/estates/estate_details.html' context_object_name = 'estate' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['is_owner'] = self.object.user == self.request.user estate_images = list(EstateImages.objects.filter(estate_id=self.object.id)) seller = Profile.objects.filter(user_id=self.object.user_id) context.update({ 'estate_images': estate_images, 'seller': seller, }) return context -
How to make a value unique for 2 fields in Django model?
I need all values in 2 fields to be unique for both of them. I have username and email in my custom User model. I want to prevent this: user1 - username = some_username, email = MY@EMAIL.COM user2 - username = MY@EMAIL.COM, email = some_email I don't want to constrain '@' or '.' so what can I do? -
Django CKEditor Code Snippet not rendered correctly
I am building a Django blog that supports code snippets for both post and comments. The following is my CKEditor config in settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'extraPlugins': ','.join( [ 'codesnippet', 'widget', 'dialog', ]), }, 'comment': { 'toolbar_Full': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['NumberedList','BulletedList'], ['Indent','Outdent'], ['Maximize'], ['CodeSnippet'] ], 'extraPlugins': ','.join( [ 'codesnippet', 'widget', 'dialog', ]), } } All instances of RichTextField in the models and forms are replaced with RichTextUploadingField. Then I ran the migrations. My text field has the code snippet button. Clicking the button allows the end users to post code snippets. But when the form is submitted the snippet is not marked down correctly. There are no markdown nor syntax highlighting. Am I missing something within the configs? Or does Django's form have limited support for code snippets? -
How to change boolean member into two checkbox for search
I have boolean member in Model. TYPE_SET_CHOICES = ( (True, 'OK'), (False, 'NG'), ) is_OK = models.BooleanField(choices=TYPE_SET_CHOICES,default=False) then I want to make search form for this model. My purpose is showing two checkboxs and enable user to check both ok row and ng row. is_OK_check = forms.TypedMultipleChoiceField( required=False, coerce=str, label='', choices=(('', 'OK'), ("","")), # What should be here? maybe something confused. widget=CheckboxSelectMultiple) How can I make this ?? -
Django(view) - Ajax Interaction?
I want to send django values to the server using ajax. parts.html <h1>{{parts.name}}</h1> <form class="form-group" method="POST" id="part_solution_form"> csrf_token %} <label for="part_solution">Write your solution here</label> <input id="part_solution" name="part_solution" type="text" class="form-control" required> </form> views.py def selected(request, part_id): parts = Part.objects.get(id=part_id) return render(request, "cram/parts.html", {"parts": parts}) def check_parts(request): if request.method == 'POST': part = request.POST['part'] solution = request.POST['solution'] parts.js $("#part_solution_form").on('submit', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/cramming/check_fib/', data: { part: $(_________), //{{ parts.id }} I want to send solution: $("#part_solution").val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val() }, success: function () { alert("SuccessFull") }, error: function () { alert("Error") } }) } ); I want to send value {{part.id}} from selected function through parts.html using ajax to check_parts. I don't know the value that I left empty in js to get value from HTML. Thanks in advance. Also, I want check_parts response (if it contains JsonResponse) in same ajax in success. -
Django administration Site. 'Delete multiple objects' produces ValidationError
When attempting to delete multiple rows, which have a one to one relationship with two other tables I received the following error: ['“March 21, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.'] The models are set up as such: class Media(models.Model): date = models.DateField(primary_key=True, unique=True) received_url = models.CharField(max_length=200, blank=True, null=True) class Api(models.Model): media = models.OneToOneField(Media, on_delete=models.CASCADE) request_url = models.CharField(max_length=200) class Text(models.Model): media = models.OneToOneField(Media, on_delete=models.CASCADE) title = models.CharField(max_length=100) copyright = models.CharField(max_length=200, blank=True, null=True) I am trying to delete the items in the Home › My_App_Main › Medias › Delete multiple objects from the Django administration site. Which presents me with the following: Are you sure? Are you sure you want to delete the selected medias? All of the following objects and their related items will be deleted: Summary Medias: 2 Apis: 2 Texts: 2 Objects Media: 2022-03-21 Api: 2022-03-21 Text: 2022-03-21 Media: 2022-03-20 Api: 2022-03-20 Text: 2022-03-20 I then click Yes, I'm Sure Which triggers then triggers the error. Checking the POST request in the network log for the browser I noted the dates appear to be in the wrong format: _selected_action […] 0 "March+21,+2022" 1 "March+20,+2022" action "delete_selected" post "yes" I tried in both … -
How to add/give access to user to a model object and how to show all object a particular user created in his homepage
I am doing an online classroom project like google classroom. So I created a model for teachers to add courses now if a teacher adds 2-3 or more courses how will I show all of his created courses on his homepage like rectangular cards we see on google classroom also how I add a student to that class I created a unique "classroom_id" field in course model how I will design that student can join that particular class by entering the classroom id. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) -
Querying other Model in class-based view produces error
I have two tables, in one of which the possible items with their properties are recorded, in the other the stock levels of these respective items are recorded. class itemtype(models.Model): item_id = models.IntegerField(primary_key=True) item_name = models.CharField(max_length=100) group_name = models.CharField(max_length=100) category_name = models.CharField(max_length=100) mass = models.FloatField() volume = models.FloatField() packaged_volume = models.FloatField(null=True) used_in_storage = models.BooleanField(default=False, null=True) class Meta: indexes = [ models.Index(fields=['item_id']) ] def __str__(self): return '{}, {}'.format(self.item_id, self.item_name) class material_storage(models.Model): storage_id = models.AutoField(primary_key=True) material = models.ForeignKey(itemtype, on_delete=models.PROTECT) amount_total = models.IntegerField(null=True) price_avg = models.FloatField(null=True) amount = models.IntegerField(null=True) price = models.FloatField(null=True) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return '{}, {} avg.: {} ISK'.format(self.material, self.amount, self.price) I have a ModelForm based on the table material_storage, in which a checkbox indicates whether transport costs should be included or not. In the form_valid() method of this ModelForm class the calculations are performed. To do so, I have to retrieve the volume per unit of the given item to use it for my transport cost calculations. Trying to geht that value the way shown below leads to an error I don't really understand. class MaterialChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.item_name class NewAssetForm(forms.ModelForm): material = MaterialChoiceField(models.itemtype.objects.filter(used_in_storage= True)) needs_transport = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(NewAssetForm, self).__init__(*args, **kwargs) self.fields['amount'].widget.attrs['min'] … -
Django testing - group object not working when using factory_boy
I'm trying to streamline my testing by using factory_boy. I would like to test views that depend on some group permissions. If I write my test by creating a user and group in setUpTestData, I can get the test to work. However, if I create the user and group using factory_boy, it doesn't look like the permissions are set in the test. view @method_decorator([login_required, teacher_required], name='dispatch') class GradeBookSetupCreateView(PermissionRequiredMixin, UpdateView): raise_exceptions = True permission_required = 'gradebook.change_gradebooksetup' permission_denied_message = "You don't have access to this." form_class = GradeBookSetupForm model = GradeBookSetup success_url = "/gradebook/" def get_object(self, queryset=None): try: obj = GradeBookSetup.objects.get(user=self.request.user) return obj except: pass The permission problem is from the PermissionRequiredMixin and permission_required. There is also a permission in the decorator but that is working fine. Here is a test that works: class GradeBookSetupTests(TestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user( username='teacher1', email='tester@email.com', password='tester123' ) cls.user.is_active = True cls.user.is_teacher = True cls.user.save() teacher_group, created = Group.objects.get_or_create(name='teacher') teacher_group = Group.objects.get(name='teacher') content_type = ContentType.objects.get( app_label='gradebook', model='gradebooksetup') # get all permssions for this model perms = Permission.objects.filter(content_type=content_type) for p in perms: teacher_group.permissions.add(p) cls.user.groups.add(teacher_group) cls.user.save() print(cls.user.groups.filter(name='teacher').exists()) my_g = cls.user.groups.all() for g in my_g: print(g) cls.gradeb = GradeBookSetupFactory(user=cls.user) def test_signup_template(self): self.client.login(username='teacher1', password='tester123') response = self.client.get(reverse('gradebook:gradebooksetup')) self.assertEqual(response.status_code, 200) … -
Retrieving data without refreshing the page with ajax in django
I can post with ajax, but when I want to pull data without refreshing the page, I can only do it 2 times, then the button loses its function. <div> <input type="hidden" name="producecode" class="pcode" value="{{per.produceCode}}" /> <input type="hidden" name="useremail" class="uponequantity" value="{{user.username}}" /> <button class="btn btn-sm btn-primary upoq"><i class="fa fa-plus"></i></button></div> and jquery $.ajax({ type: "POST", url: "/uponequantity/", headers: { "X-CSRFToken": '{{csrf_token}}' }, data: { "producecode":$(this).parent().find(".pcode").val(), "useremail":$(".uponequantity").val(), }, success: function() { window.location.assign('/basket/'+"?b="+$(".uponequantity").val()); } }); /*$.ajax({ url:'/baskett/'+"?b="+$(".uponequantity").val(), headers: { "X-CSRFToken": '{{csrf_token}}' }, type:'POST', success:function(result){ $('.basket').html(result); } }); */ }) -
Rebase git branch upon 2 pull requests
I have a Django project with 4 other members, and I'm creating a model, let's call it "model M". Model M is having 2 foreign keys, the first is model A and the other is model B. At this moment, model A and model B are both not approved and merged to the main branch on our GitHub repo, and both on different pull requests, and I need to rebase my current branch of creating model M upon those 2 pull requests of A and B. I know I can rebase my branch on 1 pull request, but is it possible to rebase it upon 2 different pull requests? If so, how can I do it without having them rebase on each other (because they don't really rely on each other)? Thanks! I've rebased my branch on the first pull request, model A. But when I've tried to rebase the current branch on model B as well, I got conflicted (because they don't have the same commit history). -
After an upload, why is the image field put as null and also get a multipart form error? Is there a way to wrap formData in post_create in auth.js?
I get MultiPartParser error on clicking submit : { "detail": "Multipart form parse error - Invalid boundary in multipart: None" }. The image field is also null. Can't change state of formData. Below is my code from views backend to PostData in frontend. I am using react and django. Here is my views.py code. class ManagePostingView(APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): request.data['user'] = request.user.id serializer = PostListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is my auth.js code for post request.` export const post_create = (title, content, image) => async (dispatch) => { if (localStorage.getItem("access")) { const config = { headers: { "Content-Type": "multipart/form-data", Authorization: `JWT ${localStorage.getItem("access")}`, }, }; const body = { title, content, image, }; try { const res = await axios.post( `${process.env.REACT_APP_API_URL}/api/list/PostView/`, body, config ); dispatch(load_user()); if (res.data != null) { dispatch({ type: POST_DATA_SUCCESS, payload: res.data, }); } else { dispatch({ type: POST_DATA_FAIL, }); } } catch (err) { dispatch({ type: POST_DATA_FAIL, }); } } }; Below is the PotData.js Here it submits data from the user to post_create so it could be sent to the backend. import React, { useState } from "react"; import { Redirect } from "react-router-dom"; import … -
Django - Performance checking permission in template
I have a template that is a header snippet that is used on every page of the platform. What I would like to know is what performance implications/issues checking permission with {% if perms.foo.add_bar %} can have on the platform. And if there is a better way to do this. I checked the load/request time of the page on Django Toolbar and didn't seem to change at all. Although I tested just at my local environment, not the production (don't have access). -
dango-filter zeigt alle Projekte an; es sollen aber nur die Projekte angezeigt werden, die der User angelegt hat
als Anfänger habe ich Probleme mit Django. Ich habe einen django_filter progrmmiert. In views.py: ''' class AufgabenView(LoginRequiredMixin, ListView): model = Aufgaben template_name = 'aufgaben/aufgaben.html' # object_list bekommt einen Namen context_object_name = 'aufgaben' #paginate_by = 2 filterset_class = AufgabenFilter # nur datensätze anzeigen, für die der User berechtigt ist. def get_queryset(self): queryset = super().get_queryset().filter(ersteller=self.request.user) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = AufgabenFilter(self.request.GET, queryset=self.get_queryset()) context['number_results'] = context['filter'].qs.count() return context ''' Leider werden alle Projekte angezeigt. Auch die, die andere User angelegt haben. aus models.py: ''' from django.db import models from django.contrib.auth.models import User from home.models import Projekt from datetime import datetime STATUS = ((0, "erledigt"), (1, "offen"), (2, "nachverfolgen"), (3, "ruht")) class Aufgaben(models.Model): datum = models.DateField(default=datetime.now) schlagwort = models.CharField(max_length=255, null=True, blank=True) aufgabe = models.CharField(max_length=255) anmerkung = models.TextField(null=True, blank=True) frist = models.DateField(null=True, blank=True) aufgabenstatus = models.IntegerField(choices=STATUS, default=1) erstellt_am = models.DateTimeField(auto_now_add=True) ersteller = models.ForeignKey(User, on_delete=models.CASCADE) projektbezug = models.ForeignKey(Projekt, on_delete=models.CASCADE) class Meta: ordering = ['projektbezug','datum'] def __str__(self): return str(self.aufgabe) + ' im Projekt: ' + str(self.projektbezug) ''' Wie kann ich die queryset filtern, so dass nur die Projekte des berechtigten Users zu sehen sind? Gruß Michael -
Can I create django-like auth app using FastAPI?
As I understand FastAPI is good for building APIs. However I was wondering, will I be able to create a Django-like web-app, say e-commerce app with accounts and cart, using FastAPI. I glanced at docs and couldn't find any kind of auth features, login/logout/signup, Forms validating that input etc. Is that available from the box or there are some libraries? Does it even make sense or it is better to use Django/flask? -
How to upload pdf file from React js to Django rest framework
I am trying to upload a file on the frontend in React to each user from React js, display them to the users in href and save into django rest framework. How can I do it? the code: export default function UserDetails() { const { id } = useParams(); const navigate = useNavigate(); const [addFile, setAddFile] = useState(null) const addUserFile = async () => { let fromField = new FormData() if (addFile !== null) { fromField.append('user_document', addFile) } await axios({ method: 'PUT', url: `http://localhost:8000/api/document/${id}/`, data: fromField }).then((response) => { console.log(response.data); navigate.push('/') }) } const [file, setFile] = useState([]) const getFile = async () => { const { data } = await axios.get(`http://localhost:8000/api/document/${id}/`) console.log(data) setFile(data) useEffect(() => { getFile(); }, []) return ( <div> <input type='file' multiple className='from-control from-control-lg' name='user_document' onChange={(e) => setAddFile(e.target.files[0])} /> <Button variant="contained" component="span" size="small" onClick={addUserFile} >Upload</Button> <a href={file.user_document}>cert-NSC-2022-South-p001-Advisor.pdf</a> </div> ) } } Thank you in advance. -
Django format change required in the session_data
My Django authentication code looks like below: @api_view(["POST"]) @authentication_classes((BasicAuthentication,)) @permission_classes((IsAuthenticated,)) def api_login(request): username = request.user.username request.session["username"] = username password = request.user.password request.session["password"] = password When I decode the session from the django_session table it gives the p output {"username":"john","password":"john123","member_id":1} But I need the decoded output as below: {'_auth_user_id': '1', '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend', '_auth_user_hash': 'baedbd0e1a2a7eb00d588384391f4aaa7fa0e14a12b6afe607f1xxxxxxxxx', '_session_expiry': 1209600} I use this API from the ReactJS front end. what changes should I do to the code to achieve the format change? -
CONTACT FORM SITE WITH DJANGO DONT SEND
I finished the form but there is a problem on sending it, when I throw an error. thank you for helping me TypeError at /envoyermail/ envoyermail() got an unexpected keyword argument 'fail_silently' Request Method: POST Request URL: http://127.0.0.1:8000/envoyermail/ Django Version: 4.0.3 Exception Type: TypeError Exception Value: envoyermail() got an unexpected keyword argument 'fail_silently' Exception Location: C:\Users\OUE\Desktop\pcibenin\App\views.py, line 47, in envoyermail from django.urls import reverse from django.shortcuts import render from django.core.mail import send_mail from django.views.generic import TemplateView from django.http import HttpResponse from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings def index(request): return render(request, "index.html") def qui_sommes_nous(request): return render(request, "qui_sommes_nous.html") def equipe(request): return render(request, "equipe.html") def galerie(request): return render(request, "galerie.html") def avendre(request): return render(request, "avendre.html") def alouer(request): return render(request, "alouer.html") def realisation(request): return render(request, "realisation.html") def contact(request): return render(request, "contact.html") def details_des_appartement(request): return render(request, "details_des_appartement.html") def envoyermail(request): if request.method=="POST": name = request.POST.get('name') subject = request.POST.get('subject') email = request.POST.get('email') message = request.POST.get('message') envoyermail( name, subject, email, message, 'ouesergegedeon225@mail.com', fail_silently = False,) message.info (request, 'Votre message a été envoyé') return render(request, 'contact.html') from django.contrib import admin from django.urls import path from App import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('qui_sommes_nous/', views.qui_sommes_nous, name='qui_sommes_nous'), path('equipe/', views.equipe, name='equipe'), … -
List all groups and parent group of an instance
I have a model Group that has a Foreign key to itself (so a group can have a parent group). It also has a m2m to Establishment. class Group(AbstractBusiness): parent = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True, related_name='children' ) establishments = models.ManyToManyField(Establishment, related_name='groups', blank=True) I'd like to have a list containing all the group ids linked to the establishments + the parent group id of those groups and then so on if they keep having a parent id (if this makes any sence). I've tried something like this, overwriting my initial for loop but this doesn't work. groups = models.Establishment.objects.get(number=establishment_id).groups.all() group_ids = [] for group in groups: group_ids.append(group.id) if group.parent: groups = list(chain(groups, models.Group.objects.filter(id=group.parent.id))) You guys have any clues? -
How to make a model not available on sertain dates and hours in Django?
So, I'm creating a room renting project. The renting is not for a whole day, it's only for 2 hours. I'm gonna have several renting companies each having several rooms for rent with diffrent capacity. So, my question is, if a room is rented on lets say 25/03/2022 20:00(so its gonna be unvailable until 22:00, and also unavailable 2 hours prior), I want the room to be still visible on the site, because someone maybe will want to rent it on diffrent day or the same day in diffrent hour. How to make this exact room unavailable only on this date and this hours? If I make is_available row in the model its gonna switch to False whenever someone rent it, but I want it to be available for all the other days and hours. Here are the models: class Owner(models.Model): name = models.CharField(max_length=100) address = models.TextField() phone = models.PositiveIntegerField() class Room(models.Model): number = models.CharField(max_length=100) owner = models.ForeignKey(Owner, on_delete=models.CASCADE) capacity = models.PositiveIntegerField() is_available = models.BooleanField(default=True) class reservation(models.Model): room_number = models.ForeignKey(Room) guest_name = models.CharField(max_length=200) guests = models.PositiveIntegerField() date_reserved = models.DateTimeField() -
Server responded with a status 404 (Bad Request) - Django
I am working with Django and React. I created a basic API of the Todo list in Django. At the same time, working in the frontend part. When I am trying to add new todo, I get the error of "Server responded with a status 404 (Bad Request). I am getting all the todos that is already in the API. But I am not able to add more. My App.js import React, { useEffect, useState } from "react"; import "bootstrap/dist/css/bootstrap.min.css"; import { ListGroup } from "react-bootstrap"; import "./App.css"; import axios from "axios"; import { Button, Modal, Form } from "react-bootstrap"; import { baseURL } from "./api"; function App() { const initialListState = { id: null, title: "", description: "", completed: false, }; const [todos, setTodos] = useState([]); const [show, setShow] = useState(false); const handleClose = () => setShow(false); const handleShow = () => setShow(true); const [values, setValues] = useState([initialListState]); const changeHandler = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const submitData = () => { let Data = { id: values.id, title: values.title, description: values.description, completed: false, }; axios.post(baseURL, Data).then((response) => { setTodos({ id: response.data.id, title: response.data.title, description: response.data.description, completed: response.data.completed, … -
running django project on a other machine, giving error
I would like to run my django project on a other machine. When running python3 manage.py runserver i get the error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/usr/lib/python3/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3/dist-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/lib/python3/dist-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/usr/lib/python3/dist-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/lib/python3/dist-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/lib/python3/dist-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) …