Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i add a footer at the end of the website which is contains for loop in html?
I used : .footer{ position: relative; height: 130px; clear: both; background-color: red; to set a footer at the end of the website but now the footer is not at the end of the all products: html: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> </head> <body style="background-color: #36454F;"> {% for i in p%} <div class='card'> <div class="number">{{i.Number}}</div> <img src="{{i.image}}"></img> <p id="id">{{i.description}}</p> <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{i.price}}</span> buy</button> </a> </div> {%endfor%} <div class="footer"> <h3>hello</h3> </div> </body> </html> css: .card { max-width: 400px; margin: 0auto; text-align: center; font-family: arial; border-style: solid; border-width: 6px; position: relative; top: 611px; margin-bottom: 33px; margin-right: 33px; justify-content: center; float: left; } .footer{ position: relative; height: 130px; clear: both; background-color: red; } .card img{ height: 400px; width: 400px; vertical-align: middle; } .price {background-color: #f44336; font-size:22px; border-radius: 3px; position: absolute; bottom: 0px; right: 0px; padding: 3px; } .card button { border: none; color: white; background-color: #000; position: relative ; cursor: pointer; width: 100%; height: 100px; font-size: 44px; align-items: center; } .card button:hover { opacity: .5; background-color: #330; } #id{ background-color: palevioletred; color: white; margin: 0; font-size: 17px; } .number{ width: 50px; height: 50px; background-color: #330; color: yellow; border-radius: 50%; position: … -
how to override django/wagtail url path in nginx?
I want to run several wagtail blogs on my server. The code i have is based on a couple of containers for each blog : one nginx container for the frontend and one container for the backend. I would like to serve both containers on one port with the nginx frontend served on / and the backend accessible on /wagtail so i could access to the admin at /wagtail/cms-admin. However when i use this config file for my nginx: server { listen 80; server_name localhost; location / { root /usr/share/nginx/html/storybook-static; index index.html index.htm; try_files $uri $uri/ /index.html; } location /wagtail { proxy_pass http://172.20.128.2:8000;#wagtail server running there proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 20M; } location /static/ { alias /app/static/; } location /media/ { alias /app/media/; } } the wagtail throws me a msg error "not found". I'm wondering if i dont need to configure something in my wagtail/django files so it recognizes it is served at /wagtail? Any hint on what i'm missing in the configuration? -
TypeError: byte indices must be integers or slices, not str & status code 500
I'm building an e-commerce site using ReactJS and Django (using redux) I'm trying to send a post request to my DB but I'm getting the following error: firstName = data['firstName'], TypeError: byte indices must be integers or slices, not str [31/May/2022 16:56:55] "POST /api/create/ HTTP/1.1" 500 63122 Here is my code: View.js api_view(['POST']) @csrf_exempt def createCitizen(request): data = request.body citizens = Citizen.objects.create ( firstName = data['firstName'], lastName = data['lastName'], dateOfBirth = data['dateOfBirth'], address = data['address'], City = data['City'], zipCode = data['zipCode'], cellular = data['cellular'], landLine = data['landLine'], hadCovid = data['hadCovid'], previousConditions = data['previousConditions'] ) serializer = CitizensSerializer(citizens, many=True) serializer.save() return JsonResponse(serializer.data, safe=False) The relevant part in RegisterPage.js const submitHandler = (e) => { e.preventDefault(); dispatch(createCitizens({ firstName, lastName, dateOfBirth, address, City, zipCode, cellular, landLine, hadCovid, previousConditions })) } return ( <Form onSubmit={submitHandler}> <Row> <h4>Please enter your information:</h4> </Row><br></br><Row className="mb-3"> <Form.Group as={Col} controlId="firstName"> <Form.Label>First Name</Form.Label> <Form.Control placeholder="Enter first name" required value={firstName} onChange={(e) => setFirstName(e.target.value)} /> </Form.Group> ... citizenAction.js export const createCitizens = (citizens) => async (dispatch) => { try { dispatch({type: 'CITIZEN_CREATE_REQUEST'}) const {data} = await axios.post('/api/create/', citizens) dispatch({ type: 'CITIZEN_CREATE_SUCCESS', payload: data }) } catch (error) { dispatch({ type: 'CITIZEN_CREATE_FAIL', payload: error.response && error.response.data.message ? error.response.data.message : error.message, }) } } … -
How to view the human readable Text in Enum Choices Django Models?
I have orders model init I have Status Enum Class I want to show the readable Text How ? models: from django.utils.translation import gettext_lazy as _ class Order(models.Model): class OrderStatus(models.TextChoices): Paid = "P", _("Paid") Shipping = "S", _("Shipping") Done = "D", _("Done") id = models.AutoField(primary_key=True) customer: User = models.ForeignKey(User, on_delete=models.CASCADE) product: Product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.PositiveIntegerField() status: OrderStatus = models.CharField( max_length=2, choices=OrderStatus.choices, default=OrderStatus.Paid ) created_time = models.DateTimeField(auto_now_add=True) last_updated_time = models.DateTimeField(auto_now=True) def __str__(self) -> str: status = Order.OrderStatus(self.status) return f"{self.customer.username}-{status.label}" @property def total_price(self) -> float: return self.amount * self.product.price def get_absolute_url(self) -> str: return reverse("get_order", kwargs={"pk": self.id}) is there something I need to write in my template to Get it or Where is the Problem ? template Code : <td>{{order.status}}</td> -
how to search foreign field in Django RestFramework Api?
I am trying to apply foreign field search function in django restFramework api. like shown in below class SearchborrowList(ListAPIView): queryset = borrow.objects.all() serializer_class = borrowserializer filter_backends = [SearchFilter] search_fields = ['student'] in this search fields = ['student'], student field is foreign field. When I search its show an error Related Field got invalid lookup: icontains how can I retrieve foreign field when search. -
Am trying to save user radio button input of an html form to my database
please am new to django, and am trying to save user radio button input of an html form to my database by category have created for different post using CBV, i really don't know how to go about please i need help , thanks in advance here is my models.py ' class Data(models.Model): 'name= models.CharField(max_length=50, default='') data=models.CharField(max_length=50 ,blank=True,null=True) `class Category(models.Model): name =models.CharField(max_length=200,default='') class CandidateForm(models.Model): image= models.ImageField(upload_to='images/', width_field=None,default=0) data=models.ForeignKey(Data,blank=True,null=True,on_delete=models.PROTECT) category=models.ForeignKey(Category,blank=True,null=True,on_delete=models.PROTECT) Nickname=models.CharField(max_length=100,default='') Name=models.CharField(max_length=100,) def __str__(self): return self.Nickname here is my views.py def vote_data(request): if request.method == 'POST': post=models.Data() post.data=models.Category.objects.filter(name='category') post.name=request.POST['candidate'] post.save() return redirect('Home') and lastly, the category.html page <form action="{%url 'data' %}" method="POST" name=""> {% csrf_token %} {% for candidate in Post.candidate %} <div class=".col-md-4-flex" data-aos="zoom-out"> <div class="position-relative"> <img src="{{candidate.image.url}}"> <p>{{candidate.Name}}</p> <label for="candidates_{{candidate.Nickname}}" class="radio-inline"> <input type="radio" name="candidate" value="{{candidate.Nickname}}" id="candidates_{{candidate.Nickname}}">{{candidate.Nickname|upper}} </label> </div> {% endfor %} </div> <input type="submit" value="submit"> sorry for uneccessary information. -
Django MultiSelectField Selected Choice Yields "Not a Valid Choice" Error
I am new to Django and have a MultiSelectField in my Meal Model. I am also utilizing a MultipleChoiceField with widget CheckBoxSelectMultiple in my Meal Form. When I select a checkbox in the Template and POST the form, I get an error which states, "[ValidationError(["Value ['CHICKEN CASSEROLE'] is not a valid choice."])]}). I am wondering what I am doing wrong here and need some assistance in figuring this out. Any help is appreciated. Below is my code for my Model and Form: class Meal(models.Model): day = models.CharField(max_length=255, blank=True) category = models.CharField(max_length=100, blank=True) meal_time = models.TimeField(null=True, blank=True, verbose_name='Meal Time') recipes = MultiSelectField(max_length=5000, choices=[], null=True) meal_id = models.IntegerField(null=True, blank=True) menu = models.ForeignKey(Menu, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return "%s %s %s %s" % ( self.day, self.category, self.meal_time, self.recipes) class Meta: app_label = "mealmenumaster" managed = True class MealForm(forms.ModelForm): day = DynamicChoiceField(choices=[], required=False) category = forms.ChoiceField(choices=(('', 'None'),) + CATEGORY, required=False) recipes = forms.MultipleChoiceField(label="Select Recipe(s)", widget=forms.CheckboxSelectMultiple(), required=False) meal_id = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: widgets = {'meal_time': TimeInput()} model = Meal fields = ['day', 'category', 'meal_time', 'recipes', 'meal_id'] app_label = "mealmenumaster" def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id', None) super(MealForm, self).__init__(*args, **kwargs) self.fields['recipes'].choices = [(x.name, x.name) for x in … -
How to get Checkbox Select Multiple for profile page
Beginner here in Django. Goal: I would like to get a multiple checkbox selection for favorite categories and save those in the database. Problem Right now I have a profile form and model, and the CheckboxSelectMultiple widget is not working like I want it to work. The categories are stored in another model which I reference in the user profile. # # # # user/forms/profile_form.py class ProfileForm(ModelForm): class Meta: model = Profile exclude = [ 'id', 'user'] widgets = { 'favourite_categories': widgets.CheckboxSelectMultiple(attrs={'class': 'form-control'}), 'profile_picture': widgets.TextInput(attrs={'class': 'form-control'}) } # # # # user/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) favorite_categories = models.ManyToManyField(Category, blank=True) profile_image = models.CharField(max_length=200, null=True, blank=True) # # # # user/views.py @ login_required def profile(request): user_profile = Profile.objects.filter(user=request.user).first() if request.method == 'POST': form = ProfileForm(instance=user_profile, data=request.POST) if form.is_valid(): user_profile = form.save(commit=False) user_profile.user = request.user user_profile.save() return redirect('profile') return render(request, 'user/profile.html', context={"form": ProfileForm(instance=user_profile)}) # # # # templates/user/profile.html <div class="shadow p-4 mb-5 mx-5 bg-body rounded"> <form class="form form-horizontal" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-primary" value="Update" /> </form> </div> The output of this can be seen in the picture. PS. I also don't know how to use ImageField … -
'django-admin help' Fatal error in launcher: Unable to create process
When I try to run "django-admin help" or any other django-admin command in the vscode terminal (within the virtualenv) it gives me the following error : Fatal error in launcher: Unable to create process using '"F:\DevOps\Django\btre_project\venv\Scripts\python.exe" "F:\Django\btre_project\venv\Scripts\django-admin.exe" help': The system cannot find the file specified. The whole Django project was located in F:\DevOps first but then I moved the Django folder outside the F:\DevOps so it's now at this location currently "F:\Django". Virtual environment can be activated and deactivated perfectly and also if I start the server with "python manage.py runserver" The server is up and running. But whenever I try to run the django command it gives me the above error. Also, in the virtual environment of project django is installed and I also tried reinstalling the django in the virtualenv with pip but nothing worked out and I get the same error. Any help would be appreciated, thanks. -
hi, I am using python3 for one of my project and I am getting msilib module error. I am using Mac. and when ever I start my server I am getting error
I am getting some module error while try to run the server for python develop on Django enter image description here -
React problems with updating state
I'm new to React and trying to build a twitter like app for this project https://cs50.harvard.edu/web/2020/projects/4/network/. This is my code: function App (){ const [state, setState] = React.useState({ view: Allpostsview, newpost: '' }); function Navitem(props){ return( <a class="nav-link" style={{cursor:'pointer'}} onClick={()=>loadNewpage(props)}>{props.content}</a> ) } if(document.querySelector("#newpost")){ ReactDOM.render(<Navitem content='New Post' view={Newpostview} />, document.querySelector("#newpost")); } if(document.querySelector("#allposts")){ ReactDOM.render(<Navitem content='All Post' view={Allpostsview}/>, document.querySelector("#allposts")); } if(document.querySelector("#user")){ ReactDOM.render(<Navitem content='Username' view={Userview}/>, document.querySelector("#user")); } if(document.querySelector("#following")){ ReactDOM.render(<Navitem content='Following' view={Followingview}/>, document.querySelector("#following")); } function loadNewpage(props){ setState({ ...state, view: props.view }); } function Allpostsview(){ return( <h1>All Posts</h1> ); } function Newpostview(){ return( <div className="formgroup functionDiv"> <h2>New Post</h2> <textarea className="form-control" rows="3" onChange={()=>handleText(event)}></textarea> <button className="btn btn-primary" onClick={()=>handelNewpost()}>Post</button> </div> ); } function handleText(event){ console.log(event.target.value) console.log(state) setState({ ...state, newpost: event.target.value }); } function handelNewpost(){ console.log('handleNewpost') } function Followingview(){ return( <h1>Following</h1> ); } function Userview(){ return( <h1>Username</h1> ); } return( <state.view /> ) } if(document.querySelector("#app")){ ReactDOM.render(<App />, document.querySelector("#app")); } I have two problems When I try to debug the code with the chrome extensions Components feature, my Navitems stop working I'm currently working on the new post feature. The function handleText shows me that my state is whatever view I was in before I clicked on new post. Therefore, when I try to enter text the view always changes. I'm … -
Django - How to save individual elements of a CharField when a form is submitted?
When I submit my form, I want the text submitted as "note" to be split up, say by paragraph, and also saved to the "tag" part of my model automatically. I have the following as my models.py class NoteModel(models.Model): note = models.CharField( max_length = 5000 ) def __str__(self): return f"{self.note}" class NoteTagModel(models.Model): note = models.ForeignKey( NoteModel, on_delete=models.CASCADE, related_name="notes", blank= False, null = True, ) tag = models.CharField( max_length = 5000 ) def __str__(self): return f"Note: {self.note} | Tag: {self.tag}" I have the following as my forms.py class NoteTagForm(ModelForm): class Meta: model = NoteTagModel fields = [ 'note', ] Is there a way of doing this with Signals? Or would using a hidden inline formset be the best way? Any other suggestions are greatly appreciated. I appreciate that JavaScript may be needed to separate out the text and declare as a variable to be saved as a form value. Many thanks -
djangorestframework-simplejwt with auth0 - settings issue?
environment: django (4.0.4) rest_framework (3.13.1) djangorestframework-simplejwt (5.2.0) What are the exact settings that should be used with simplejwt+auth0? I cannot find any example and unfortunately i've failed to figure it out by myself. I have tried the following: AUTH0_DOMAIN = 'dev-demo-xxxx.auth0.com' API_IDENTIFIER = 'xxxxx' PUBLIC_KEY = None JWT_ISSUER = None if AUTH0_DOMAIN: jsonurl = request.urlopen('https://' + AUTH0_DOMAIN + '/.well-known/jwks.json') jwks = json.loads(jsonurl.read().decode('utf-8')) cert = '-----BEGIN CERTIFICATE-----\n' + jwks['keys'][0]['x5c'][0] + '\n-----END CERTIFICATE-----' certificate = load_pem_x509_certificate(cert.encode('utf-8'), default_backend()) PUBLIC_KEY = certificate.public_key() JWT_ISSUER = 'https://' + AUTH0_DOMAIN + '/' SIMPLE_JWT = { 'ALGORITHM': 'RS256', 'AUDIENCE': 'https://issuer-domain', 'ISSUER': JWT_ISSUER, 'VERIFYING_KEY': PUBLIC_KEY } but tokens that are sent from client (retrieved successfully using auth0 javascript library) are not verified properly on the backend. (token has been successfully verified using jwt.io debugging tool) current error: code: "token_not_valid" detail: "Given token not valid for any token type" -
Selecting first item in a subquery of many to many relationship in django
Consider having a Book model with many Comments (from different Users) which may belong to many Categories. class Category(Model): title = CharField(max_length=200) class Book(Model): title = CharField(max_length=200) categories = ManyToManyField(Category) class User(Model): name = CharField(max_length=200) class Comment(Book): content = TextField() book = ForeignKey(Book, null=False, on_delete=CASCADE) user = ForeignKey(User, null=False, on_delete=CASCADE) I want to select comments for an specific Book, and for each Comment, annotate it with the number of comments that the writer of that Comment wrote for the first Category of that book. And I want to this in a single query. Something like this: def get_commnets(book): main_category = book.categories.first() n_same_comments_subquery = Subquery( Comments.objects .filter(user__id=OuterRef('user_id'), book__category__first=main_category) .annotate(count=Count('pk')) .values('count') )[:1] comments = ( book.comment_set .annotate(n_same_comments=n_same_comments_subquery) ) return comments The previous piece of code does not work, obviously. This is because there is not any lookup like first. I've tried many other solutions, but non of them worked. How can I achieve this goal? Thank you in advance. -
Django override __init__ form method using ModelForm
I have a foreign key (zone_set) as a choice field in a form. It should only display current project's zone_set . As you can see, It is not the case since it's displaying a zone_set: I belong to an other project, I should not be displayed here which does not belong to the current project. Any help please ! Here is my form but it doesn't work class ODMatrixForm(forms.ModelForm): class Meta: model = ODMatrix # fields = '__all__' exclude = ('size', 'locked',) def __init__(self, current_project=None, *args, **kwargs): super().__init__(*args, **kwargs) if current_project: queryset = ZoneSet.objects.filter(project=current_project) self.fields['zone_set'].queryset = queryset -
How to stop adding
How can I prevent adding an object if there is an exact same object in the cell room_bool == False in Django rest api models.py class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True, verbose_name='Релевантность') category = models.CharField(max_length=150, verbose_name='Категория') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', help_text='Номер в который хотите заселить гостя!', ) first_name = models.CharField(max_length=150, verbose_name='Имя') last_name = models.CharField(max_length=150, verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Администратор',related_name='admins') pasport_serial_num = models.CharField(max_length=100, verbose_name='Серия паспорта', help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа', help_text='Загружайте файл в формате .pdf') visit_date = models.DateField( default=django.utils.timezone.localdate, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, verbose_name='Дата отбытия', default='После ухода!') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False, verbose_name='Релевантность', help_text='При бронирование отключите галочку') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool},{self.admin}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' views.py class RegCreate(CreateAPIView): queryset = Registration.objects.all() serializer_class = RegSerializer serializers.py class RegSerializer(serializers.ModelSerializer): admin = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Registration exclude = ['price', 'visit_date'] -
Add field from LDAP to user object
pretty new to software development so please bear with me. I need to show password_set_date within the user object of my app. Currently, when I console.log(sessionStorage.getItem(‘user’)) (from the front-end) I get something like this: {id: id, username: username, first_name: first_name, last_name: last_name, date: date} I need to add a password_set_date field to this object password_set_date is not a column in the postgres DB but is returned from LDAP. I’ve tried modifying the models.py AbstractUser model, views.py file & serializers.py file, but I honestly don’t understand them or their relationship. I don’t need to modify the authentication. Let me know if you need any additional information/code. Greatly appreciate your help! -
How to fix CORS - same domain, Django API and React site
I have a page developed in React deployed with vercel, which makes requests to a Django web server. I've put them under my domain: one is page.example.com and the other is api.example.com. However, when the page makes requests to api.example.com I get a CORS error. My settings look like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig', 'djoser', 'rest_framework.authtoken', "rest_framework_api_key", 'oauth2_provider', 'drf_api_logger', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'drf_api_logger.middleware.api_logger_middleware.APILoggerMiddleware' ] I've tried CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_ALL_ORIGINS = True as well as CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["https://page.example.com"] CORS_ORIGIN_WHITELIST = ("https://page.example.com') , to no avail. -
Django with postgresql arrayfield of enum
I have a probleme to link my django application to my postgresql database. I have create a custom type currencies in postgresql and I use it as an array. // Type create type currencies as enum ('EUR'); // Usage currencies currencies[] not null In Django, I have made a Enum Currencies ans try to use it as a choices in a Charfield with no succes using the doc.. The django doc about Arrayfield class Currencies(models.TextChoices): EURO = 'EUR', 'euro' from django.contrib.postgres.fields import ArrayField currencies = ArrayField( base_field=models.CharField( choices=Currencies.choices, max_length=3 ), default=list ) -
Does flask's database take space in storage of the computer
does the flask's database, for example users.db consume space on the storage of the computer? I am asking this because I don't know if Django's media folder is worse and consume more space than flask's database when you try to store images there with b64encode. -
Use of mixins for CRUD in Django Rest Framework
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. I use mixins from REST framework https://www.django-rest-framework.org/api-guide/generic-views/#mixins I have found some relevant examples but still, my serializer is only returning the fields from the Student model for CRUDoperation. I'm not able to see the Course models field in REst api ui. How can I do CRUD operation with using mixins ? How to display Data from two model without creating new model in Django? use of mixins class defined in Django rest framework models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" ###I combine both Student and Course into one class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = … -
How to fix a problem trying to deploy a django app to Heroku
When I try to deploy my django app to Heroku with $git push heroku main I keep getting- ERROR: Could not find a version that satisfies the requirement apt-clone==0.2.1 (from versions: none) Please help! -
TypeError: history.push is not a function. In my opi udemy course
Im following tutorial on udemy and facing critical problem, what is stopping me from further coding.... There is no typeo... I have copied sourcecode. Im having problem with selecting payment method... Im 100% sure is about "type=radio" I just cant select it, and by pressing Continue - error above error is occurring.. TypeError: history.push is not a function submitHandler 20 | const submitHandler = (e) => { 21 | e.preventDefault() 22 | dispatch(savePaymentMethod(paymentMethod)) > 23 | history.push('/placeorder') | ^ 24 | } 25 | 26 | return ( function PaymentScreen(history) { const cart = useSelector(state => state.cart) const { shippingAddress } = cart const dispatch = useDispatch() const [paymentMethod,setPaymentMethod] = useState('paypal') if(!shippingAddress.address ) { history.push('shipping') } const submitHandler = (e) => { e.preventDefault() dispatch(savePaymentMethod(paymentMethod)) history.push('/placeorder') } return ( <FormContainer> <CheckoutSteps step1 step2 step3 /> <Form onSubmit={submitHandler}> <Form.Group> <Form.Label as='legend'>Select Method</Form.Label> <Col> <Form.Check type='radio' label='PayPal or Credit Card' id='PayPal' name='paymentMethod' checked onChange={(e) => setPaymentMethod(e.target.value)} > </Form.Check> </Col> </Form.Group> <Button type='submit' variant='primary'> Continue </Button> </Form> </FormContainer> ) }``` -
Django: How to filter a queryset by a another model in django
i have a model Course and another model Video that is a foreignKey to the Course model. Now what i want to do is this, i want to display all the videos related to a course and display the videos count along side the name of the course in a a list view not in the detail view. this is the code i have written but it keep showing an error views.py def my_courses(request): courses = Course.objects.filter(course_creator=request.user) lectures = Video.objects.filter(course=courses).count() context = { 'courses': courses, 'lectures':lectures, } return render(request, 'dashboard/my_course.html', context) error that the code above shows The QuerySet value for an exact lookup must be limited to one result using slicing. -
Django choices list conversion
I want to use a list I have created from a static json file as a menu option on my web page. This does not work when I makemigrations. I believe the issue is that choices is expecting the two field format, rather than the list I have created. How do I convert this? Makemigrations error: ValueError: too many values to unpack (expected 2) from django.db import models #Generic for models from django.contrib.auth.models import User #Required for dynamic user information from django.forms import ModelForm #Custom form #from django.contrib.postgres.fields import JSONField #Required to support json for lists - Obsolete? #from django.db.models import JSONField #Required to support json for lists - Also obsolete? from jsonfield import JSONField import json #json static data imports data = open('orchestration/static/router_models.json').read() #opens the json file and saves the raw inventory contents inventory = json.loads(data) #converts to a json structure #Constructor for the list of router models ROUTER_MODELS = [] #List of router models for routers in inventory["router_models"]: print(routers["model"]) ROUTER_MODELS.append(routers["model"]) #Unique order. Top of heirachy tree class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) #Unique name of order created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) #Person who created the order created_at = models.DateTimeField(auto_now_add=True) #Date/Time order was created def __str__(self): return …