Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to set up Django model for a balance sheet app
I want to create simple app where a user can keep track of their net worth over time. For example, the user could go in at the end of each month and input their balances for all of their assets and liabilities. The app would keep track of the data over time so it could be displayed as a graph. I'm trying to figure out how to set up my models for this. I think I need to have the balances as a separate class otherwise every time you wanted to add a new date you would have to update the model itself. Here's what I came up with. I'm interested if this is a good way to do this or if there is a cleaner way. class Asset(models.Model): name = models.CharField(max_length=30) description = models.TextField() class Liability(models.Model): name = models.CharField(max_length=30) description = models.TextField() linked_account = models.ForeignKey(Asset,null=True,blank=True) class Meta: verbose_name_plural = "Liabilities" class AssetBalance(models.Model): account = models.ForeignKey(Asset) date = models.DateField() balance = models.FloatField() class LiabilityBalance(models.Model): account = models.ForeignKey(Liability) date = models.DateField() balance = models.FloatField() -
How to use Postman to authenticate Google Login with dj_rest_auth
So I am following the official documentation for Google sign in with DjangoRestFramework using DJ Rest Auth (this link) I intend to authenticate with Postman Oauth2 (by following the guide and generating an Access Token) Postman is generating an access token successfully, but I cannot seem to use this authentication in my API calls. Please who knows which step I am missing - I want to handle everything in Postman. urls.py urlpatterns = [ path('', Home.as_view(), name='home'), path('admin/', admin.site.urls), path('accounts/', include(api_urls, namespace='api')), path('accounts/login/', GoogleLogin.as_view(), name='google_login'), path('accounts/', include('rest_framework.urls')), ] views.py class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = 'http://localhost:8080/accounts/google/login/callback/' client_class = OAuth2Client On calling an API endpoint, I get an invalid token error: If I however visit the Google Login view in my RestFramework UI (in my case http://localhost:8080/accounts/login), I get an endpoint to make a POST, and on making a POST request, a key is generated. Only this key (if used as a Bearer token) works in my API calls. How can I authenticate on Google, and make my API calls independent of the DRF UI? Callback URL has been configured on my Google Developer Client. PS: I feel the answer is in step 6 of the documentation, but I am … -
How to prevent methods of being imported in an outside package at pycharm?
I would like to prevent imports of private methods outside a specific interface in a big commercial project to improve architecture. I've tried with init.py but maintenance is hard and I had problems with circular imports over time. I've also tried with _method() underline to make private methods, but then I could not use these methods inside my own interface. What I would like to set up or within my pycharm configs or by making a customized use of import machinery from python is something like these: -- interface_foo ---- method_foo.py # here I create a public and a private method ---- method_bar.py # here I can import both methods with no issues, cause it is inside inferface ---- api.py # here i display the public methods for other interfaces to use them --interface_baz ----method_baz.py # here I can import ONLY public method By trying to import private methods from interface_foo inside interface_baz should raise an error (like ImportError) -
djando rest framework AssertionError
mi pregunta es porque me arroja este error estoy tratando de actualizar y me dice que estoy recibiendo un un AssertionError class none type mi problema siempre se ha dado con la imagen al enviarla me da siempre problemas asi estuve con mi metodo post hasta que en el serializer lo convert a url mi view.py class PokemonsViewSets(APIView): parser_classes = (MultiPartParser, FormParser, JSONParser,FileUploadParser) def get(self, request,pk=0,format= None, *args, **kwargs): if (pk>0): pokemon = list(PokemonsBBDD.objects.filter(id=pk).values()) if len(pokemon)>0: pokemons = pokemon[0] datos ={'message':"Succes","pokemones": pokemons} else: datos = {"message":"list pokemons not found"} return Response(datos,status=status.HTTP_200_OK) else: queryset = PokemonsBBDD.objects.all() # pokemonId = PokemonsBBDD.objects.get() serializer = ProjectSerializer(queryset, many=True) if len(queryset)>0: datos = {'message':"Succes","pokemones":serializer.data} else: datos = {"message":"list pokemons not found"} return Response(datos,status=status.HTTP_200_OK) def post(self, request, format= None): serialize = ProjectSerializer(data=request.data) if serialize.is_valid(): serialize.save() return Response(serialize.data, status=status.HTTP_201_CREATED) return Response(serialize.errors,status=status.HTTP_400_BAD_REQUEST) def put(self,request,pk,*args,**kwargs): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: serialize = updateSerializer(pokemon, data = request.data) if serialize.is_valid(): return Response(serialize.data) else: print(serialize.error_messages) return Response(serialize.errors) @action(detail=True) def patch(self,request,pk,format= None,*args,**kwargs): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: serialize = updateSerializer(pokemon,data= request.data) if serialize.is_valid(): serialize.save() return Response({'succes':'exitosa'}) else: print(serialize.error_messages) return Response({'error','bad reques'}) def delete(self,request,pk=0,format= None,*args,**kwargsl): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: pokemon.delete() return Response({'message':'dato ELiminado'},status=status.HTTP_200_OK) else: return Response({'messageToFailed':'no se encontro … -
Is it possible to upload an app to a vps server with back in django and front in react.js?
I developed a website that uses react.js and django, and my question is if it is possible to upload it to a vps server. -
REST related/nested objects URL standard
if /wallet returns a list a wallets and each wallet has a list of transactions. What is the standard OpenAPI/REST standard? For example, http://localhost:8000/api/wallets/ gives me { "count": 1, "next": null, "previous": null, "results": [ { "user": 1, "address": "3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd", "balance": "2627199.00000000" } ] } http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/ gives me { "user": 1, "address": "3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd", "balance": "2627199.00000000" } If I wanted to add a transactions list, what is the standard way to form this? http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/transactions ? http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/transactions?offset=100 for pagination -
Set and not let modify foreign key value (user)
I have 2 models that I want to preset the value and ideally have it hidden from the Django admin when creating new record, this way the user don't amend this value. This are the created and modified by that are foreign keys to users. I found this link https://pypi.org/project/django-currentuser/, that i thought it might do the job, however it reverted my django from the latest version to version 3, so I dont want to use it, and also, it doesnt work if i set either created or last modified but not both, if i set it in the 2 models i get 4 errors. I am wondering if there is an easy way to set this default value? from django.db import models from email.policy import default from django.contrib.auth.models import User from django.utils import timezone # from django.contrib import admin # https://pypi.org/project/django-currentuser/ from django_currentuser.middleware import (get_current_user, get_current_authenticated_user) from django_currentuser.db.models import CurrentUserField class Company(models.Model): modified_by = models.ForeignKey(User, related_name='company_modified_by', unique = False, on_delete=models.CASCADE) created_by = CurrentUserField() created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=150, unique = True) class Meta: verbose_name = "Company" verbose_name_plural = "Companies" def __str__(self): return self.name class UserProfile(models.Model): modified_by = models.ForeignKey(User, related_name='user_profile_modified_by', unique = False, on_delete=models.CASCADE)#CurrentUserField(on_update=True) created_by = … -
Deleted the migrations folder accidently so I dropped all my tables in database but still not working
I deleted my migrations folder accidently so to make things work again I dropped all tables in my database as well. But now even tho python manage.py makemigrations is working, python manage.py migrate still says 'No migrations to apply' why? -
Django Rest / React NextJS - pass username in html form back to DB in a post request
How can you pass username in html form back to Django DB, when making a post request? I get the following error when I submit the form null value in column "owner_id" of relation "contracts_contract" How can I adjust it, so that post request is saved and owner (username) is correctly captured in post request in django db nextjs file: const PostRequest = () => { const [name, setName] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); let body = { owner_id: 1, name: name, } axios.post("http://127.0.0.1:8000/contract/contract-create/", body).then(response => { console.log(response) }) }; return ( <form className='form' onSubmit={handleSubmit}> <input type='text' className='form-input' id='name' value={name} onChange={(e) => setName(e.target.value)} /> <button type='submit'> submit </button> </form> ); }; #Models.py class Contract(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) name = models.CharField(max_length=30) #serializers.py class ContractSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Contract fields = '__all__' @api_view(['POST']) def contractCreate(request): serializer = ContractSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: print("data is invalid") return Response(serializer.data) -
I coud not run server
I'm learning django,but i stuck in something, i cant run server(manage.py) from django.urls import path from . import views urlpattern = [ path('hello/',views.say_hello) ] in my django project folder is a urls.py but i created another one for somthing else; this is main urls.py : """storefront URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] -
django, X-CSRFToken is set incorrectly in request header
basically, i got this to actually send a csrf token to the frontend and set it there in cookie section in application tab in dev window in the browser: @method_decorator(ensure_csrf_cookie) def get(self, request, format=None): return JsonResponse({'csrftoken':get_token(request)}) in react side: useEffect(()=>{ axios.get('http://127.0.0.1:8000/csrf/').then((res)=>{ console.log(res.data) Cookies.set('csrftoken',res.data.csrftoken) }) },[]) let handleSubmit = (e) => { e.preventDefault(); axios .post("http://127.0.0.1:8000/signup/", signup, { withCredentials: true, headers: { "X-CSRFToken": Cookies.get("csrftoken") }, }) .then((res) => { setDisabled(true) setIsUp(true) setTimeout(()=>{setIsUp(false) redirect('/')},3000) }) .catch((e) => { console.log(e.response.data) let err = e.response.data setError(err); }); }; on my local machine (on the local hosts): i get these values to match: as you can see both Cookie and X-CSRFToken are matching in request header, however, in production: and the weirder part is that in request header the name of the key in local host is Cookie, but in production it is cookie (c and C difference) and of course I get an error when i make a post request in production server: <p>CSRF verification failed. Request aborted.</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF token from the &#x27;X-Csrftoken&#x27; HTTP header incorrect. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/4.0/ref/csrf/">Django’s help … -
Django Rest framework doesn't accept JWT Authentication
I'm not in that backend and python business and I'm trying to implement a JSON REST-API with django and the django restframework. For the authentication I would like to use simple jwt for django. I implemented it with this getting started guide: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html I get a valid JWT string but if I want to fetch data with a GET request and the jwt in the Authentication header I always get a 403 with {message: 'Authentication credentials were not provided'}. My code looks like this: settings.py from pathlib import Path import os from datetime import timedelta from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions, AllowAny ... INSTALLED_APPS = [ 'rest_framework_simplejwt', 'rest_framework', ] ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), } CORS_ALLOW_ALL_ORIGINS = True PERMISSION_CLASSES = [IsAuthenticated] urls.py from django.contrib import admin from django.urls import include, path from rest_framework.schemas import get_schema_view from rest_framework.documentation import include_docs_urls from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView ) urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('nutzer_api/', include('nutzer.urls')), path('admin/', admin.site.urls), path('docs/', include_docs_urls(title="DatenmanagerAPI")), ] nutzer/settings.py from django.urls import path from . import views urlpatterns = [ path('hello/', views.HelloView.as_view(), name='hello'), ] … -
How to see the raw MongoDB queries Djongo is running?
I am using djongo as my backend database connector engine. The decision to use Django with MongoDB as well as the choice of using Djongo predates me tenure with the team. I am trying to improve the efficiency of a search result for which I want to know the exact "find" query that is being run on MongoDB. But I can't seem to find a way to do it. Is there a way I can see the exact query that djongo is running under the hood? Follow up: I cannot write the exact search query here but it looks something like this queryset = ( ModelName.objects.filter( Q(attr1__icontains=search_term) | Q(foreign_key1__attr__icontains=search_term) ) .distinct() .order_by("-id") ).select_related( 'foreign_key1__attr' ).values( 'attr1', 'foreign_key1__attr' ) I am a bit confused. Does Foreign Key even make sense if my backend is MongoDb? Is this shoddy DB design or does djongo implement some foreign key constraints at the middleware layer? -
Using variables in a class in django
I am trying to make a chart that displays the temperature and timestamp data, however I want to filter it. The current database this data is being taken from looks like this: And I only want the graph to display data from the specific user that is already logged in. Furthermore, I have pages for each room ID showing the data from that room and with that user, and this is where I want the graph to be displayed. So you login and go to a specific room page and the graph shows the temperature and timestamp data from that room (and of course with that username). The current structure displays the chart by uploading the JSON formatted data to a link called API, and the code to get this API data up is displayed here. class ChartData(APIView, models.Model): authentication_classes = [] permission_classes = [] def get(self, request, *args, **kwargs): labels = [] for e in Post.objects.all(): labels.append(e.timestamp) # print(e.room_id) # print(e.username) #print(e.temperature) chartLabel = "my data" chartdata = [] for e in Post.objects.all(): chartdata.append(e.temperature) data ={ "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, } return Response(data) So right now it takes every temperature and timestamp in the database and puts that on the … -
Got this error when i used the command manager server
I am building a dashboard project currently using Django so that I can learn it as well. I am following a tutorial and did as they did it but I am getting this error right now. I am not sure where I went wrong so please anything helps!! Error Message C:\Users\Vignesh\.vscode\Interview Dashboard\dashboard> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 15, 2022 - 15:01:34 Django version 4.1.2, using settings 'dashboard.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [15/Oct/2022 15:01:55] "GET / HTTP/1.1" 200 10681 [15/Oct/2022 15:01:55] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [15/Oct/2022 15:01:55] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [15/Oct/2022 15:01:55] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [15/Oct/2022 15:01:55] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 C:\Users\Vignesh\.vscode\Interview Dashboard\dashboard\dashboard\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Vignesh\anaconda3\lib\site-packages\django\urls\resolvers.py", line 717, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the … -
How do I enforce that child classes have all fields in the database
I have defined a Person class. Than Teacher inherits from person. Is there a way to force Django to generate the table teacher with all the fields from the model, rather then having a foreign key to Person table, and 1 column: about? Also I would like to skip creation of person table, as it's abstract. class Person(models.Model): class meta: abstract = True name = models.CharField(max_length=60) surname = models.CharField(max_length=60) age = models.IntegerField() def __str__(self): return f'{self.surname}, {self.name}' class Teacher(Person): about = models.TextField(null=True, blank=True) -
Django REST Framework - Struggling with nested serializer - This Field is Required
I've been trying all night to get a nested serializer to work, and I'm so deep in it now that I'm struggling to keep track of the changes I've made. This is for a group project for a uni assignment, and I'm still quite new to Django. What I'm trying to accomplish is a CreateAPIView that uses a serializer to create a Composer, get/create a Nationality for it, and then add a row to a lookup table named ComposerNationality. I've gotten close a few times. But right now the I'm getting the following error when trying to POSt via Postman: "nationality_serializer": [ "This field is required." ] Here is what I have so far: models.py class Composer(models.Model): id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) birth = models.IntegerField(blank=True, null=True) death = models.IntegerField(null=True, blank=True) biography = models.TextField(blank=True, null=True, default = 'No Information Available, Check Back Later') bio_source = models.CharField(max_length=200, blank=True, null=True, default = "") featured = models.BooleanField(default=False) composer_website = models.CharField(max_length=300, blank=True, null=True, default = "") image = models.CharField(max_length=300, default = "https://i.picsum.photos/id/634/200/200.jpg?hmac=3WUmj9wMd1h3UZICk1C5iydU5fixjx0px9jw-LBezgg") def __str__(self): return self.firstName class Nationality(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) def __str__(self): return self.name class ComposerNationality(models.Model): composer = models.ForeignKey(Composer, on_delete=models.CASCADE) nationality = models.ForeignKey(Nationality, on_delete=models.CASCADE) def __str__(self): return … -
How to perform inner join of 3 tables in Django?
I have this Django model example class Users(models.Model): first_name = models.CharField(max_length=255, blank=True, null=True,unique=True) last_name = models.CharField(max_length=255, blank=True, null=True) class TableA(models.Model): user= models.ForeignKey(Users, on_delete=models.CASCADE) atrribute_a_1 = models.CharField(max_length=255, blank=True, null=True,unique=True) atrribute_a_2 = models.CharField(max_length=255, blank=True, null=True) class TableB(models.Model): user= models.ForeignKey(Users, on_delete=models.CASCADE) table_a_id= models.ForeignKey(TableA, on_delete=models.CASCADE) atrribute_b_1 = models.DecimalField(max_digits = 100, decimal_places = 8, default=0) atrribute_b_2 = models.DecimalField(max_digits = 100, decimal_places = 8, default=0) atrribute_b_3 = models.DecimalField(max_digits = 100, decimal_places = 8, default=0) class TableC(models.Model): user= models.ForeignKey(Users, on_delete=models.CASCADE) table_a_id= models.ForeignKey(TableA, on_delete=models.CASCADE) atrribute_c_1 = models.DecimalField(max_digits = 100, decimal_places = 8, default=0) atrribute_c_2 = models.DecimalField(max_digits = 100, decimal_places = 8, default=0) class TableASerializer(serializers.ModelSerializer): class Meta: model = TableA fields = '__all__' class TableBSerializer(serializers.ModelSerializer): class Meta: model = TableB fields = '__all__' class TableCSerializer(serializers.ModelSerializer): class Meta: model = TableC fields = '__all__' I want to perform this action: select * from TableA inner join TableB on TableA.id=TableB.table_a_id inner join TableC on TableA.id=TableC.table_a_id where TableA.id=3 How am I supposed to do that? as I tried filter and select_related and it didn't work as I checked in the internet or even documentation examamples they start the selection from TableC or TableB , but in my case I want to start from TableA Like: my_query=TableA.Objects.filter(id=3)....something serializer=TableASerializer(my_query,many=False).data In results I want [All … -
DRF nested serializers returns empty dictionary
I have two modals designation and UserModal class DesignationModal(models.Model): designation=models.CharField(max_length=100) def __str__(self): return self.designation class UserModal(AbstractUser): username=models.CharField(max_length=300,unique=True) password=models.CharField(max_length=300) email=models.EmailField(max_length=300) designation=models.ForeignKey(DesignationModal,on_delete=models.CASCADE, related_name="desig",null=True) def __str__(self): return self.username every user only have one designation. I wrote serializer for that. class DesignationSerializer(serializers.Serializer): class Meta: model=DesignationModal fields=['designation','id'] class UserSerializer(serializers.ModelSerializer): designation=DesignationSerializer(read_only=True,many=False) class Meta: model=UserModal fields=['id', 'username','designation'] I'm getting a JSON response like this { "status": true, "data": [ { "id": 3, "username": "akhil", "designation": {} } ] } no values in the dictionary, when I used to rewrite the serializer code like this. class UserSerializer(serializers.ModelSerializer): designation=serializers.StringRelatedField() class Meta: model=UserModal fields=['id', 'username','designation'] im getting designation values as string { "status": true, "data": [ { "id": 3, "username": "akhil", "designation": "agent" } ] } why im not getting values in previous way ? -
source parameter in django serializer not working
I am trying to serialize a nested request body data (just the part of it) body - { "context": { "timestamp": "2022-10-13T09:48:47.905Z", }, "message": { "intent": { "item": { "descriptor": { "name": "apple" } }, }}} serializer class SearchSerilizer(serializers.Serializer): timestamp = serializers.CharField(source="context.timestamp", max_length=35) Caller snippet serializer = SearchSerilizer(data=request.data) if serializer.is_valid(): print(serializer.data) return Response(serializer.data) else: print(serializer.errors) return Response(serializer.errors) And it prints {'timestamp': [ErrorDetail(string='This field is required.', code='required')]} -
installation of Virtual Environment for Django
Is it necessary every time after shutdown I need to create virtual environment for the Django project I'm doing. correct me in Some ways possible . -
for loop in Django for custom n number of times
I want to run for loop based on the number of each individual model entry, I have a testimonial model and one of its field is ratings(and integer field) I want to run a for-loop for n times, where n=ratings value for that particular entry. for ex: here ratings = 4 I want to run for-loop for 4 times so that I can show 4 stars in the testimonial section. I tried doing this:(which of course is the wrong method, displayed just for sake demonstration of what I want) the models.py looks something like this: -
How to modify the display of a validation error in Django?
I wanted to create simple datepicker that does not accept back dates. Within my models.py I have defined MealDay class and standalone functionvalidate_pub_date. The logic behin works just fine, but I do not understand the way Django is showing up the ValidationError("Date can't be past!"). Why this is where it is, and why it seems to be within <li> tag? Is there any possibilty to handle the error within the HTML template or any other way to add some html/css to it? There is how the error looks now: models.py: def validate_pub_date(value): if value < timezone.now() - datetime.timedelta(days=1): raise ValidationError("Date can't be past!") return value class MealDay(models.Model): day = models.DateTimeField(default=timezone.now().day, validators = [validate_pub_date]) breakfast = models.TextField(max_length=100, blank=True) lunch = models.TextField(max_length=100) dinner = models.TextField(max_length=100, blank=True) views.py class MealdayCreateView(CreateView): model = MealDay template_name = "mealplanner/mealday_new.html" form_class = CreateMealdayForm forms.py class CreateMealdayForm(ModelForm): class Meta: model = MealDay fields = '__all__' widgets = { 'day': forms.DateInput(attrs={'type':'date'}), } mealday_new.html {% extends "mealplanner/base.html" %} {% block content %} <h1>Plan your meals!</h1> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock content %} {% endblock content %} -
How to structure the user model for todo list Django
So my boss wants me to learn django in one week i have no experience at all im stuck in a tutorial hell so to escape hell, im going to make a simple api for a todo list app. As of right now , i have developed endpoints for GET and POST but i want every list for a new user so, { users:[ { user_1: Tasks: [ { 'task1':abc, } ] } ] } Please help -
How to resolve this issue when building a docker image of a Django app
I'm trying to dockerize my django app but I'm having an issue where the CMD isn't recognizing the "python3" command. I created the requirements.txt, Dockerfile and .dockerignore file in the root directory and the Dockerfile contains the follow: FROM python:3.8-slim-buster WORKDIR /app COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . CMD [ "python3", "manage.py", "runserver", "0.0.0.0:8000" ] I'm using VS Code and the intellisense is highlighting all the items in the CMD list as an error. When I try to build the image, I'm getting the following error: Error response from daemon: dockerfile parse error line 12: unknown instruction: "PYTHON3", Can anyone provide any possible solutions to the problem?