Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload image from react native to Django along with name and email
Does any body know how we send image,email and name from React Native to Django </Text> <View style={{flexDirection:'row',}}> <View style={{marginTop:20,}}> <Text style={{borderWidth:1, backgroundColor:'white', width:50, height:50, borderRadius:40, textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> 1 </Text> <Text style={{fontSize:19,color:'white',textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Photos </Text> <Text style={{color:'white',fontSize:7,textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Enter all the information about {"\n"} your car </Text> </View> <View style={{paddingLeft:10,marginTop:20,}}> <Text style={{borderWidth:1, backgroundColor:'white', width:50, height:50, borderRadius:40, textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> 2 </Text> <Text style={{fontSize:19,color:'white',textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Photos </Text> <Text style={{color:'white',fontSize:7,textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Upload pictures of your {"\n"} cars from all angles </Text> </View> <View style={{paddingLeft:10,marginTop:20,}}> <Text style={{borderWidth:1, backgroundColor:'white', width:50, height:50, borderRadius:40, textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> 3 </Text> <Text style={{fontSize:19,color:'white',textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Photos </Text> <Text style={{color:'white',fontSize:7,textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Add the price at which you {"\n"} are will to sell the car </Text> </View> </View> </View> </ImageBackground> <View style={{backgroundColor:'green', width:'100%', height:400, marginTop:120,}}> <Text style={{alignSelf:'center', fontSize:25, color:'white',}}> Car Information </Text> <TextInput style={styles.inputstyle} label = "City" value = {city} mode = "outlined" onChangeText= {Text => setcity(Text) } /> <TextInput style={styles.inputstyle} label = "Car Information" value = {carinfo} mode = "outlined" onChangeText= {Text => setcarinfo(Text) } /> <TextInput style={styles.inputstyle} label = "Milage" value = {milage} mode … -
Django .cleaned_data.get()
class UserRegistration: """This class doesn't inherit to any parent class.""" def register(request): if request.method == 'POST': """Then takes the POST data.""" form = UserCreationForm(request.POST) # Check the data from the form if it's valid if form.is_valid(): username = form.cleaned_data.get('username') where's that username coming from that has been passed as a parameter in the cleaned_data? -
Run External Python script outside the django project through html button
I am trying to run python script through html button but I am getting the following error. I don't know why. kindly help to get rid off it. The error is: module 'sys' has no attribute 'execute' views.py: from subprocess import run, PIPE from django.shortcuts import render import requests import sys def external(request): out = run([sys.execute,'/home/abc/Documents/test.py'], shell=False, stdout=PIPE) print(out) return render(request, 'home.html', {{'data1': out}}) home.html: <html> <head> <title> RUN PYTHON SCRIPT </title> </head> <body> <form action='{% url "external" %}' method="post"> {% csrf_token %} <input type="submit" name="btn" value="start analyse" id="toggle1" onclick="location.href='{% url 'external' %}'" /> </form> </body> </html> urls.py: path('external/', views.external, name="external"), Even the button doesn't execute the test.py python script and gives the following error: module 'sys' has no object 'execute' in views.py kindly help me to run script through html button -
Django doesn't save record to database
I have a view with one button that redirect to another view that is supposed to save data to a database HTML view 1 <a href="upd_dab_seq"> <button type="button" class="btn btn-dark">Update DB</button> </a> Python view 2 def upd_dab_seq(request): # clean DB Sequencies.objects.all().delete() arr = os.listdir('main_app/sequencies') for i in range(len(arr)): # Insert in the database Sequencies(name = arr[i], description = '').save() print(arr[i]) return redirect('/settings') MODEL from django.db import models class Sequencies(models.Model): name = models.CharField(max_length=30) description = models.TextField() URLS urlpatterns = [ path("settings", views.settings, name="settings"), path("upd_dab_seq", views.upd_dab_seq, name="upd_dab_seq"), ] Now, everything seems to work but no records have been saved on the databse. The print() works and I got no error. I've tried Sequencies.objects.create(name = arr[i], description = ' ') as well but nothing happens I'm using the default SQLite DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } -
Problem with django foreign key auth_user
I am developping a HR project with django. I want to save the information which user modified my person model the last time. Therefore, my model.py contains lines like these: class person(models.Model): modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_modified', verbose_name='Modifiziert von') In admin.py, I save the modified_by information like this def save_model(self, request, obj, form, change): obj.modified_by = request.user However, my class person is also my authentication user model, as defined in settings.py AUTH_USER_MODEL = 'person.person' I assume that in my database, modified_by directly refers to my AUTH_USER_MODEL. But the database looks like this: "person_person_modified_by_id_5069ed54_fk_auth_user_id" FOREIGN KEY (modified_by_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED auth_user is not filled meaningfully so that I cannot save any information as it crashes when filling the "modified_by" field. Does anyone have a good idea how to solve this problem? I tried changing the ForeignKey to 'self' but this didn't work. Thanks and cheers, Philipp -
Remove Internal Link option
I know this question has been asked before, but the only given solution was hacky and doesn't fully work, at least not with the current version of wagtail. I want to remove the Internal Link option from the page chooser, as for some reason, using the Internal Link just returns "None" meaning it doesn't work. I can link internally manually with the external link option anyway, so I have tried removing it however I can. I have hiding it using CSS and defaulting to external link using JS and hooks, but that doesn't work (any time I create a new link it goes back to defaulting to internal link). I have now also tried replacing wagtailadmin/chooser/_link_types.html by making my own inside templates as the documentation seems to suggest, but that doesn't seem to work either as the old template still seems to be in use... -
How to check if policy ID contains four number exact match in Django
Asking for help on how to detect existing policy that has exact match on filename. Example : GIRL4876S is still passed even though BOY4876T already exists. def policy_exists(policy_id, ref=None): filename = policy_id + '.xml' try: if ref: repo.get_contents('policies/' + filename, ref) else: # no ref default = previous release commit repo.get_contents('policies/' + filename, prev_release_commit()) return True except UnknownObjectException: return False def submit_new(submissions): errors = [] for sub in submissions: if sub.attrib['defect_type'] != 'NV': errors.append('Invalid defect type: ' + sub.attrib['defect_type']) if gh.policy_exists(sub.attrib['policy_id']): errors.append('Existing Policy: ' + sub.attrib['policy_id']) # if sub.attrib['policy_id'].endswith('T'): # errors.append('Terminate policy ' + sub.attrib['policy_id'] + ' is not allowed for this submission type') branch_name = 'NEW-' + ','.join(str(s.attrib['policy_id']) for s in submissions) return branch_name, errors since both GIRL4876S and BOY4876T has 4876 on them. The function should append error. -
v-if and v-else directives to show created and updated dates
I have a django model which stores created and updated date on my front end i have a header called Date in my vue headers i am displaying the created date but i need to display the updated date under the same header when an object is updated. i have same date called row.updated_date_formatted if this is none i need to display created_date else i need to display updated date <template slot="row" slot-scope="{ row, index }"> <td v-text="row.created_date_formatted"> </td> </template> -
Save uploaded InMemoryUploadedFile as tempfile to disk in Django
I'm saving a POST uploaded file to disk by using a technique described here: How to copy InMemoryUploadedFile object to disk from django.core.files.storage import default_storage from django.core.files.base import ContentFile from django.conf import settings data = request.FILES['image'] path = default_storage.save('tmp/%s' % filename, ContentFile(data.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) The file does get uploaded and stored at the specified location. However, the content is garbled. It's an image - and when I look at the stored file, I see, the characters are not the same and the image file is damaged. The filesize, however, is the same as the original. I guess, I need to do some conversion before saving the file, but how/which...? -
HttpError 500 from Keycloak when fetching userinfo with django allauth
After upgrading keycloak to 20.0.0 I am unable to login with keycloak using django-allauth because of an error (http 500) when calling the userinfo endpoint. By checking the logs om my local keycloak instance I see that it is caused by a nullpointer exception, as seen below. Anyone experiencing the same after updating? 2022-11-03 08:44:42,555 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (executor-thread-30) Uncaught server error: java.lang.NullPointerException at org.jboss.resteasy.plugins.server.BaseHttpRequest.getFormParameters(BaseHttpRequest.java:53) at org.jboss.resteasy.plugins.server.BaseHttpRequest.getDecodedFormParameters(BaseHttpRequest.java:74) at jdk.internal.reflect.GeneratedMethodAccessor176.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.jboss.resteasy.core.ContextParameterInjector$GenericDelegatingProxy.invoke(ContextParameterInjector.java:166) at com.sun.proxy.$Proxy45.getDecodedFormParameters(Unknown Source) at org.keycloak.protocol.oidc.endpoints.UserInfoEndpoint.issueUserInfoPost(UserInfoEndpoint.java:146) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130) at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:660) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:524) at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:474) at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364) at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:476) at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:434) at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:192) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:152) at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:183) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:141) at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:32) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261) at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161) at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364) at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247) at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73) at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:151) at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:82) at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.handle(VertxRequestHandler.java:42) at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284) at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:173) at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:140) at io.quarkus.vertx.http.runtime.StaticResourcesRecorder$2.handle(StaticResourcesRecorder.java:84) at io.quarkus.vertx.http.runtime.StaticResourcesRecorder$2.handle(StaticResourcesRecorder.java:71) at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284) at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:173) at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:140) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$6.handle(VertxHttpRecorder.java:430) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$6.handle(VertxHttpRecorder.java:408) at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284) at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:173) at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:140) at org.keycloak.quarkus.runtime.integration.web.QuarkusRequestFilter.lambda$createBlockingHandler$0(QuarkusRequestFilter.java:82) at io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:564) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29) at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:829) -
Update a value of a column through django orm
I'm trying to update a column value through django model, backed legacy db is postgressql, the column in db is defined as: "numbers integer[] NOT NULL" in my django application's models.py i have the column as : "numbers = ArrayField(models.IntegerField())" in the code i'm trying to update as below: user = class_name.objects.using('default').get(id=14) user.numbers = number # here value number is a list user.save() this part of code is inside try and exception block i'm not seeing any errors but the save() part is not executing i.e code stops there not going to next lines -
How can modify request.GET in django REST framework
i have a request param as: <WSGIRequest: GET 'dashboard/auth/complete/activities-update/?session_key=abbccddeeff&state=GKW9z7ET AR&response_type=code&scope=update&show_login=true'> I want to remove the session_key from the request.SO I tried the following code: request.GET._mutable = True # to make it editable request.GET.pop("session_key") request.GET._mutable = False but request is still same I need request as: <WSGIRequest: GET 'dashboard/auth/complete/activities-update/?state=GKW9z7ET AR&response_type=code&scope=update&show_login=true'> -
CSRF Origin check failed Django/Vue.JS
I am currently making a web app that uses Vue.JS for the frontend part and Django for the backend. I'm using django-rest-framework to communicate between the client and the server. I would like to specify that everything works fine when using Postman for testing my requests When trying to login or register (those are only the two features I have implemented yet) The server sends back the following response: "CSRF Failed: Origin checking failed - http://localhost:8080 does not match any trusted origins." Status: 403 The csrftoken cookie is there and I made sure it's sent Here are some details on my setup Requests are sent using Axios. In main.js I overrode the following axios.defaults axios.defaults.baseURL = 'http://localhost:8000'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; And the login request is sent in this method in a Pinia user store: async login(email, password) { try { let response = await axios.post('authentication/login/', {email: email, password: password}); this.setUserData(response.data.id, response.data.email); } catch(error) { console.log(error); } }, Server side: My User view is written the following way: def UserAuthenticationView(APIView): serializer_class = UserSerializer def get(self, request): #retrieve currently logged-in user pass def post(self, request): #register new user in database pass @api_view(['POST]) def login(request): # decode … -
Django Admin Many to Many as listbox in list_display
How I can make MM field like listbox in Admin (row will change heigh dynamically) I want to see: like it in Sharepoint. -
How do i deploy Django Application with no code
Would like to deploy Django Application as binary or no source code on the server. We are planning to do it as Docker compose and trying to deploy only the generated class files into server. Is there a way to deploy only the binary files for the same. Right now on the server its copying python files and source code along with docker image. How do we secure on the same. -
Django data type for str with int or text with number input
Good Day! what data type does django use for inputs like str+int or text+num for example, POST request in JSON format: [ { "PostNum": POS01 }, { "PostNum": POS003 } ] Thanks -
failed to delete the start_date with django queryset
I am trying to delete the data between start_date and_date using django. Here is the code I am using: Porfolio.objects.filter(portfolio_id=portfolio_id, date__gte=start_date, date__lte=end_date).delete() Problem: whatever the start and end_date I am using, the start_date is not deleted while all the period afterward is deleted until end_date. and I am sure that in all cases I tested I have data in the start_date to delete. Could not figure out why I am getting this behaviour. -
ERROR: Cannot install pytest-cov==2.12.1 and pytest<4.6 because these package versions have conflicting dependencies
I want to install a project, before that i must install the requirement.txt, but there's a problem here ERROR: Cannot install -r requirements.txt (line 15) and idna==3.1 because these package versions have conflicting dependencies. The conflict is caused by: The user requested idna==3.1 requests 2.25.1 depends on idna<3 and >=2.5 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts requirement.txt: certifi==2020.12.5 chardet==4.0.0 defusedxml==0.7.1 Django==3.2 django-mathfilters==1.0.0 idna==3.1 oauthlib==3.1.0 Pillow==8.2.0 psycopg2==2.8.6 psycopg2-binary==2.8.6 PyJWT==2.0.1 python3-openid==3.2.0 pytz==2021.1 reportlab==3.5.67 requests==2.25.1 requests-oauthlib==1.3.0 six==1.15.0 social-auth-app-django==4.0.0 social-auth-core==4.1.0 urllib3==1.26.4 i dont know how to solve this problem :/ -
Vue function to display formatted date
I have a django model which has two datetime fields which are created and updated which needs to be displayed on front end when object is created and display the updated date when object is updated how can i achieve this on vue i have added just created date but it needs to be formated and should display updated date when object is updated. <div class="table-wrapper"> <vue-table type="document" :headers="headers" :items="items" :processing="is_processing" :ordering="ordering" :pagination="pagination" @update:pagination="updatePagination($event)" @update:ordering="updateOrdering($event)" > <template slot="row" slot-scope="{ row, index }"> <td v-text="row.created"></td> </template> </vue-table> </div> {% endblock %} {% block footer_scripts %} {{ urlParams|json_script:"url-params-data" }} <script type="text/javascript"> </script> <script type="text/javascript"> var vm = new Vue({ components: { Multiselect: window.VueMultiselect.default, VueTable: window.VueTable }, mixins: [ window.paginatedDataMixin ], el: '#wrapper', delimiters: ["<%","%>"], data: { api_url: list_api_url, headers: [ { 'name': 'Date', 'field': 'created', 'width': '20%' }], filtering: { }, }, mounted: function() { this.loadData('search'); }, methods: { } }); </script> {% endblock %} v-text="row.created" shows created date in format 2022-11-02T23:56:47.698434 i need to show 02 Nov,2022 for the Date header and for the same date header v-text="row.updated" will show updated date if object is updated -
django_currentuser alternatives or how to get current user in Models.py
I have 2 Models in my django models.py. I need to get data from model2 to model1, but I don't need to store it anywhere in the model1 fields. I found @property of django and implemented that. My issue was that I need to get who the user is using request.user, which is not possible in models.py So how can I access user in django models? Is there any other packages? or is there any inbuilt django way which I haven't thought about? I searched and got a package called django-currentuser , unfortunately i'm using Django 4 which doesn't have a support. -
REACT + DJANGO - CORS Errors After Login - CORS header ‘Access-Control-Allow-Origin’ missing
We have a React + Django application on GCP App Engine instances and we are facing a CORS error when fetching data through our REST API. We have already installed and configured the CORS package for the Django Rest Framework in our django application: ` ALLOWED_HOSTS = [ 'xxxxxxxxxxxx.appspot.com', 'yyyyyyyyyyyy.appspot.com', ] CORS_ALLOWED_ORIGINS=[ 'http://localhost:3000', 'https://xxxxxxxxxxxx.appspot.com', 'https://yyyyyyyyyyyy.appspot.com', ] CORS_ALLOW_CREDENTIALS=True ` The preflight request is successful as well as the application login, which performs an async request to our backend: access-control-allow-origin: https://xxxxxxxxxxxxxxxxxxxxx.appspot.com access-control-allow-headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with access-control-allow-methods: DELETE, GET, OPTIONS, PATCH, POST, PUT access-control-max-age: 86400 The correct URL is passed through the allow-origins header. The actual GET request is then blocked with a 400 response code from the browser and the following error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxx.appspot.com/api/entities?page_size=10. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400. The strangest thing is that we are able to login into the application and that uses an async request to the same domain, only after we login does this error appear. We have gone through several stackoverflow pages and different configurations (Eg. Using Regex in he allow ORIGINS configuration) but nothing … -
Connect to Postgres on Heroku with Django properly
I'm new to Django and Heroku. I'm confused about how I should connect to Postgres database on Heroku from my Django app considering the fact that all the credentials and DATABASE_URL could be changed. Firstly, to connect to my Postgres on Heroku I started by using environment variables and hardcoded them in my Heroku dashboard. Then I figured out that it is a bad practice because the values can be changed. I checked this guide by Heroku where they recommend adding this to settings: DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) With that, I added my DATABASE_URL to my .env file - because otherwise, the URL will be empty. Now I can get all the correct database credentials in my DATABASE that are the same as in my dashboard. So halfway there. Then I deleted all the hardcoded environment variables from my Heroku dashboard. Then when I tried to heroku run python src/manage.py migrate -a myapp data, I received an error: django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? As I understand it, the problem is that it can't connect to the database (maybe because I deleted … -
django-admin startproject myworld cannot work on mac
I am learning django but stuck at beginning of start project as below in terminal: kevinlin@kevindeMacBook-Pro ~ % django-admin startproject myworld kevinlin@kevindeMacBook-Pro ~ % I have installed python but version 2.7 shown on terminal, 3.10 version shown on python shell. I am wondering if the issue is caused by running version 2.7 on terminal ? kevinlin@kevindeMacBook-Pro ~ % python --version Python 2.7.18 Python 3.10.7 (v3.10.7:6cc6b13308, Sep 5 2022, 14:02:52) I have checked all of pip/django/virtlenv have been installed. I have tried to search solutions on google and here but cannot solve the issue. -
Combine today date and input type=time in DateTimeField in Django
Here I am using Django 3.0 and Python 3.7 Here I am getting time from django template and i need to combine this time and today date as save it in database as DateTimeField Here is my models.py class WorkTime(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField() total_time = models.TimeField(blank=True, null=True) Here is my views.py class AddWorkTimeView(View): def get(self, request): client = request.user.client return render(request,'core/work_time_form.django.html') def post(self, request): c = request.user.client start_time = request.POST.get('start_time') # print start_time - 11:15 end_time = request.POST.get('end_time') # print end_time - 14:15 WorkTime.objects.create(client=c,start_time=start_time,end_time=end_time) return redirect('work_times') Here is my work_time_form.django.html <form class="form-horizontal" method="post"> {% csrf_token %} <div class="row"> <div class="span10 offset1"> <div class="control-group"> <label class="control-label pull-left">Start Time</label> <input type="time" step="900" class="input_box" name="start_time"> </div> <div class="control-group"> <label class="control-label pull-left">End Time</label> <input type="time" step="900" class="input_box" name="end_time"> </div> <div id="form-buttons-container" class="form-actions"> <div class="controls"> <input type="submit" class="btn btn-inverse" value="Save"> </div> </div> </div> </div> </form> Here what format i want it to save to my datebase Example: 2020-11-03 10:30:00 (here date is today date) And also calculate the time difference between start_time and end_time in minutes and save it to total_time field To achieve this what changes i need to do to my code Please help me to solve … -
How to make the data of table kept even after containers deleted?
My purpose is to keep data even after deleting and rebuilding containers. More specifically, I want to keep data even after putting like "docker-comand down" or "docker-comand up -d --build". My environment is Docker Django PostgreSQL Nginx Gunicorn docker-compose.prod.yml version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn ecap.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:13.0-alpine volumes: - db_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - ./static_volume:/home/app/web/staticfiles - ./media_volume:/home/app/web/mediafiles ports: - 80 depends_on: - web volumes: db_data: static_volume: media_volume: I assume that the problems is how to write volumes in the yml file. Although I followed the shown way, I cannot keep the data.