Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django admin page redirected you too many times
This is my main urls file from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.apiOverview), path('admin/', admin.site.urls), path('academy/', include('academy.urls')), path('administration/', include('administration.urls')), ] this code working fine in localhost, but when i run it in online server works other endpoints correctly but when i use to login admin by using admin/ then showing this Error..!! I search it but unable to solve this issue. I use online rederect tool where shows 301 and 302 redirection code!! Please help me!! -
Django: How to get a person whose birthday is today from a database?
Good afternoon, I recently started programming with Django and there was a slight difficulty with displaying the date of birth of a person whose birthday is today from the database, can anyone come across this? model.py class HapB(models.Model): name = models.CharField('Имя', max_length=50) last_n = models.CharField('Фамилия', max_length=50) Otdel = models.CharField('Отдел', max_length=50) date_of_birth = models.DateField('Дата рождения', null=True, blank=True) def __str__(self): return self.name -
Is transferring JSON data in Django possible without JS / JQuery?
I am learning how to handle JSON files in Django and I have successfully unpacked JSON, but now I would like to put it inside the table. Is there a way to do that with pure HTML and using so called "tornado brackets" {{ }} not with jQuery / JS functions? My code: API BACKEND FILE from requests import get default_values = { "repoName": "", "repoURL": "" } def get_response(): response = get_json() main_dictionary = { "items":[] } try: for repos in response: main_dictionary["items"].append({ "repoName": repos["name"], "repoURL": repos["html_url"] }) except KeyError as error: print("Key Error, check the validity of the keys you try to use to decode JSON") return main_dictionary["items"] def get_json(): first_response = get('https://api.github.com/users/jacobtoye/repos') response = first_response.json() return response A FAILED ATTEMPT AT RENDERING PURE HTML TABLE {% block content %} <table> <tr> {% for repos in response %} <td>{{ repoName }}</td> {% if not forloop.last and forloop.counter == 3 or forloop.counter == 6 %} </tr> {% endif %} <tr> {% endfor %} </tr> </table> The table doesn't show at all. I don't think that any other code files are substantial for this problem, but if you think you need more code, LMK I will gladly show you :) -
My DataTable isn't displaying like it should
https://datatables.net/ I took the datatable from this site. I write through my code but previous and next buttons are not styled. I'm using Django framework. How can I fix this? Here is my html table: <div class="table-keep"> <div class="container"> <h1>Olv Go Registrations</h1> <table class="table" border=1 id="mydatatablem"> <thead> <tr> <th>Full Name</th> <th>Company</th> <th>Email</th> <th>Phone Number</th> <th>Note</th> </tr> </thead> <tbody> {% for x in x_list %} <tr> <td>{{x.full_name}}</td> <td>{{x.company}}</td> <td>{{x.email}}</td> <td>{{x.phone_number}}</td> <td>{{x.note}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src='https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js'></script> <script> $(document).ready(function () { $('#mydatatablem').DataTable(); }); </script> When I use this datatable my on my site the buttons looks like this: https://i.stack.imgur.com/6MQDg.png -
Django google-authentication while using XAMPP(mysql)
I Am working on a Django project, and now I want to add google authentication To my project. when I'm adding Authentication: I face the redirect page problem. task/problem: we need to redirect the home page with some MySQL data(XAMPP). Error: after migration, I run the manage.py runserver. when I'm opening the localhost:8000/account/login, it's now working. -
Session work in local server not in server - Django
I have a Django app which uses cookie session to pass data from one to another template/functions. The problem that I face is that while setting the cookie with either file based, DB based it worked in local perfectly, but while I try set the same session in Digital Ocean development server, it failed for some unknown reason. Here are file which transaction with session settings.py Attempt 1: SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_NAME = "user_session" SESSION_COOKIE_HTTPONLY = True SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True Attempt 2: SESSION_ENGINE = 'django.contrib.sessions.backends.file' SESSION_FILE_PATH = os.path.join(BASE_DIR, "session") views.py def pre_login(request): request.session['pre_login'] = data .... def index(request): user_data = request.session['pre_login'] .... While checking the cookie session in browser, it creates a sessionid for Localhost. But when checking session for the same code, there is nothing for my development server. Please help!!! -
How to solve this fail during installation of Pillow?
I am trying to install pillow and can't solve this installation error. Python version 3.9.7. Pip version 22.1.2 Thank you for help. PS C:\code\django> python -m pip install Pillow Collecting Pillow Using cached Pillow-9.1.1.tar.gz (49.8 MB) Preparing metadata (setup.py) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [186 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-39 creating build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\BdfFontFile.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\ContainerIO.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\CurImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\ExifTags.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\features.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\FliImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\FontFile.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\GdImageFile.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\GifImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\GimpGradientFile.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\Image.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\ImageChops.py -> build\lib.mingw_x86_64-cpython-39\PIL copying src\PIL\ImageCms.py -> … -
Django, Webpack and Heroku: Error reading /app/webpack-stats.json
I'm trying to use Django with Webpack on Heroku via django-webpack-loader. After pushing the files from the repository to Heroku, I run webpack to generate the static files in /dist as well as webpack-stats.json: npx webpack --config webpack.config.js This works fine: both the /dist files and the webpack-stats.json file are correctly created (both are placed within /app/). However, when I try to load the page I get an error: OSError at / Error reading /app/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? The error doensn't say much other than the file /app/webpack-stats.json is missing; however, the file exists, its content is well-formatted and it's in the right location. -
I get an error [<class 'decimal.ConversionSyntax'>] in my cart, how do I fix this?
When adding an item to the cart, an error occurs InvalidOperation at /cart/ [<class 'decimal.ConversionSyntax'>]. My code: cart..py ............................... from decimal import Decimal from django.conf import settings from TeaYardApp.models import Products class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() # получаем товары и добавляем их в корзину product = Products.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in product: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.save() Form for adding goods to the cart,forms.py .................................. from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(25, 200+1, 25)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField( choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) I don't know … -
How do I use filter for Count in Django annotate()?
So I've seen lots of posts dealing with the same question, but most of them were outdated(Django versions) and I couldn't find anything helpful. So the problem is, I was trying to use filter for Count in Django annotation. Below is an example, and I've tried three variances that I found after Googling. all_posts = Post.objects.all().annotate( count_comments = Count('user_comment', validated=True), #1 count_comments = Count('user_comment').filter(validated=True), #2 count_comments = Count('user_comment', filter=Q(validated=True)), #3 ) As you can see, I'm trying to get the number of comments that are validated. But obviously none of them works. What is the correct way of using the filter? -
Why does the set method in the many-to-many field through a custom model not work but add method does?
I have these models: class PackRepo(BaseModel): title = models.CharField(max_length=256, verbose_name='Title') class PackVersion(ModelWithUID, BaseModel): repositories = models.ManyToManyField( to='PackRepo', verbose_name='Chart Repositories', related_name='chart_versions', through='ChartVersionRepo' ) class ChartVersionRepo(BaseModel): chart_version = models.ForeignKey(PackVersion, on_delete=CASCADE) chart_repo = models.ForeignKey(PackRepo, on_delete=CASCADE) class Meta: unique_together = ['chart_version', 'chart_repo'] BaseModel has some auto-generated or nullable fields. When I want to set a couple of PackRepo for PackVersion in the migration file, the set() method does not work but add method does. The set method does not raise any errors but ChartVersionRepo's instances do not change. I searched it but I could not find the reason. This is my code: ChartRepoModel = apps.get_model("core", "packrepo") pack_version_new_item = copy.deepcopy(duplicate_items[0]) pack_version_new_item.pk = None pack_version_new_item.save() repos = ChartRepoModel.objects.filter(pack_versions__in=duplicate_items_ids).distinct().values_list('id', flat=True) new_item.repositories.set(repos) -
Django match the day and after the hour
recently I posted here a question to match the calendar users. Now the problem is, I am matching the exact interval of days-time. Here are the four conditions I am looking for: Search to each day if doesn't exist a match in the day, exclude the result from the list. if exists at least one day equal, check the range hour. if the hour of the user is inside the mine, then include the result on the list. Please, take a look at the other post to respond to this. I separated the questions to be more clear. Thanks -
plot with matplotlib using django
How i can add on my code that i want colors without color yellow because the yellow is just for outliers def show_absorbance(df_abs, crop_left, crop_right, clean_param): df_abs_t = df_abs.iloc[:, -1].T outliers = inf_norm_detection(df_abs,crop_left, crop_right, clean_param) colors = list(mcolors.CSS4_COLORS.values()) plt.figure(figsize=(16, 10)) plt.subplot(221) plt.plot(df_abs.to_numpy()[:, 1:].T, 'yellow') for i, outlier in enumerate(outliers): plt.plot(df_abs.loc[outlier].iloc[1:], c=colors[i],label=outlier) plt.legend() plt.show() so when i defined here colors , how i remove the yellow? colors = list(mcolors.CSS4_COLORS.values()) -
ModuleNotFoundError: No module named” when run in docker
I have the following Django project which runs perfectly in non-docker debug mode. xxxProjectv3 │ ├── asgi.py │ ├── celery.py │ ├── __init__.py │ ├── settings │ │ ├── development_settings.py │ │ ├── django_settings.py │ │ ├── __init__.py │ │ ├── production_settings.py │ │ └── project_settings.py │ ├── urls.py │ └── wsgi.py ├── CCTV │ ├── admin.py │ ├── apps.py │ ├── camera.py │ ├── consumers.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── routing.py │ ├── tasks.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── celerybeat-schedule.db ├── db.sqlite3 ├── docker-compose.yml ├── Dockerfile ├── dome_control │ ├── admin.py │ ├── apps.py │ ├── conditions.py │ ├── consumers.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── relays.py │ ├── routing.py │ ├── tasks.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── home │ ├── admin_bak.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── requirements.txt ├── shared_data │ ├── conditions.json │ ├── debug.log │ ├── django.log │ ├── relays.json │ └── temperhum.json ├── static … -
Integration Vue.js in my Django application
I have a generic question about best practises in terms of using Vue.js and Django. My idea is to integrate Vue.js framework to the existing app. In total I have more than 15 views in Django (ListViews, DetailVIews, TemplateViews) and I'd like to use Vue.js only in 2 views (together with DRF). What is the best way to do it? Should I create a seperate app (in most courses I watched it is called backend and frontend) and connect it to SQL database and leave everything else as it is or I really need to adjust all views to Vue.js framework? I am also concerened about authentication process because everything is written puerly in Django and I am not sure how would that cooperate when creating app in Vue.js? -
Single user view in Django API (Rest Framework)
I created an API on Django using the rest framework, I populate that through the default Django Admin Page. My question: the API works fine and I'm able to get all the results, but I'm looking to create an endopoint like /api/<int:CID> that returns just one user. I would like to use the field 'CID' to filter. How can I do that? Thanks! I've some fields in my API, here my serializers.py class HCSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = HomeController fields = ('full_name','Staff','CID', 'OI', 'Rating', 'GND', 'TWR', 'APP', 'CTR', 'Notes') class VCSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = VisitingController fields = ('full_name','CID', 'OI', 'Rating', 'GND', 'TWR', 'APP', 'CTR', 'Notes') my views.py class HCViewSet(APIView): def get(self): HC = HomeController.objects.all().order_by('full_name') serializer = HCSerializer(HC, many=True) return Response(serializer.data) class VCViewSet(APIView): def get(self): VC = VisitingController.objects.all().order_by('full_name') serializer = VCSerializer(VC, many=True) return Response(serializer.data) my models.py class HomeController(models.Model): full_name = models.CharField(max_length=60) ATM = 'ATM' DATM = 'DATM' TA = 'TA' EC = 'EC' FE = 'FE' WM = 'WM' INS = 'INS' MTR = 'MTR' BLK = 'BLK' Staff = [ (ATM, 'Air Traffic Manager'), (DATM, 'Deputy Air Traffic Manager'), (TA, 'Training Administrator'), (EC, 'Events Coordinator'), (FE, 'Facility Engeneer'), (WM, 'Webmaster'), (INS, 'Instructor'), (MTR, 'Mentor'), (BLK, 'Blank'), ] Staff = … -
Django upload multiple images per post
Hi I want to let the user upload multiple images per post. Similary to an ecommerce platform with multiple images per product. But till now the images are not sent to the database. Thats my code so far: models.py class Project(models.Model): title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) class ProjectImage(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) image = models.FileField() forms.py class ProjectForm(ModelForm): image = forms.ImageField(widget=ClearableFileInput(attrs={'multiple':True})) class Meta: model = Project fields = ['title', 'describtion'] views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) images = request.FILES.getlist('image') if form.is_valid(): project = form.save() for i in images: ProjectImage(project=project, image=i).save() context = {'form':form} return render(request, 'projects/project_form.html', context) project_form.html <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input type="submit" name="" id=""> </form> -
Can't change style of Bootstrap datatables
I'M trying to use this bootstrap datatable in Django: <script src='https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js'></script> <script> $(document).ready(function () { $('#mydatatable').DataTable(); }); </script> But when I try to change default texts position it won't apply. These are the default divs with bootstrap. I find them from chromes inspect part.I want to change these : <div class="dataTables_info" id="mydatatable_info" role="status" aria-live="polite">Showing 1 to 10 of 22 entries</div> <div class="dataTables_paginate paging_simple_numbers" id="mydatatable_paginate"><a class="paginate_button previous disabled" aria-controls="mydatatable" data-dt-idx="0" tabindex="-1" id="mydatatable_previous">Previous</a><span><a class="paginate_button current" aria-controls="mydatatable" data-dt-idx="1" tabindex="0">1</a><a class="paginate_button " aria-controls="mydatatable" data-dt-idx="2" tabindex="0">2</a><a class="paginate_button " aria-controls="mydatatable" data-dt-idx="3" tabindex="0">3</a></span><a class="paginate_button next" aria-controls="mydatatable" data-dt-idx="4" tabindex="0" id="mydatatable_next">Next</a></div> My Actual html file: <div class="table-keep"> <div class="container"> <h1>My Table</h1> <table class="table" border=1 id="mydatatable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>School</th> <th>Phone Number</th> <th>Email</th> </tr> </thead> <tbody> {% for x in x_list %} <tr> <td>{{x.name}}</td> <td>{{x.age}}</td> <td>{{x.school}}</td> <td>{{x.phone}}</td> <td>{{x.email}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <!-- Need to have JQuery and Javascript for DropDown Actions to work --> <script src="http://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src='https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js'></script> <script> $(document).ready(function () { $('#mydatatablem').DataTable(); }); How can I grab and change style of the #mydatatable and the buttons above? -
How to pass iterable list of filtered users in Django template using form?
I have a custom user model that has additional filter than the default Django User, viz. is_candidate and is_voter. I want to pass the list of all those users who have is_candidate as True. I tried to make a form of such users and passed that form in template, but I ma getting following error: TypeError at /votes/ cannot unpack non-iterable User object Request Method: GET Request URL: http://localhost:8000/votes/ Django Version: 4.0.3 Exception Type: TypeError Exception Value: cannot unpack non-iterable User object Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\widgets.py, line 737, in _choice_has_empty_value Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.4 Python Path: ['D:\\VU\\CS619\\BC170403979\\punjabbarcouncil', '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', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages'] Server time: Sun, 12 Jun 2022 10:19:32 +0000 Complete details of error is: Traceback Switch to copy-and-paste view C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars D:\VU\CS619\BC170403979\punjabbarcouncil\register\views.py, line 142, in votes return render(request, 'register/votes.html', context) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py, line 24, in render content = loader.render_to_string(template_name, context, request, using=using) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py, line 62, in render_to_string return template.render(context, request) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py, line 62, in render return self.template.render(context) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py, line 175, in render return self._render(context) … -
How to execute a task in django if condition matched?
I was trying to build a trading application which can handle multiple users, The users can add their bids on stocks. If the current prices of stock matches with the price entered by the user execute that order. Can this task be completed via Celery and celery-beat? if multiple users has placed order then all the order needs to be executed at a same time. I just need to know higher level knowledge on how we can solve this task? -
How Can i go to Customer.html page when i click on cancel link? I can go to dashboard but no to specific page customer because it have id?
CLick TO see picture Click to See the error -
How to upload payment picture by orders, 'QuerySet' object has no attribute '_meta'
I can't filter to upload pictures. I want to upload pictures by : orders= Order.objects.filter(id=orid, id_profil=id_profil) get error : 'QuerySet' object has no attribute '_meta' view.py def Detail(request, orid=None): data = cartData(request) cartItems = data['cartItems'] id_profil = request.user.profile orders = Order.objects.filter(id=orid, id_profil=id_profil) OrderItems = OrderItem.objects.filter(order=orid) pengirimans = Pengiriman.objects.filter(order=orid) if request.method == "POST": form = Uplaodpic(request.POST ,request.FILES ,instance=orders) if form.is_valid(): form.save() else: form=Uplaodpic(instance=orders) context = {'orders':orders, 'OrderItems':OrderItems, 'pengirimans':pengirimans, 'cartItems':cartItems, 'form':form} return render(request, 'store/detail.html' ,context) forms.py from django.forms import ModelForm from .models import Order, Profile class Uplaodpic(ModelForm): class Meta: model=Order fields=["id","bukti"] detial.html <td colspan="2"> <img src="{{ order.buktiURL }}" alt="image" class="img-thumbnail" style="max-height:100px"> </td> <td colspan="2"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="Submit" id="submit" name="submit"> </form> </td> </tr> modes.py class Order(models.Model): id_profil = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) order_data = models.DateTimeField(auto_now_add=True) selesai = models.BooleanField(default=False, blank=True, null=True) status = models.BooleanField(default=False, blank=True, null=True) id_transaksi = models.CharField(max_length=200, null=True) bukti = models.ImageField(upload_to='bukti/',default="person-circle.svg",null=True, blank=True) ongkir = models.CharField(max_length=200, null=True) total = models.CharField(max_length=200, null=True) total_harga = models.CharField(max_length=200, null=True) pembayaran = models.CharField(max_length=200, null=True) -
Django URL Pattern Syntax - raw string
So this might sound like a newb question but I was just wondering what is the difference between path('index/', views... And... path(r'^index/$', views... I just wrote my first web app and I use the first example but I see everyone using the raw string syntax in examples I look up. Are there any differences between the way django handles the two examples? Thanks in advance. -
Add customer modal and edit in one view in django
I am kinda like stuck. I have a BankAccountCreation() and the the form is called in a modal in Django template. I am trying to get the same for be used for editing. but when I do that my edit button returns an empty form My view is as below def employee_info(request, id): if not request.user.is_authenticated: return redirect('/') context = {} banks = Bank.objects.all() employee = get_object_or_404(Employee, id = id) bank_instance = Bank.objects.filter(employee = employee).first() context = {} context['employee'] = employee context['bank'] = bank_instance context['banks'] = banks context['title'] = 'profile - {0}'.format(employee.get_full_name) if request.method == 'GET': form = BankAccountCreation() context['form'] = form return render(request, 'employee/employee_info.html', context) if request.method == 'POST': form = BankAccountCreation(data = request.POST) if form.is_valid(): instance = form.save(commit = False) employee_id = request.POST.get('employee') employee_object = employee instance.employee = employee_object instance.name = request.POST.get('name') instance.branch = request.POST.get('branch') instance.account = request.POST.get('account') instance.code = request.POST.get('code') instance.save() messages.success(request, 'Bank Details Successfully Created for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-success alert-dismissible show') return redirect('employee_info', id=employee.id) else: context['form'] = form messages.error(request, 'Error Updating details for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-warning alert-dismissible show') return redirect('employee_info', id=employee.id) form = BankAccountCreation() return render(request, 'employee/employee_info.html', context) The Bank model has a foreign key to the Employee model -
Django. How to return error 500 without sending mail to admins
I am using standard error handling in production - if there are server errors I am getting mails. However, on certain APIs I want to have a response with HTTP code 500 or 502 as part of the "valid flow". (It's done for educational purposes) So my view for that looks like this: from rest_framework.response import Response from rest_framework import status def give_me_error(request): return Response("This is expected error", status=status.HTTP_500_INTERNAL_SERVER_ERROR) And what I want is not to get email of this particular response (because I wanted it to be 500) I've also tried this way: from django.http import JsonResponse def give_me_error(request): return JsonResponse({'error': 'expected error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) But it also generates mail. Is there a way to have a view returning error 500 that will not trigger e-mail send? (without disabling the e-mail functionality system-wide) Per Django documentation: https://docs.djangoproject.com/en/4.0/howto/error-reporting/ When DEBUG is False, Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater)