Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set graphene field when returning from query resolver
We are currently upgrading from an old version of graphene (0.99) to a new one (2.15). In the old version, we were able to set the value of a field in the query resolver. For example: class DogType(DjangoObjectType): selected = graphene.Boolean() class Meta: model = Dog class DogsQuery(graphene.ObjectType): dogs = graphene.List(DogType) resolve_dogs(self, info): top_dogs = Dogs.objects.all()[:10] return [DogType(d, selected=(i == 0)) for i, d in enumerate(top_dogs)] This resolver hands back a list of DogTypes, and the first dog in the list has "selected=True" while the others have "selected=False". It resolves successfully. In newer versions of graphene, this throws an error: "'DogType' object has no attribute 'pk'". I presume this is because newer versions of graphene don't want us to return Types. So I'm just wondering if it is possible to set the graphene field "selected" in the query resolver itself in newer versions of graphene? -
How to upload an image on server with react native?
I'm using react native on frontend and django in backend. I want to submit a form and that form contains images in it. Now the problem is. I'm unable to upload images with following code. currently following json is going in backend. { "details":{ "name":"My first ", "description":"this is Gina be cool", "display":"file:///data/user/0/com.merchant_app/cache/rn_image_picker_lib_temp_935cb7c5-72fd-4c7a-ab45-7b62906909f7.jpg", "background":"file:///data/user/0/com.merchant_app/cache/rn_image_picker_lib_temp_9449c3c0-32c6-4122-8a92-1a9b5afa352f.jpg" }, "hours":[ { "partition":"P1", "timings":[ { "day":"Monday", "full_day":false, "close_day":false, "start_time":"2022-09-16T01:00:00.149Z", "close_time":"2022-09-16T01:00:00.149Z" } ] } ] } backend response : {'display': ['The submitted data was not a file. Check the encoding type on the form.'], 'background': ['The submitted data was not a file. Check the encoding type on the form.']} my code . const {Name,bio,displayFilePath,backgroundFilePath} = this.props.route.params.stepOneData const background = backgroundFilePath const display = displayFilePath console.log("==> ",backgroundFilePath.assets[0].fileName) let data = { details = { name:Name, description:bio, display:display, background:background }, hours:[ { "partition":"P1", "timings":[ { "day":"Monday", "full_day":false, "close_day":false, "start_time":"2022-09-16T01:00:00.149Z", "close_time":"2022-09-16T01:00:00.149Z" } ] } ] } try { await addNewGroundAPI(formdata) alert("Post created") } catch (e) { console.log("Error", e) // alert("Error") } If you know to fix it. Please contribute in solving this thank You. -
Django+Postgres Broken transaction after checking for uniqueness
I created a simple project with one application and a model. https://github.com/SergeyMalash/test_unique It has two unique fields. Also in the settings I specified ATOMIC_REQUESTS When I make a POST request with an invalid IP address, an error occurs (screenshot) My assumptions: As far as I understand, during the check for uniqueness, a DataError exception occurs, since postgres can't compare inet field with an incorrect IP address This breaks all subsequent calls to the database. https://github.com/encode/django-rest-framework/blob/master/rest_framework/validators.py#L71 Am I right? How can this be fixed? I need to leave ATOMIC_REQUESTS enabled My issue is partially related to https://github.com/encode/django-rest-framework/issues/3381 But I didn't find a solution there. `https://pastebin.com/bDuQvje4` `https://pastebin.com/7VaWjMaZ` -
Django/Wagtail Rest Framework API Ordering/Pagination
I am using wagtail. I have serialized my API. I want to order them by -first_published_at, when someone hit my API url api/v2/pages they will see an ordered API without filtering it via URL. here is my api.py code: class ProdPagesAPIViewSet(BaseAPIViewSet): renderer_classes = [JSONRenderer] filter_backends = [FieldsFilter, ChildOfFilter, AncestorOfFilter, DescendantOfFilter, OrderingFilter, TranslationOfFilter, LocaleFilter, SearchFilter,] meta_fields = ["type","seo_title","search_description","first_published_at"] body_fields = ["id","type","seo_title","search_description","first_published_at","title"] listing_default_fields = ["type","seo_title","search_description","first_published_at","id","title","alternative_title","news_slug","blog_image","video_thumbnail","categories","blog_authors","excerpt","content","content2","tags",] nested_default_fields = [] ordered_queryset= [] name = "pages" model = AddStory api_router.register_endpoint("pages", ProdPagesAPIViewSet) I have tried ordered_queryset= [AddStory.objects.order_by('-first_published_at')] But it's not ordered by the newest published stories. How should I do the query? Here is my API response { "meta": { "total_count": 6 }, "items": [ { "id": 4, "meta": { "type": "blog.AddStory", "seo_title": "", "search_description": "", "first_published_at": "2022-08-30T11:05:11.341355Z" }, { "id": 6, "meta": { "type": "blog.AddStory", "seo_title": "", "search_description": "", "first_published_at": "2022-08-30T11:13:47.114889Z" }, { "id": 7, "meta": { "type": "blog.AddStory", "seo_title": "", "search_description": "", "first_published_at": "2022-08-31T11:13:47.114889Z" }, -
How to extend template from library
I have a Django app, where I have customized the admin base_site.html. I have installed a library (Django admin tools) which also extends the admin base_site.html Obviously, my custom base_site.html does not load anymore. I'd like to extend the base_site from django-admin-tools but I did not find how. I have read the Django docs (Template inheritence and extends) but could not find anything with more details. I have also seen the {% extend "project:path/file.html" %} notation but could not find documentation about how the part before the : works. I have tried : {% extend "admin_tools/base_site.html" %} {% extend "admin_tools/admin/base_site.html" %} {% extend "admin/admin_tools/base_site.html" %} {% extend "admin/admin_tools/menu/templates/admin/base_site.html" %} {% extend "admin_tools/menu/templates/admin/base_site.html" %} {% extend "admin_tools:menu/templates/admin/base_site.html" %} How can I extend this file ? And, if it exists, where can I find the documentation on how exactly extend works ? My template config looks like this : TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": False, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", # Custom context processors "utils.context_processors.settings", "social_django.context_processors.backends", "social_django.context_processors.login_redirect", ], 'loaders': [ "admin_tools.template_loaders.Loader", "django.template.loaders.app_directories.Loader", # insert your TEMPLATE_LOADERS here ] }, }, ] -
Unique together with something related by a foreign key
class ExamSectionMixin(models.Model): exam_section = models.ForeignKey('fipi_exam_sections.ExamSection', blank=True, null=True, on_delete=models.CASCADE, ) class Meta: abstract = True class PriorityMixin(models.Model): priority = models.PositiveIntegerField(blank=False, default=0, null=False, db_index=True) class NameMixin(models.Model): name = models.CharField(max_length=255, null=False, default="") def __str__(self): return self.name class Meta: abstract = True class TaskDescription(NameMixin, PriorityMixin, ExamSectionMixin): class Meta: constraints = [ models.UniqueConstraint(fields=['exam_section__exam_part', 'name', ], name='exam_section-name'), models.UniqueConstraint(fields=['exam_section__exam_part', 'priority', ], name='exam_section-priority') ] This code blows up when migrating. That is makemigrations is done. But not migrate. fipi_task_descriptions.TaskDescription: (models.E012) 'constraints' refers to the nonexistent field 'exam_section__exam_part'. Could you tell me whether it is possible to organise unique together of exam_part and name and exam_part and priority respectively? -
Optional Parameter in URL for Taggit Django
I've been trying to use Tags in my project, using the django application django-taggit. I already put them in the models and it works fine so far. But now i want that people can search for the items in the url with the tags. For example /items/tag=blue. But i want this parameter in the URL to be optional. How can i do this? This is my URL: path('items/', views.ItemsView.as_view(), name='items') I just want a parameter in this url, that is optional so the user can, but doesn't have to search for them. -
How to get the remaining values from django array loop
I am learning some stuff in the Django template but I encountered some difficulty in adding my dynamic style. My goal here is to add a span and class in the first word but I don't know how to get the remaining words. Here's my code: <h4> {% for b in banner.title.split %} {% if forloop.counter == 1 %} <span class="main-color">{{ b }}</span> {% else %} {{ b }} {% comment %} HOW CAN I GET THE REMAINING HERE{% endcomment %} {% endif %} {% endfor %} </h4> {% comment %} Target output: <h4> <span class="main-color">OUR</span>WORKS </h4> {% endcomment %} -
ASGI Django Application Hosting in Windows Server 2012
Can I host ASGI Django App in Windows Server 2012 backed with Apache? I explored several blogs which mentions about "mod_wsgi" which confused me if it could handle ASGI application. Medium/Analytics-Vidya Prof. Dr. Christian Leubner settings.py INSTALLED_APPS = [ 'channels', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'broadcast', ] ASGI_APPLICATION = 'AppMain.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], # "hosts":[os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, }, } asgi.py import os import django from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from broadcast.consumers import AConsumer import broadcast.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppMain.settings') django.setup() # application = get_asgi_application() application = ProtocolTypeRouter({ 'http' : get_asgi_application(), 'websocket' : AuthMiddlewareStack( URLRouter( broadcast.routing.websocket_urlpatterns ) ) }) -
I can't get to one parameter(m2m) from my models Django
I created view where i add stops to route, its working fine, but stops are not appearing in order when i add them, and i have no idea why. Please tell me where i'm making a mistake Here's my code: Models: #not important class Port(models.Model): class Route(models.Model): name = models.CharField(max_length=128, default='') user = models.ForeignKey(User, on_delete=models.CASCADE) stop_list = models.ManyToManyField(Port, through='RoutePort') def __str__(self): return f'{self.name}' class RoutePort(models.Model): port = models.ForeignKey(Port, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) order = models.PositiveIntegerField() class Meta: ordering = ['order'] the order i intend them to appear is set by 'order' parameter from class routeport form: class AddRoutePort(forms.ModelForm): class Meta: model = RoutePort fields = ['port', 'order'] form is short and i dont know if i didnt forget something there View, get is working correctly, post works almost ok. New ports are correctly added to new route from list, but they appear in order of being added, not the one i wanted them to. class RouteCorrectView(View): def get(self, request, pk): route = Route.objects.get(pk=pk) form = AddRoutePort() return render(request, 'route_correct.html', {'route':route, 'form':form}) def post(self, request, pk): route = Route.objects.get(pk=pk) form = AddRoutePort(request.POST) if form.is_valid(): to_port = form.save(commit=False) to_port.route = route order = to_port.order ordering = RoutePort.objects.filter(order__gte=order, route=route) for port in … -
Select From Another DataBase in Django Rest framework
In Rest FrameWork Django I want use from another DataBase in my View Now I can use data of databse model of django created . I want select a database of another program and show in api Please Help Me Thanks -
Rendering Django View Data to HTML
I am creating a learning portal, in which students can learn on various books. Each book will have various chapters / topics. Each topic is having a unique slug, as reflected the below mentioned model, which we want to render / show on an HTML page, upon clicking on it. I want to show the contents of the topic on a separate HTML page, when somebody click on that particular topic. I have written the below mentioned code, however, failed to populate the data on the HTML. My Django model, view.py and url.py is as under. My Django model is as follows: class book_explination(models.Model): title = models.CharField (max_length = 255) slug = models.SlugField(max_length= 250, null = True, blank = True, unique= True) lesson_no = models.CharField (max_length = 255) book_text = models.TextField (blank=False, null=False) my view is as follows: def topic_detail(request, url): topic_detail = book_explination.objects.get(slug = url) return render(request, 'blog/topic_detail.html', {'topic_detail':topic_detail}) The HTML rendering page is as follows: {% block content %} <div class="container"> <p> {{lesson_no | safe}} </p> <p> {{book_text | safe}} </p> <p> {{book_text_explination | safe}} </p> </div> {% endblock %} <ul> {% for c in topic_detail %} <li>{{ c.lesson_no }}</li> <li>{{ c.lesson_no }}</li> <li>{{ c.lesson_no }}</li> {% endfor … -
How to connect to RDS from locally created django
I am trying to connect to Aurora on RDS from a local Django application. Docker is used as the execution environment. Publicly Accessible is allowed to connect to RDS from local. I have confirmed that I can connect from local with mysql command, but not from on django. Why can't I connect from Django? Commands tried: $ mysql -h xxxx.xxxx.ap-northeast-1.rds.amazonaws.com -u admin -p mysql> This command allows you to get inside mysql. The django database setup is as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxxxxx', 'USER': 'admin', 'PASSWORD': 'xxxxxxx', 'HOST': 'xxxxx.xxxxxxx.ap-northeast-1.rds.amazonaws.com', 'PORT': '3306', } } Output error statement: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'xxxxx.xxxxx.ap-northeast-1.rds.amazonaws.' (111)") -
Django test : Field 'id' expected a number but got datetime.datetime
It's my first time doing tests in a Django app, and I don't understand my error. When i run python manage.py test, I got this error : D:\Users\boucardale\Documents\code\djangotest>python manage.py test You are in dev mode Found 1 test(s). Creating test database for alias 'default'... Traceback (most recent call last): File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\commands\test.py", line 24, in run_from_argv super().run_from_argv(argv) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\commands\test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\test\runner.py", line 1000, in run_tests old_config = self.setup_databases( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\test\runner.py", line 898, in setup_databases return _setup_databases( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\test\utils.py", line 220, in setup_databases connection.creation.create_test_db( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\db\backends\base\creation.py", line 79, in create_test_db call_command( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\__init__.py", line 198, in call_command return command.execute(*args, **defaults) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) … -
how to get selected value from checkbox into views.py and convert into excel?
index.html <form method="GET"> <div class="form-row"> <div class="custom-control custom-checkbox mb-10 popup-sec-chk"> <input class="custom-control-input form-control inputfld" type="checkbox" id="date_inquiry" name="excelfields[]" value="dateofInquiry"> <label class="custom-control-label" for="date_inquiry">Date of Inquiry</label> </div> <div class="custom-control custom-checkbox mb-10 popup-sec-chk"> <input class="custom-control-input inputfld" type="checkbox" id="callers_name" name="excelfields[]" value="Callers name"> <label class="custom-control-label" for="callers_name">Caller's Info</label> </div> </div> <div class="modal-footer"> <a type="submit" href="{% url 'excelExport' %}" class="btn btn-primary" >Select</a> </div> </form> views.py def excelExport(request): try: if request.method == 'GET': checkedField = request.GET.getlist('excelfields[]') print("Checked list data ====== ", checkedField) return HttpResponseRedirect('home') except Exception as e: print("Exception =", e) return render(request, 'home.html') Print Output:- Checked list data ====== [] I'm working on a Django project where i want to do export in excel the selected data from checkbox. Right now I'm able to do export into excel but getting all the data, instead i want the selected data which i will select from the checkbox. -
How to change media url in django?
I have a website in production that serves media files properly. Media Setting in settings.py file : MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I have created a media folder inside my project where my all media are being stored. Due to the media URL it severs media files as https://domain_name/media/file_name. I want to serve my media files as https://domain_name/images/file_name. I try to change the MEDIA_URL setting in settings.py file, but it shows 404 error for the images. Updated settings.py file MEDIA_URL = 'images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Django Templates avoid loop
I am working on a project and jhave a slight confusion. The Djago Template index.html has following code: <div class="carousel-item active"> {% for i in products|slice:"0:"%} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 17rem;"> <div class="card-body"> {% for img in i.images.all %} {% if forloop.counter == 1 %} <img src={{img.img_url}} class="card-img-top" alt="..."> {% endif %} {% endfor %} <h6 class="card-title">{{i}}</h6> {% for skus in i.skus.all %} {% if forloop.counter == 1 %} <h6 class="card-price">{{skus.price}} {{skus.currency}}</h6> {% endif %} {% endfor %} <a href="#" class="btn btn-primary">Add to Cart </a> </div> </div> </div> {% endfor %} </div> In this code , Is there a way to eliminate the {% for skus in i.skus.all %} The all tag is getting all objects but I am restricting the loop to run only one time through if condition so that I can only get the first item. Is there a way to eliminate the loops that have .all in them and restrict the statement to run only one time though any other way. -
Django not loading static files from React build folder
I am not able to load CSS and JS files in React frontend. Django setting file STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), **os.path.join(BASE_DIR, '../frontend/build/static')** ] After I run npm run build and check the django its not loading the static files. -
unable to set value using useState Hook in reactjs
function App() { const [LinkList, setLinkList] = useState([]); const [categories, setCategories] = useState({id:[], cat:[]}); var catArray = []; useEffect(() => { fetch("http://127.0.0.1:8000/api/service/category-list/") .then((response) => response.json()) .then((data) => { for (var i = 0; i < data.length; i++) { catArray.push({id:data[i].id, cat:data[i].category}); } setCategories(catArray); console.log(categories); //this line displays empty array console.log(catArray)//this line literally displays the date fetched. if( setCategories(catArray)){ console.log(true); //it rejects this line of code }else{ console.log("false");//this line is executed } }); }, []); I've put the issue in the comment of code -->{id: Array(0), cat: Array(0)} the above line is displayed when I try to log "categories" to the console please share me your Idea on this problem. code is literally correct, but it still throwing error to the console -
SMTPSenderRefused at /password-reset/ - Django
settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('USER_EMAIL') EMAIL_HOST_PASSWORD = os.environ.get('USER_PASS') Error: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h10-20020a170902680a00b0015e8d4eb1d5sm14008586plk.31 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 4.1.1 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h10-20020a170902680a00b0015e8d4eb1d5sm14008586plk.31 - gsmtp', 'webmaster@localhost') Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\smtplib.py, line 887, in sendmail Raised during: django.contrib.auth.views.PasswordResetView Python Executable: D:\Django\Tutorial\env\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\\Django\\Tutorial\\django_project', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310', 'D:\\Django\\Tutorial\\env', 'D:\\Django\\Tutorial\\env\\lib\\site-packages'] Server time: Fri, 16 Sep 2022 06:10:41 +0000 I am trying to set an email password reset in my django app but get this unexpected error. can you help me with this or provide me with some links so I can reach to the core of this error. -
I want to return the response without disturbing the data coming from subscription of node in django
async def get_event(self,address): infura_ws_url = 'wss://ropsten.infura.io/ws/v3/7c074579719748599c087f6090c413e2' address_checksumed = self.w3.toChecksumAddress(address) async with connect(infura_ws_url) as ws: await ws.send('{"jsonrpc": "2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}') # print("HERE") subscription_response = await ws.recv() print(subscription_response) while True: try: message = await asyncio.wait_for(ws.recv(), timeout=15) response = json.loads(message) txHash = response['params']['result'] tx =self.w3.eth.get_transaction(txHash) if tx.to == address_checksumed : print("Pending transaction fincoming:") print({ "hash": txHash, "from": tx["from"], "value": self.w3.fromWei(tx["value"], 'ether') }) transaction_receipt_json = { "transaction_hash": txHash, "from": tx["from"], "value": self.w3.fromWei(tx["value"], 'ether') } return transaction_receipt_json # return Response(transaction_receipt_json) pass except Exception as e: print("Exception") print(e.args) print(e.__str__) pass @action(detail=False, methods=['GET'], url_path='subscribe-deposit') def subscribe_deposit_address(self, request): address = self.request.query_params.get('address') # get_event.delay(address,) # return Response('Address subscribed') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) while True: resp = loop.run_until_complete(self.get_event(address)) return Response(resp) when I call this API from postman it subscribe the pending tx and returns when any transaction pending contains my address as destination but immediately after returning the response on postman my request ends and I don't want it that my request get end I want my request don't end and whenever any pending tx comes which contains my address as destination it returns the tx in response -
I created a view that add stops to route and they are not appearing by parameter order from models
I created view where i add stops to route, its working fine, but stops are not appearing in order when i add them, and i have no idea why. Please tell me where i'm making a mistake Here's my code: Models: class Port(models.Model): name = models.CharField(max_length=128) description = models.TextField(default='') lattitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) amenities = models.ManyToManyField(Amenity, blank=True) def __str__(self): return f'{self.name}' class Route(models.Model): name = models.CharField(max_length=128, default='') user = models.ForeignKey(User, on_delete=models.CASCADE) stop_list = models.ManyToManyField(Port, through='RoutePort') def __str__(self): return f'{self.name}' class RoutePort(models.Model): port = models.ForeignKey(Port, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) order = models.PositiveIntegerField() class Meta: ordering = ['order'] the order i intend them to appear is set by 'order' parameter from class routeport form: class AddRoutePort(forms.ModelForm): class Meta: model = RoutePort fields = ['port', 'order'] form is short and i dont know if i didnt forget something there View, get is working correctly, post works almost ok. New ports are correctly added to new route from list, but they appear in order of being added, not the one i wanted them to. class RouteCorrectView(View): def get(self, request, pk): route = Route.objects.get(pk=pk) form = AddRoutePort() return render(request, 'route_correct.html', {'route':route, 'form':form}) def post(self, request, pk): route = Route.objects.get(pk=pk) form … -
Why does Django Money show 3 decimals with decimal_places=2?
I'm very confused by this: >>> from djmoney.models.fields import Money >>> Money("0.129", "EUR", decimal_places=2) Money('0.129', 'EUR') I've expected to see Money('0.12', 'EUR') or Money('0.13', 'EUR'). I know I can use round(2) to get the expected result, but what influence does decimal_places have? If it stores the data anyway, why/when should I use the parameter? The docs are not helpful. -
Error loading MySQLdb Module in django project when mysql setup
I have a problem with my project, I installed the "pymysql", but i am trying to use the "pymysql", but i try to use and gives the following error: ModuleNotFoundError: No module named 'pymysql' pip install pymysql import pymysql ModuleNotFoundError: No module named 'pymysql' Collecting MySQL-python Using cached MySQL-python-1.2.5.zip (108 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [19 lines of output] Traceback (most recent call last): File "/home/admin1/Documents/HOG_APIs/HOGENV/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in main() File "/home/admin1/Documents/HOG_APIs/HOGENV/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/home/admin1/Documents/HOG_APIs/HOGENV/lib/python3.10/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 130, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 338, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 320, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 482, in run_setup super(_BuildMetaLegacyBackend, File "/tmp/pip-build-env-f52gexwm/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 335, in run_setup exec(code, locals()) File "", line 13, in File "/tmp/pip-install-atvcbcg9/mysql-python_60be5e09ce744d36b68b98258534b6a2/setup_posix.py", line 2, in from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for … -
MultiValueDictKeyError in crud
def editproduct(request,pk): #editproduct/4 pk=4 prod=Item.objects.get(id=pk) if request.method=='POST': if len(request.FILES)!=0: os.remove(prod.image.path) prod.image=request.FILES['image'] prod.name=request.POST.get('name') #iphone prod.description=request.POST.get('description') #offers prod.price=request.POST.get('price') #200000 prod.save() return redirect(index1) context={'prod':prod} return render(request,'edit_item.html',context)