Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form is not updating the user database
I want to update User database using forms.When I trying to update it remains same the database and not update. So to perform this task ? forms.py from django import forms from django.contrib.auth.models import User class updateform(forms.ModelForm): class Meta: model=User fields="__all__" views.py from django.contrib.auth.models import User from .forms import updateform @permission_required('is_superuser')#only superuser can update the data base def upform(request,id): emp=User.objects.get(id=id) if request.method=='POST': frm=updateform(request.POST,instance=emp) if frm.is_valid(): frm.save() return redirect('/') else: frm=updateform(instance=emp) return render(request,'examp.html',{'frm':frm}) examp.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static '/examp.css' %}"> <style> td,th{ border:1px solid; text-align:center; padding:10px; } </style> </head> <body> {% include 'include/header.html' %} <form action="/" method="POST"> {% csrf_token %} {{ frm.as_p }} <input type="submit" value="Submit"> </form> </body> </html> How to update the database using this given form. -
How to automatically create data fields in other apps
I want to assign some location to an item and also save it to other app. So, when I make changes to it from one app, the other gets updated too. location.py: class ManageLocation(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) zone = models.ForeignKey(Zone, on_delete=models.CASCADE, default='1') section = models.ForeignKey(Section, on_delete=models.CASCADE, default='1') level = models.ForeignKey(Level, on_delete=models.CASCADE, default='1') where the referenced keys are seperate classes with name and description. ***mainpurchases:*** class MainPurchases(models.Model): METHOD_A = 'CASH' METHOD_B = 'CREDIT' PAYMENT_METHODS = [ (METHOD_A, 'CASH'), (METHOD_B, 'CREDIT'), ] product = models.ForeignKey(Item, on_delete=models.PROTECT) #assign-warehouse #assign-level #assign-zone #assign-section quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) outlet = models.ForeignKey(Outlet, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.CharField(max_length=6, choices=PAYMENT_METHODS, default=METHOD_A) This is where I want to assign it and save it in managelocations. better approaches are appreciated. -
HandleChange function is not working in reactjs .All the null values from initial state is being posted on django rest framework
//something is not working here idk what.I tried changing e.target.id to e.target.name .That too didnt work. Image.js import axios from 'axios'; class Image extends React.Component { constructor(props){ super(props); this.state = { floor_no:null, distance:null, area:null, no_of_rooms:null, price:null, images: null }; this.handleChange=this.handleChange.bind(this); this.handleImageChange=this.handleImageChange.bind(this); } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; handleImageChange = (e) => { this.setState({ images:e.target.files[0] }) }; handleSubmit = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); form_data.append('floor_no',this.state.floor_no); form_data.append('distance',this.state.distance); form_data.append('area',this.state.area); form_data.append('no_of_rooms',this.state.no_of_rooms); form_data.append('price',this.state.price); form_data.append('images',this.state.images,this.state.images); let url = 'http://localhost:8000/'; axios.post(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; render() { return ( <div className="App"> <form onSubmit={this.handleSubmit}> <p> <input type="number" id='floor_no' onChange={this.handleChange} value={this.state.floor_no} required/> </p> <p> <input type="number" id='distance' value={this.state.distance} onChange={this.handleChange} required/> </p> <p> <input type="number" name='area' value={this.state.area} onChange={this.handleChange} required/> </p> <p> <input type="number" id='no_of_rooms' value={this.state.no_of_rooms} onChange={this.handleChange} required/> </p> <p> <input type="number" id='price' value={this.state.price} onChange={this.handleChange} required/> </p> <p> <input type="file" id='images' accept="image/png, image/jpeg" onChange={this.handleImageChange} required/> </p> <input type="submit"/> </form> </div> ); } } export default Image; models.py from django.db import models # Create your models here. class RenterInfo(models.Model): username= models.CharField(max_length=100) password=models.CharField(max_length=50) def __str__(self): return self.username def upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class RentDetails(models.Model): property_type=models.CharField(max_length=10) floor_no=models.IntegerField(null=True) distance=models.IntegerField(null=True) location=models.CharField(max_length=20) images=models.ImageField(upload_to='post_images',null=True) area=models.IntegerField(null=True) … -
How to add user code to web service. I want to enable users to write and embed algorithms in my site
Image Generator WEB Application (2 User Roles) Client (Filled in the data in the fields → Pressed the generate button → Received the image) Creator (Created a new generator → Created user fields → Uploaded the template → Wrote a data handler from the fields → Posted the generator to the network) Question: Implementation of the "Wrote data handler" step. User "Creator" has skills in graphic design programs. Does he know what programming is? Maybe he knows what programming is How to get algorithms from the user? Maybe there are ready-made solutions or examples. Need any information Thank you! I thought to embed No-code, low-code or python. The only example that I know of is a chat bot constructor without code. -
Django: UpdateView not showing the correct BooleanField value in Template
I have below Django Project developed with Generic Class Based View. models.py from datetime import datetime from django.urls import reverse class Product(models.Model): prodName = models.CharField(max_length=50, default=None, unique=True) def __str__(self): return self.prodName class Shipment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cost = models.IntegerField(max_length=4) orderDate = models.DateTimeField(default=datetime.now, editable=False) quantity = models.IntegerField(max_length=4) receieved = models.BooleanField() def __str__(self): return f'{self.product}: {self.orderDate} views.py from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView, DeleteView, ListView from .models import Product, Shipment # Create your views here. class ShipmentListView(ListView): model = Shipment fields = '__all__' class ProductCreateView(CreateView): model= Product fields = ['prodName'] success_url= reverse_lazy('modalform:shipDetail') class ShipmentCreateView(CreateView): model = Shipment fields = ('product', 'cost', 'quantity', 'receieved') success_url= reverse_lazy('modalform:shipDetail') class ShipmentUpdateView(UpdateView): model= Shipment # template_name: str= 'modal_form/shipment_update.html' fields = ('product', 'cost', 'quantity', 'receieved') success_url= reverse_lazy('modalform:shipDetail') class ShipmentDeleteView(DeleteView): model = Shipment success_url= reverse_lazy('modalform:shipDetail') shipment_form.html {% block content %} <div class="border rounded-1 p-4 d-flex flex-column"> {% if not form.instance.pk %} <h3>Create Shipment</h3> {% else %} <h3>Update Shipment</h3> {% endif %} <hr> <form action="" method="post"> <label class="form-check-label" for="product"> Product </label> <select class="form-control" name="product" id="product"> {% for id, choice in form.product.field.choices %} <option value="{{ id }}" {% if form.instance.pk and choice|stringformat:'s' == shipment.product|stringformat:'s'%} selected {% endif %} > {{ choice }} </option> {% endfor %} </select> … -
Django template extension; django.template.exceptions.TemplateSyntaxError: Invalid block tag when trying to load i18n from a base template
I have a base.html template file for Django (4.1.2) as: <!DOCTYPE html> <html lang="en"> {% load static %} {% load i18n %} <head> <meta charset="utf-8"> {% block title %} <title>My Title</title> {% endblock %} </head> <body> {% block content %} {% endblock content %} </body> </html> and an index.html page, at the same level in the /templates folder of my app, extending the base one, as: {% extends "base.html" %} {% block content %} <h1>My Django project</h1> <ul> <li><a href="/admin">{% trans "Admin" %}</a></li> <li><a href="{% url 'foo' %}">{% trans "Foo" %}</a></li> </ul> {% endblock %} But when I browse the latter page, the server returns the following error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 6: 'trans', expected 'endblock'. Did you forget to register or load this tag? But if I simply add {% load i18n %} at the second line of the index.html, the page loads fine. What is wrong with the loading of the base template in the index.html page? -
Which is the correct bootstrap5 package to load in Django; django-bootstrap5 or django-bootstrap-v5
I am searching for a CSS framework to use with Django and I end up finding boostrap 5. But there seems to be two packages with almost the same name. So, which one is the correct (if any) bootstrap 5 package to load from PyPi in Django: this one: https://pypi.org/project/django-bootstrap5/ or this one: https://pypi.org/project/django-bootstrap-v5/ ? -
FastAPI: OAuth2PasswordBearer: 422 Unprocessable Entity
I'm trying to make an authenticated route using FastAPI and I got 422 Unpossessable Entity error first, I make Dependency to decode token and return user data get_current_user which takes Depends OAuth2PasswordBearer(tokenUrl="token") then I made the end point get_your_articles the route is: @article_route.get("/your-articles") async def get_your_articles(user: dict = Depends(get_current_user), db: Session = Depends(get_db)): if user is None: raise HTTPException( detail="invalid token, login again", status_code=400 ) try: articles = db.query(models.Article).filter(models.Article.auther_id == user.get("id")).all() return { "msg": "success", "data": articles } except SQLAlchemyError as e: return { "Error": e } I use Depends() to decode the token and return the user oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=401, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") user_id: int = payload.get("id") if username is None or user_id is None: raise credentials_exception user = { "username": username, "id": user_id } return user except JWTError as e: raise HTTPException( detail=f" Error in jwt {e}" ) and this is the response: -
what is the need of def __str__(self) in django [duplicate]
i have a question about str(self) function in django during one documentation reading i found models.py class Product(models.Model): product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.CharField(max_length=250, blank=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name what does this def str(self) do -
Django error happened when I installed debug toolbar
everything was working perfectly before until i installed debug toolbar everything was working perfectly befor until i installed django debug toolbar I don’t understand why it is now saying this in the terminal -
Date filter in django
Filter dates that have not passed class Distributor(models.Model): expire_at = models.DateTimeField() I want to get the data that has not expired -
How to detect the logged in user from Keycloak OpenID logout_token on back channel logout?
First let me describe the setup: We have a frontend Angular based product from a different client team (not part of code we can easily modify), and a backend django based API server. The front end logs in to a keycloak server, and when logged in, the backend gets an Auth header with a bearer token in every request. From this, we are able to identify the logged in user as follows (using python-keycloak): ret = keycloak.userinfo(bearer_token) username = ret['preferred_username'] This is obviously very wasteful since it needs an extra network request to keycloak everytime - so we create a django user session instead and use that for session management. Now when it comes to logging out, when the user logs out from the front end, we need to void the django session. I've setup the "Back channel logout URL" on the keycloak realm settings to call some endpoint on the django server. The endpoint gets called on logout, and it gets a "logout_token" value in the arguments. Now I'm not sure how I am supposed to identify which user is logging out based on this token. How can this be done? Thanks in advance... -
I cant use the objects attribute in django project
I created a Projects model class Projects(models.Model): name = models.CharField(max_length=257, unique=True, null=False) description = models.TextField() active_issue_count = models.IntegerField(default=0) # functiona bağlanmalı solved_issue_count = models.IntegerField(default=0) # functiona bağlanmalı is_active = models.BooleanField() start_date = models.DateTimeField() deadline = models.DateTimeField() and I want to use this project model Projects.objects.all() with this code but when I typed in pyCharm shows me this suggestion but while I try to use this model class User(AbstractUser, PermissionsMixin): objects = UserManager() related_group = models.CharField current_project = models.ForeignKey(to='core.Project', related_name='current_project', on_delete=models.PROTECT, null=True) total_worked_project = models.IntegerField(default=0) # functiona bağla active_work_project_count = models.IntegerField(default=0) # functiona bağla REQUIRED_FIELDS = ['email'] ` I can use User.objects.all() without suggestion what should I do anyone can help me ? -
You may need to add an 'await' into your view
I am working on a Django project which fetch status code from websites and save it in the database. I want to make it async otherwise it take too much time and gives an error. So after researching and watching tutorials I came up with this code but it throws the error in title. views.py @sync_to_async async def get_page(session, url, urlMain): async with session.get(url) as response: st_code= await response.status return url, st_code, urlMain @sync_to_async async def create_search(request): form = SearchForm() if request.method == 'POST': name = request.POST['name'] tasks = [] async with aiohttp.ClientSession() as session: for item in data: url = data[item]['url'] urlMain = data[item]['urlMain'] tasks.append(get_page(session, url, urlMain)) results = await asyncio.gather(*tasks) for url, st_code, urlMain in results: if st_code == 200: site_data = SearchResult( url = urlMain, sitename = item, ) site_data.save() context = {'form':form} return render(request, 'index.html', context ) This is the error django shows: Exception Value: The view main.views.SyncToAsync._call_ didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view. -
Read some datetime fields as UTC in Django
I have time zone support as active in my application settings USE_TZ = True So, all my DateTimeFields in my models are transformed from my local time zone to UTC before being saved to database. Question: In some cases, the user enters a datetime field value with day precision only like 2022-10-24 without time part, and I already accepts this format as an input. But in such case, I want to save this value without time zone, so that it will be parsed later without time zone. Why does this cause a problem? If a user enters a value 2022-10-24 and his local time zone is UTC+2, it will be saved in database as 2022-10-23 22:00:00 UTC. Once another user opens the same instance and his local time zone is UTC+1, he will see the value as 2022-10-23 23:00:00 while I want him to see it with the same value that the initial user enters it, so it should be 2022-10-24 00:00:00. Partially Failed Trial: I have tried to handle this in my ModelForm by parsing the entered format, then replacing the time zone info to UTC if it is with day precision. from pytz import UTC datetime_value = datetime_value.astimezone().replace(tzinfo=UTC) … -
Hosting Whatsapp bot Using Pywhatkit with Heroku
I used the Pywhatkit python library to automate sending whatsapp messages, it's working very well in localhost, I realized I have to keep my PC on 24/7 for this to work. So I thought about hosting on Heroku (I don't know if that is possible), so I put it on heroku, but every time I try to run my script in heroku, I get the following error. Heroku Error Traceback (most recent call last): File "/app/test.py", line 2, in <module> import pywhatkit File "/app/.heroku/python/lib/python3.10/site-packages/pywhatkit/__init__.py", line 16, in <module> from pywhatkit.whats import ( File "/app/.heroku/python/lib/python3.10/site-packages/pywhatkit/whats.py", line 7, in <module> import pyautogui as pg File "/app/.heroku/python/lib/python3.10/site-packages/pyautogui/__init__.py", line 249, in <module> import mouseinfo File "/app/.heroku/python/lib/python3.10/site-packages/mouseinfo/__init__.py", line 223, in <module> _display = Display(os.environ['DISPLAY']) File "/app/.heroku/python/lib/python3.10/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'DISPLAY' Code (Files) requirement.txt pywhatkit==5.4 test.py import pywhatkit try: pywhatkit.sendwhatmsg_instantly("+1*********", "Hello from NewYork") print("Successfully Sent!") except: print("An Unexpected Error!") -
The FastCGI process exited unexpectedly while deploying Django project on iis windows server
FAST CGI IS NOT WORKING PROPERLY IN DJANGO DEPLOYMENT ON IIS WINDOW SERVER HTTP Error 500.0 - Internal Server Error C:\Users\satish.pal\AppData\Local\Programs\Python\Python310\python.exe - The FastCGI process exited unexpectedly Most likely causes: •IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. •IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. •IIS was not able to process configuration for the Web site or application. •The authenticated user does not have permission to use this DLL. •The request is mapped to a managed handler but the .NET Extensibility Feature is not installed. Things you can try: •Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account. •Check the event logs to see if any additional information was logged. •Verify the permissions for the DLL. •Install the .NET Extensibility feature if the request is mapped to a managed handler. •Create a tracing rule to track failed requests for … -
Get value of primary key before save
Given the following model I am attempting to use the models ID field (a UUID) in the upload_to path but its defined as None, presumably as it hasn't been generated at that point. If I use a UUID field that isn't defined as the primary key it works OK. How do I get the value of the id field at the point picture_path is ran? # models.py class Foo(models.Model) def picture_path(instance, filename): return 'pictures/{0}/{1}'.format(instance.id, filename) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) picture = models.ImageField(upload_to=picture_path, null=True, blank=True) (I know that django will automagically append random chars to avoid duplicate file names, this is a deliberately simplified example, in the real app need to keep each models files in a seperate folder) -
Django profile picture tries to duplicate when updating profile
When a user updates their profile, if they don't change their profile picture, it tries to resave in a recursive manner. user/ profile_pics/ image1.jpg user/ profile_pics/ image2.jgp models.py def create_path(instance, filename): return os.path.join( str(instance.user.id), 'profile/logo', filename ) class Member(models.Model): profile_pic = models.ImageField(upload_to=create_path, null=True) profile_pic_thumbnail = models.ImageField(upload_to=create_path, null=True) def __str__(self): return str(self.user) def save(self, *args, **kwargs): if not self.make_thumbnail(): # set to a default thumbnail raise Exception('Could not create thumbnail - is the file type valid?') super(Member, self).save(*args, **kwargs) def make_thumbnail(self): image = Image.open(self.profile_pic) image.thumbnail((500, 500), Image.ANTIALIAS) thumb_name, thumb_extension = os.path.splitext(self.profile_pic.name) thumb_extension = thumb_extension.lower() thumb_filename = thumb_name + '_thumb' + thumb_extension if thumb_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' elif thumb_extension == '.gif': FTYPE = 'GIF' elif thumb_extension == '.png': FTYPE = 'PNG' else: return False # Unrecognized file type # Save thumbnail to in-memory file as StringIO temp_thumb = BytesIO() image.save(temp_thumb, FTYPE) temp_thumb.seek(0) # set save=False, otherwise it will run in an infinite loop self.profile_pic_thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=False) temp_thumb.close() return True forms.py class CreateMemberProfileForm(ModelForm): class Meta: model = Member fields = ('profile_pic') widgets = { 'profile_pic': ImageUploaderWidget(), } views.py class UpdateProfileView(UpdateView): model = Member form_class = UpdateMemberProfileForm template_name = 'update_profile.html' success_url = reverse_lazy('dashboard') updateprofile.html <form class="dropzone" enctype="multipart/form-data" method="post"> {% csrf_token %} … -
Adding several schema encoding URLs in Django REST framework swagger-ui.html template
I have the swagger-ui.html file in a Django (v4.1.2) app as follow (taken from the Django REST framework doc): <!DOCTYPE html> <html> <head> <title>Swagger</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@3/swagger-ui.css"> </head> <body> <div id="swagger-ui"></div> <script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url 'yaml-schema' %}", url: "{% url 'json-schema' %}",<!-- This is what I naturally want to add --> dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout", requestInterceptor: (request) => { request.headers['X-CSRFToken'] = "{{ csrf_token }}" return request; } }) </script> </body> </html> I have defined two paths defining the schema in the urlpatterns list in my main url.py, one for a YAML encoded version and the other for a JSON encoded version of the schema: (...) from drf_spectacular.views import ( SpectacularYAMLAPIView, SpectacularJSONAPIView, SpectacularSwaggerView, ) (...) # OAPI 3 urlpatterns = [ ... path( rf"{API_BASE}schema/yaml/", SpectacularYAMLAPIView.as_view(), name="yaml-schema", ), path( rf"{API_BASE}schema/json/", SpectacularJSONAPIView.as_view(), name="json-schema", ), path( rf"{API_BASE}docs/", SpectacularSwaggerView.as_view( template_name="swagger-ui.html", url_name="yaml-schema" ), name="swagger-ui", ), ] drf_spectacular.views doc: https://drf-spectacular.readthedocs.io/en/latest/drf_spectacular.html#module-drf_spectacular.views I would like to add two links on top of the swagger API doc page, one per schema encoding: But when I add the line url: "{% url 'json-schema' %}", in the swagger-ui.html file, there is only the last … -
How to save different javascript codes in a blog application?
I have a blog using vue.js as frontend framework, Django as backend framework and postgressql as database. I want to have games among my blog posts text so each post has different js code (vue component). What is your solution to structure my database? -
How to mix python and javascript in the server side
I'm creating an application that needs to pull certain data to show it to the user. This data is pulled via a JavaScript function that ideally I'd like to have on the server side, not on the source code of the page. The flow should be: User chooses 1 parameter in the website and clicks ok Send a POST request to Django with that parameter Django's view uses that parameter to pull another 4 parameters from the Django database Somehow use this 4 parameters in the JavaScript function to get some timeseries data Pass this data from JavaScript to the view, and from the view update the browser's template without the user refreshing the page How can I pass the 4 parameters from Python to the JS function, and then the result of the JS function back to Python? The reason I need to use JavaScript and not Python for retrieving that data is because JS has a specific library that would make my life so much easier. -
Django Send Email form, how to add value from another model established via foreign key
I am trying to create a Ticket form which sends Email. Everything is working fine, but there is a foreign key field, I am pulling data from it in this ticket, I am not able to include that in the email body. views.py def createTicket(request): form = TicketForm(request.POST) if request.method == 'POST': if form.is_valid(): subject = "Ticket Email" body = { 'customer': form.cleaned_data.get('customer'), 'subject': form.cleaned_data.get('subject'), 'priority': form.cleaned_data.get('priority'), 'details': form.cleaned_data.get('details'), } message = "\n".join(body.values()) form.save() try: send_mail(subject, message, 'from_email', [form.cleaned_data.get('technician_email')]) except BadHeaderError: return HttpResponse('Invalid Header') return redirect('/') context = {'form': form} return render(request, 'ticket_form.html', context) models.py class Ticket(models.Model): PRIORITY = ( ('normal', 'Normal'), ('urgent', 'Urgent') ) STATUS = ( ('pending', 'Pending'), ('hold', 'Hold'), ('closed', 'Closed') ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) technician = models.CharField(max_length=255, null=True) technician_email = models.CharField(max_length=255, null=True) subject = models.CharField(max_length=255, blank=True, null=True) priority = models.CharField(max_length=255, blank=True, null=True, choices=PRIORITY) details = models.CharField(max_length=2000, blank=True, null=True) class Customer(models.Model): company_name = models.CharField(max_length=255, null=True) Customer_type = models.ManyToManyField(Customertype, blank=True) first_name = models.CharField(max_length=255, null=True) last_name = models.CharField(blank=True, max_length=255, null=True) Now the foreignkey fiend "customer", I am unable to obtain data, what is the correct method to pull value from this field. I am getting below error: Exception Type: TypeError Exception Value: sequence item 0: expected str … -
django row sql query in multi model
I want to use blow query in my django but I select multiple model in my query and I don't know what should I set for ? in my code ?.objects.row("SELECT * from Backup,auth_user, Account_asset where Backup.AssetName=Account_asset.Asset_name and auth_user.id = Account_asset.user_id and auth_user.username = admin") I need type that can query on whole models -
UnboundLocalError when simply adding a logic check
Good day fellas, sometimes computer logic really is just unbearable... Can someone do me the courtesy of explaining why this code works: def forecast_view(request): if request.method == 'POST': city = request.POST['city'] city_capitalized = city.capitalize() safe_string_city = urllib.parse.quote_plus(city) #language = request.POST['language'] #units = request.POST['units'] #url = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&lang='+language+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b&units='+units).read() res = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+safe_string_city+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b').read() json_data = json.loads(res) data = { 'country_code': json_data['sys']['country'], 'coordinates': str(json_data['coord']['lon']) + ' ' + str(json_data['coord']['lat']), 'weather': json_data['weather'][0]['main'], 'description': json_data['weather'][0]['main'], 'icon': 'http://openweathermap.org/img/wn/' + json_data['weather'][0]['icon'] + '@2x.png', 'wind': json_data['wind']['speed'], 'temperature': json_data['main']['temp'], 'pressure': json_data['main']['pressure'], 'humidity': json_data['main']['humidity'], 'city': city_capitalized, } else: city = '' data = {} return render(request, 'weather/forecast.html', data) But then as I add a simple logic check I get the UnboundLocalError if request.method == 'POST': if request.POST.get("filters"): pass elif request.POST.get("get_info"): city = request.POST['city'] city_capitalized = city.capitalize() safe_string_city = urllib.parse.quote_plus(city) #language = request.POST['language'] #units = request.POST['units'] #url = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&lang='+language+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b&units='+units).read() res = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+safe_string_city+'&appid=66d8dd58fe4ab3e2cbf275d5aee1d85b').read() json_data = json.loads(res) data = { 'country_code': json_data['sys']['country'], 'coordinates': str(json_data['coord']['lon']) + ' ' + str(json_data['coord']['lat']), 'weather': json_data['weather'][0]['main'], 'description': json_data['weather'][0]['main'], 'icon': 'http://openweathermap.org/img/wn/' + json_data['weather'][0]['icon'] + '@2x.png', 'wind': json_data['wind']['speed'], 'temperature': json_data['main']['temp'], 'pressure': json_data['main']['pressure'], 'humidity': json_data['main']['humidity'], 'city': city_capitalized, } else: city = '' return render(request, 'weather/forecast.html', data) How does it make any sense? I am not assigning or ressigning anything! Thanks for the help …