Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show in Django Admin Icons based on model value
I need to show an Icon in Django Admin based on the value. For example: If Model Field weather has value sun then show icon sun (png or webfont) Is this possible? -
Django throws 500 when debug is False in Production
I am unable to understand why Django 3 fails when I run with DEBUG=False. Also there seems to be a problem with urls: www.domain.com/ -> Does not work www.domain.com/en/ -> No problem The logs seem to mention a million problems but I don't understand what the initial problem is, so I am looking for help: Exception while resolving variable 'self' in template '404.html'. Traceback (most recent call last): File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 585, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) '^django-admin/'>], [<URLResolver <module 'wagtail.admin.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py'> (None:None) '^admin/'>], [<URLResolver <module 'wagtail.documents.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/documents/urls.py'> (None:None) '^documents/'>], [<URLPattern '^i18n/$' [name='set_language']>], [<URLPattern '^sitemap\.xml$'>], [<URLResolver <URLResolver list> (None:None) 'bg/'>]], 'path': ''} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'self' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): … -
django: request.POST.get() return NoneType
I am work from data acquired from an html form. I am currently failing to capture the data on the server side. Every input returns "NoneType" on the server. I feel like I tried everything that I could find around here, notably changing id for name in the html form, nothing works. here is what I got so far: views.py: def quadriatransport_simulationView(request): return render(request, "simulation.html") @csrf_exempt def compute(request): destination = request.POST.get("destination") nombre_de_palettes = request.POST.get("nombre_de_palettes") poids_par_palette = request.POST.get("poids_par_palette") Optimisation_prix = request.POST.get("Optimisation_prix") Optimisation_delai = request.POST.get("Optimisation_delai") result = {"destination":destination} print(result) return JsonResponse({"operation_result": result}) results returns a dictionnary where destination is None now here is what I have been able to do on the webpage <form method="POST"> {% csrf_token %} <label><h3>Input variables to calculate EOQ:</h3></label> <br> <br> <span>Destination (departement) <input type="text" id="destination"> <br> <br> <span>Nombre de palettes <input type="text" id="nombre_de_palettes"> <br> <br> <span>Poids par palette <input type="text" id="poids_par_palette"> <br> <br> <span>Optimiser prix <input type="checkbox" id="Optimisation_prix"> <br> <br> <span>Optimiser délai de livraion <input type="checkbox" id="Optimisation_delai"> <br> <input id="ajax-call" type="submit" value="Simuler"> </form> <p id="ajax"></p> and here is my js script inside of the webpage <script> document.querySelector("#ajax-call").addEventListener("click", event => { event.preventDefault(); let formData = new FormData(); formData.append('estination', document.querySelector("#destination").value); formData.append('nombre_de_palettes', document.querySelector("#nombre_de_palettes").value); formData.append('poids_par_palette', document.querySelector("#poids_par_palette").value); formData.append('Optimisation_prix', document.querySelector("#Optimisation_prix").value); formData.append('Optimisation_delai', document.querySelector("#Optimisation_delai").value); let … -
Using Outlook SMTP server to send email through a contact form but unable to send as I need the server to be able to accept multiple "From" addresses
Currently using Django as the chosen framework for my project and I have implemented a contact form and my main goal is for users to complete the contact form and the admin of the site (me) get an email, which shows me the details of their enquiry. I am trying to use the Outlook SMTP server and these are my current settings in settings.py: EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '<my_emailAddress>' EMAIL_HOST_PASSWORD = os.environ.get('OUTLOOK_PASSWORD') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = '<my_emailAddress>' However, whenever I complete the form and send the request to the server I am receiving the following error code: (554, b'5.2.252 SendAsDenied; <my_emailAddress> not allowed to send as <inputtedForm_emailAddress>; STOREDRV.Submission.Exception: SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message. I am looking for some help surround this issue - it would be greatly appreciated. Thanks in advance, Rhys -
You may install a binary package by installing 'psycopg2-binary' from PyPI [WINDOWS]
Hi guys I'm getting this error and I don't know how to fix this the command that I run in my console is the following: pip install -r ..\requirements\local.txt It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 I don't know how to fix this I really need help -
Django Python - import error: No module named 'views'
I am trying to run a webserver in Django using this tutorial series: https://www.youtube.com/watch?v=Rpi0Ne1nMdk&list=PLPSM8rIid1a3TkwEmHyDALNuHhqiUiU5A I get an error when I try and import the script 'landing.views' inside urls.py, here is the error in it's entirety: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'views' Here is the code that generates the error seen above in urls.py: from django.urls import path from landing.views import Index urlpatterns = [ path('', Index.as_view(), name='index'), ] I have also tried looking at posts that other users have … -
Incorrect response from .get_or_create function in Django
I have been trying to understand why the .get_or_create function I'm using isn't working. It's supposed to find the object in the DB with matching parameters and create a new one if none are found. When running this, it always says that there are not matching objects and the tuple return True every time hence always creating a new object (a duplicate). This causes the Except statement to run every time as well. Here is my function: for desktop in desktops: try: clean_location = serialized_location_information(desktop) clean_machine = serialize_machine_information(desktop) location_name, location_created = Location.objects.get_or_create( latitude=clean_location["latitude"], longitude=clean_location["longitude"], provider=clean_machine["provider"], defaults={ "country": clean_location["country"], "state": clean_location["state"], "city": clean_location["city"], "street_address": clean_location["street_address"], "postal_code": clean_location["postal_code"], "name": clean_location["name"], "status": clean_location["status"], } ) if l_created: logger.info(f"New Location was created successfully") except Exception as ex: logger.error(f"Could not get or create location: {ex}") location = None pass Here is my model: class Location(models.Model): class Meta: unique_together = ['latitude','longitude','provider'] latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) country = models.CharField(max_length=100, blank=True) state = models.CharField(max_length=25, blank=True) city = models.CharField(max_length=250, blank=True) street_address = models.CharField(max_length=250, blank=True) postal_code = models.CharField(max_length=100, blank=True) name = models.TextField(blank=True) status = models.PositiveSmallIntegerField(default=10, choices=LocationStatus.CHOICES) provider = models.ForeignKey(Provider, on_delete=models.CASCADE, default= '') def __str__(self): return f"{self.name}" -
One dictionary key is overriding the others. Dictionary is being accessed at definition
I am experiencing an odd issue where 21 of the dictionary keys work correctly. However, when this specific 22nd one is added, things stop working correctly. The dictionary is accessed when being defined as well as being immediately accessed always with the 22nd key (whether it is correct or not). The dictionary is inside of a Django function view that aims to edit Product forms and save them to a quotation. Below is the template and url as well as function view. {% url 'quote:edit_line_item' pk=quote.pk product_name=item.product_name line_item=item.pk%} re_path(r'quote/(?P<pk>\d+)/edit-line-item/(?P<product_name>.+)/(?P<line_item>\d+)/$', views.add_to_quote, name = 'edit_line_item') def add_to_quote(request,*args,**kwargs): pk = kwargs['pk'] if kwargs.get('line_item') == None: product_template_form = 'quote/product_template_form.html' form_dict = { 'FilterProduct':FilterProductForm(request.POST,initial={'quote':pk},user=request.user), 'Product1': Product1Form(request.POST,initial={'quote':pk}, 'Product2': Product2Form(request.POST,initial={'quote':pk}, ... 'Product21':Product21Form(request.POST,initial={'quote':pk}, } form = form_dict[request.POST['product_name']] else: obj = get_object_or_404(model_dict[kwargs['product_name']], pk=kwargs['line_item']) print(f"object {obj}") print(kwargs) product_template_form = 'quote/edit_product_form.html' print("here") form_dict = { "FilterProduct": FilterProductForm(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj,user=request.user), # "FilterProduct": print("why am I printing?"), 'Product1': Product1Form(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj), 'Product2': Product2Form(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj), ... 'Product21': Product21Form(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj), } print("there") print(kwargs.get('product_name')) form = form_dict[str(kwargs.get('product_name'))] ...continues from here with logic return render(request, product_template_form, {'form':form}) Since the line_item kwarg is provided the else statement of the function … -
Network request failed error in React native using django api
i am trying to get the simple data from the api that i created in django tried many instructions but could not resolve this error with api Here is my react native code export default function App() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const handleSubmit = () => { ##tried:127.0.0.1 also computer ip then localhost## return fetch("http://localhost:8000/demo/customer/") .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); return responseJson; }) .catch((error) => { console.error(error); }); }; return ( <View style={styles.container}> <View style={styles.login}> <Text>Login</Text> <TextInput placeholder="Email" keyboardType="email-address" style={styles.inp} onChangeText={(text) => setEmail(text)} /> <TextInput placeholder="password" style={styles.inp} onChangeText={(text) => setPassword(text)} /> <Button title="login" color="orange" onPress={handleSubmit} /> </View> <View> <Text> {email}-{password} </Text> </View> </View> ); } this is the error that i get most of my time and sometimes it gives null when using apisauce error Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue django setting INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'corsheaders', 'demo' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST … -
Django3 Nginx Gunicorn Supervisor not logging error
Im trying to catch/ log django errors (500) in my prod environment. However all the log files doesn't contain any traceback. To test if it works I have a view in django with: raise Exception("test exception to test the logging") It doesn't matter how I change the configuration - it doesn't log it. Current config: Django (SETTINGS.py) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs/django.log'), }, 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'), }, }, } prod_gunicorn.bash #!/bin/bash NAME="RPG-DJANGO" DJANGODIR=/home/my_user/rpg-django SOCKFILE=/home/my_user/prod_env/run/gunicorn.sock USER=my_user GROUP=sudo NUM_WORKERS=4 DJANGO_SETTINGS_MODULE=rpg.settings DJANGO_WSGI_MODULE=rpg.wsgi cd $DJANGODIR source /home/my_user/prod_env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --access-logfile /home/my_user/rpg-django/logs/gun_access.log \ --error-logfile /home/my_user/rpg-django/logs/gun_error.log \ --capture-output \ --log-level=debug /etc/supervisor/conf.d/rpg-django.conf [program:RPG-DJANGO] command=/home/my_user/rpg-django/prod_gunicorn.bash user=root stdout_logfile=/home/my_user/rpg-django/logs/prod_gunicorn.log stderr_logfile =/home/my_user/rpg-django/logs/prod_gunicorn.log redirect_stderr=true autostart=true autorestart=true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 /etc/nginx/sites-available/rpg-django.conf server { server_name rpg.skin-society.com; access_log /home/my_user/rpg-django/logs/nginx-access.log; error_log /home/my_user/rpg-django/logs/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location ^~ /static { root /home/my_user/rpg-django; } location / { include proxy_params; proxy_pass http://unix:/home/my_user/prod_env/run/gunicorn.sock; } } -
Get the value of an IntegerChoices value in Django?
Suppose I have the following Django (3.2) code: class AType(models.IntegerChoices): ZERO = 0, 'Zero' ONE = 1, 'One' TWO = 2, 'Two' class A(models.Model): a_type = models.IntegerField(choices=AType.choices) Also, that I have a Django template with a variable a: {{a.a_type}} is a number. How do I get "Zero" (the string associated with a_type)? -
How to show data from views on chartjs in django?
I am making an app on Django at the moment and I don't know how to get the data from views to the chart properly. Here's my code for views: def data(request): nysestuff = nyse.objects.all() riskappstuff = riskapp.objects.all() feargreedstuff = feargreed.objects.all() putcallstuff = putcall.objects.all() feargreednm = [float(feargreedstuff[i].Fear_Greed/100) for i in range(len(feargreedstuff))] outputdata = [(float(nysestuff[i].NYSE_Up_Vol) + feargreednm[i] + float(putcallstuff[i].Put_Call) + float(riskappstuff[i].Risk_App))/4 for i in range(len(feargreedstuff))] yesno = [outputdata[i] > 50 for i in range(len(outputdata))] labels = [str(nysestuff[i].Daily_NYSE) for i in range(len(nysestuff))] context= { 'outputdata': outputdata, 'labels': labels, 'yesno': yesno } return render(request, 'newapp/index.html', context=context) I want to get outputdata and labels into the chart. Here's my code for the html: <!DOCTYPE html> <h1>Trial page</h1> <body>{{labels}}</body> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!--Chart js--> <title>Sample Graph</title> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script> </head> <canvas id="myChart" width="200" height="100"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: {{labels}}, datasets: [{ label: '# of Votes', data: {{outputdata}}, // backgroundColor: [ // 'rgba(255, 99, 132, 0.2)', // 'rgba(54, 162, 235, 0.2)', // 'rgba(255, 206, 86, 0.2)', // 'rgba(75, 192, 192, 0.2)', // 'rgba(153, 102, 255, 0.2)', // 'rgba(255, 159, 64, 0.2)' // ], … -
Cleaned_data coming as empty data in django form?
I have a form field and it is a form.JsonField(). When I am submitting data,and logging the data received in the cleaned_data, it always outputs the empty data. Reason being, when I log the request.POST, I can see the incoming data is coming as list e.g <Querydict:{"name":["test",'']. When I pass request.POST to my form, I always get self.cleaned_data.get("name") as empty. It always gives me the last item from the list value. Possible solution in my mind, is to manipulate the request.POST data before sending to form and then everything will work fine. e.g update_request = request.POST.copy() updated_request['name'] = updated_request.getlist('name')[0] Now, I can pass this to my form e.g form = MyForm(updated_request,instance=self.get_sample()) Point is this seems more like a hack compared to a clean solution. Is there a more efficient way to do this instead of hacking all this in the views. -
How can I solve this DJANGO_SETTINGS_MODULE or call settings.configure() problem?
I'm currently learning to use Django with a Udemy course that is pretty outdated but since it was the best rated I thought I'd give it a try. After covered how to set the models.py file they showed how to use Faker to populate the admin section with fake data. The problem arises when trying to run this populate file, this is what shows up: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This is my populate file from faker import Faker from first_app.models import AccessRecord, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() # FAKE POP SCRIPT fakegen = Faker() topics = ['Search', 'Social', 'Market', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get the topic for the entry top = add_topic() # create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create( topic=top, url=fake_url, name=fake_name)[0] # create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create( name=webpg, date=fake_date)[0] if __name__ == '__main__': print('populating script..') populate(20) … -
pg_config executable not found. WINDOWS
I'm trying to pip install my requirements with this command": pip install -r ..\requirements\local.txt looks like everything is going good but then I run into this error -
MultiValueDictKeyError at /sendEmail/ 'file'
I'm trying to send an attachment via e-mail in my project with Django. But I am getting such an error. I know this question asked before but they're almost 10 years old and some of them didn't even answered. So I need help 😅. Thanks in Advance.. My codes are as follows: Django=3.2.7 django-crispy-forms==1.12.0 views.py # send email def sendMail(request): message = request.POST.get("message", "") subject = request.POST.get("subject", "") receivers = request.POST.get("email", "") email = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [receivers]) email.content_subtype = "html" file = request.FILES["file"] #file = request.POST.get("file") email.attach(file.name, file.read(), file.content_type) email.send() return HttpResponse(f"Sent to {receivers}") forms.py class EmailForm(forms.Form): # receivers email email = forms.EmailField() subject = forms.CharField(max_length=100) file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) message = forms.CharField(widget = forms.Textarea) models.py # for sending email class EmailReportModel(models.Model): """ this model created just for email foreignKey """ #receiver_emails = models.ForeignKey(BolgeMailListeleri, on_delete=models.CASCADE, related_name = "receiver_emails") receiver_emails = models.ManyToManyField(BolgeMailListeleri) subject = models.CharField(max_length=255, default="") message = models.TextField() upload = models.FileField(upload_to='uploads', null=True, blank=True) #upload = models.Field() #image1 = forms.Field(label='sample photo', widget = forms.FileInput, required = True ) SendEmail.html {% load crispy_forms_tags %} <div class="main"> <!-- Create a Form --> <form method="post" enctype="multipart/form-data"> <!-- Security token by Django --> {% csrf_token %} {{ form|crispy }} <button type="submit">Gönder</button> </form> <button onclick="goBack()" … -
Make a http call in python
I am trying to call the google fit API with python but the example for sessions is not working for me. The example by google GET https://fitness.googleapis.com/fitness/v1/users/me/sessions?activityType=97 HTTP/1.1 Authorization: Bearer [YOUR_ACCESS_TOKEN] Accept: application/json My code @api_view(['GET']) def googleFitView(request): social_token = SocialToken.objects.get(account__user=2) token=social_token.token url_session= "https://fitness.googleapis.com/fitness/v1/users/me/sessions" headers = { "Authorization": "Bearer {}".format(token), "Accept": "application/json" } session_call = requests.post(url_session, headers=headers) return Response(session_call) If I a call to another API of google fit it is working so the authentication is not a problem. I also followed the documentation and the session call does not require a body @api_view(['GET']) def googleFitView(request): social_token = SocialToken.objects.get(account__user=2) token=social_token.token url = "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate" headers = { "Authorization": "Bearer {}".format(token), "Content-Type": "application/json;encoding=utf-8", } body = { "aggregateBy": [{ "dataTypeName": "com.google.activity.segment", }], "startTimeMillis": 1634767200000, "endTimeMillis": 1634853600000 } respo = requests.post(url, data=json.dumps(body), headers=headers) return Response(respo) -
Getting this error '' No Python at 'c:\program files (x86)\python38-32\python.exe' ''
I have an existing django project . I wanted to open that project . But , after activating the virtual environment ,whenever i am trying to run 'python manage.py runserver' I am getting this "No Python at 'c:\program files (x86)\python38-32\python.exe" error in command prompt. I am not getting any solution of this problem . -
django- how to override the django field
I have Django model date field I just want to override the date field with the JavaScript date range picker. JavaScript date range picker is working fine but unable to override the field in the template. html: <div>Netdue Date</div> <div class="row" id='id_row'> <input type="text" name="daterange" value="01/01/2018 - 01/15/2018" /> <!-- {{ form.Netdue_Date}} --> </div> <script> $(function() { $('input[name="daterange"]').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> forms.py class DateInput(forms.DateInput): input_type = "date" def __init__(self, **kwargs): kwargs["format"] = "%Y-%m-%d" super().__init__(**kwargs) class Userform(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['Netdue_Date'].widget.attrs.update( { 'placeholder': 'Netdue_Date', 'name': 'email', 'id': 'Netdue_Date'}) class Meta: model =Userbase fields = '__all__' widgets={ 'Netdue_Date':DateInput(), } -
Django code to read from a file and update to website without refresh
I would like to implement the solution provided at the link below to list a number on my website and have that number change automatically as it reads from the file. The file will be updated with a new number as part of a separate process. Django: Display contents of txt file on the website I would like to ensure that the number in the website changes dynamically without needing a refresh of the browser Thanks in advance community! -
Django rest frameowrk : Prevent one user from deleting/Editing/Viewing other users in ModelViewSet
I was using Django users model for my Django rest framework. For this I used Django's ModelViewSet for my User class. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user But currently from postman when I make the request using the token of one user to view, delete, edit other users http://127.0.0.1:8000/api/users/4/ Its able to edit/delete/view other users. I don't want that to happen and one user can make request on itself only is all I want. This is my apps urls.py urls.py from django.urls import path, include from .views import ArticleViewSet, UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('articles', ArticleViewSet, basename='articles') router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] How can I prevent one user from accessing other users when they make GET/POST/PUT/DELETE request. -
How much HTML and CSS knowledge should I have before learning Django? [closed]
I've completed learning python basic concepts and now I want to learn Django. But I want to know how much HTML and CSS knowledge should I have before approaching in Django. -
Relating data in a Django Model to another model
I have this model. class AuctionListings(models.Model): """ Model for all the listings listed on the site. """ title = models.CharField(max_length=40) description = models.TextField() image_url = models.URLField() current_bid = models.PositiveSmallIntegerField() category = models.CharField(choices=CATEGORIES, max_length=5) date = models.DateField(default=date.today) datetime = models.DateTimeField(default=timezone.now) date_last_updated = models.DateField(auto_now=True) date_added = models.DateField(auto_now_add=True) timestamp_last_updated = models.DateTimeField(auto_now=True) timestamp_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Title:{self.title}, Date Added:{self.date_added}, Category:{self.category}" class Meta: """ Specifies the plural name of the model for the Django Admin Panel. """ verbose_name_plural = "Auction Listings" I want to be able to set the starting bid in Auction Listings when someone creates a new listing. Just like how eBay would do it. I want the bid to also be able to be updated in the bid model. And that if the listing is deleted, the bid on the listing would also be deleted. Because there is no listing. I've tried using a foreign key but then I get this You are trying to add a non-nullable field 'current_bid' to auctionlistings without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) … -
Primary key error logging in Django Admin using MongoDB
first of all, I'm new in MongoDB and this is my first application using it so I know I have lack of documentation reading, but I am trying to find solution to this problem due that the documentation read says that everything might work well with no changes. I have correctly configured the settings file with the MongoDB database and have created my models. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'my database', } } I have created a superuser using the django-admin createsuperuser but when I try to login into the admin panel I get this error. ValueError: Cannot force an update in save() with no primary key. I know that MongoDB doesn't have a Primary Key and Foreign Key system and it's based on JSON-like type objects, but the documentation say that it works well with it so I thought that it was previously ready to run this. Any clue of what is happening? Thank you. -
How to post a Json with a base64 file using python request?
Right now I am programming an API with python, and I have the following problem: I have to POST the following JSON to an url: prescription = { "Name": “file_name", # This is a string "Body" : "xxx",# (File in base64 format) "ParentId" : "xxxxxxxxxxxxxxxxxx", # This is a string "ContentType" : "xxxxx/xxx" # This is a string } But when I try to do the following request: requests.post(url, prescription) I am getting the following error: TypeError: Object of type bytes is not JSON serializable How can I make a request for posting that JSON? Is it even possible? Thanks for your help.