Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading Images with Wagtail on Google App Engine causes OSError: [Errno 30] Read-only file system
I am trying to run a wagtail site on the Google Cloud App Engine standard environment using a cloud instance of mySQL. I followed the documentation provided here: https://cloud.google.com/python/django/appengine Almost everything is working except for when users upload images. When a user uploads an image to the deployed site a 500 error is reported to the user, and the error log shows "OSError: [Errno 30] Read-only file system". When I run the site locally using the cloud SQL proxy this error does not occur, and I am able to upload images just fine. Can you advise me on why this would happen, and what to change to avoid this error in deployment? Thank you in advance! -
write all possible requests elasticsearch-dsl django
Is there a way to write all possible requests elasticsearch-dsl where the user enters the field names and their values? I suggested the following class diagram: i created this models in models.py file : class Rules(models.Model): id_rule = models.AutoField(primary_key=True) rule_name = models.CharField(max_length=200, null=False, blank=False) rule_description = models.CharField(max_length=99999, null=False, blank=False) status = models.CharField(max_length=200, null=False, blank=False) operator_choices = ( ('1', '='), ('2', '<>'), ('3', 'gt'), ('4', 'lt'), ('5', 'gte'), ('6', 'lte'), ) class AttributeClause(models.Model): id_AttributeClause = models.AutoField(primary_key=True) rule = models.ForeignKey(Rules, on_delete=models.CASCADE) attribute = models.CharField(max_length=200, null=False, blank=False) valeur = models.CharField(max_length=200, null=False, blank=False) operator = models.CharField(max_length=10, choices=operator_choices, default='1') operator_logic_choices = ( ('1', '|'), ('2', '&'), ('2', '~'), ) class Relation(models.Model): clause = models.ForeignKey(AttributeClause, on_delete=models.CASCADE) operator = models.CharField(max_length=10, choices=operator_logic_choices, default='1') I want an idea like this PS: This code is not correct, it is just the idea def Create_rule(): Rules =Rules.objects.all() for r in Rules : result="result = table.search()" clause =AttributeClause.objects.all().filter(rule=r) for c in table_clause : if c.opperateur =='=' : result.append(".filter(Q('match',",c.attribute,"=",c.value,")") else : if c.opperateur =='lg' : result.append(".filter(Q('range',",c.attribute,"={'gt':",c.value,"})") else : if c.opperateur =='lt' : result.append(").filter(Q('range',",c.attribute,"={'lt':",c.value,"})") else : if c.opperateur =='lte' : result.append(").filter(Q('range',",c.attribute,"={'lte':",c.value,"})") else : if c.opperateur =='gte' : result.append(").filter(Q('range',",c.attribute,"={'gte':",c.value,"})") else result.append(").exclude('match', ",c.attribute,,"=",c.value,")") last=True for rel in table_relation: if rel.clause == c.id : result.append(rel.operateur) last= False … -
How to resize RichTextUploadingField in Django Page
I am trying to apply RichTextUploadingField to my front end page and the text field is extended out of the column and container that I have set. How do I resize it to fit into the container? Here is an image of what I mean so that it can help explain what I mean -
django overriding serializer save() method
As I showed in image below, I want to select my favourite items and add it to favourite array. There should be more than 100+ items and every selected item should be store. But Now only last selected item is storing, it replaces others. I think I need to override serializer save method! But how? Can you guys help me please!!! Here is my code models.py class Item(models.Model): name = models.CharField(max_length=200) description = models.TextField(null=True) cost = models.FloatField(null=True) categories = models.ManyToManyField('Category') publishDate = models.DateTimeField(auto_now_add=True, null=True) image = models.ImageField(null=True, upload_to=item_image_file_path) views = models.IntegerField(null=True) def __str__(self): return self.name class RegularAccount(models.Model): username = models.CharField(max_length=200) dateCreated = models.DateTimeField(auto_now_add=True, null=True) favourites = models.ManyToManyField('Item') logo = models.ImageField(null=True, upload_to=regularaccount_logo_file_path) phone = models.CharField(max_length=200, null=True) def __str__(self): return self.username serializers.py class FavouriteItems(serializers.ModelSerializer): """Serializer for FavouriteItems""" favourites = serializers.PrimaryKeyRelatedField( many=True, queryset=Item.objects.all() ) class Meta: model = RegularAccount fields = ('id', 'favourites',) views.py class RegularAccountViewSet(viewsets.ModelViewSet): #Code UNTIL elif self.action == 'select_favorites': not important """Manage RegularAccount in the DB""" serializer_class = serializers.RegularAccountSerializer queryset = RegularAccount.objects.all() def get_queryset(self): """Get queryset""" return self.queryset def get_serializer_class(self): """Return appropriate serializer class""" if self.action == 'retrieve': return serializers.RegularAccountSerializerDetail elif self.action == 'upload_image': return serializers.RegularImageSerializer ##UNTIL HERE IMPORTANT elif self.action == 'select_favorites': return serializers.FavouriteItems return self.serializer_class def perform_create(self, serializer): … -
How can I check if element is in Class.models.all()?
I want to check if some elements are in objects.all or not. I have class Profile which objects.all are <QuerySet [<Profile: firstuser Profile>, <Profile: seconduser Profile>]>. So I want to know if there is my element in HTML jinja templates. -
Bad performance of update() on sliced query in Django with postgres - are there better solutions?
I'm using PostgreSQL 12 and Django 3 as an ORM I noticed slow query performance when updating a lot of database rows at once with update() Example application to illustrate: Items need to be reserved by a reservation system, when an item is available its status has a value 'A', when reserved 'R'. The reservations are in bulk (1000 up to 100rd of thousands of items at the time). Django snippet (note I cannot use update on the queryset directly since it has been sliced): with transaction.atomic(): items = Item.objects.select_for_update().filter(status='A')[:1000] Item.objects.filter(pk__in=items).update(requester=r, status='R') The following query is generated and takes up to 4 seconds to execute on my test environment for (only) updating 1000 items (it takes more than 1h for updating 1M items). UPDATE "item" SET "requester_id" = 16, "status" = 'R' WHERE "item"."id" IN ( SELECT U0."id" FROM "item" U0 WHERE U0."status" = 'A' LIMIT 1000 FOR UPDATE ) I was wondering if there are better approaches to this problem, any suggestions for improving performance? (besides optimizing the hardware and executing asynchronously/parallel). -
How to convert Python io.BytesIO-object to file-like object? [closed]
I have a temporary file using Python TempFile which is served via Http. Problem is when the FileResponse (which is a subclass of StreamingHttpResponse) is returned and streams the file to the client, the tempfile library tries to "garbage collect" and delete the temporary file, while it is still open in "read binary" mode. So I am using to Python io.BytesIO to load the entire file into memory, so i can close the temporary file and still stream its content. A short snippet looks like this: (...) song = open(song_path, "rb") song_buffer = io.BytesIO(song.read()) song.close() response = FileResponse(song_buffer) return response This approach however, just sends the binary data, and not a file. So how would you make sure a file is sent? Any ideas for other approaches also very welcome. -
Django Server not starting
Greetings!! I am using django for a month.Everything was okay.But today when I run this py manage.py runserver It output nothing.Rather than it again shows the command line.It is first time having this problem after I started django.Please fix this problem and help me to start my django server again!!! -
How to fix NoReverseMatch error in Django table for a delete button
Python version 3.7.7 and Django version 2.2.3. Code on Github https://github.com/jcwill415/Stock_Market_Web_App I want to add a delete button in the last column of a table. When the code is outside of the table, it works to delete an entry from the table. But when the code is inside the table, I receive a NoReverseMatch error that says: NoReverseMatch at /add_stock.html Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<stock_id>[^/]+)$'] Request Method: GET Request URL: http://localhost:8000/add_stock.html Django Version: 2.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<stock_id>[^/]+)$'] Exception Location: C:\djangostock\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: C:\djangostock\venv\Scripts\python.exe Python Version: 3.7.7 Python Path: ['C:\\Users\\JCW\\Desktop\\Stock_Market_Web_App-master\\stock', 'C:\\Users\\JCW\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\JCW\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib', 'C:\\Users\\JCW\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Program Files\\Python37', 'C:\\djangostock\\venv', 'C:\\djangostock\\venv\\lib\\site-packages'] add_stock.html <table class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th scope="col">TICKER</th> <th scope="col">COMPANY</th> <th scope="col">STK PRICE</th> <th scope="col">PREV CLOSE</th> <th scope="col">MARKET CAP</th> <th scope="col">VOLUME</th> <th scope="col">YTD CHG</th> <th scope="col">52 WK HIGH</th> <th scope="col">52 WK LOW</th> <th scope="col">REMOVE STK</th> </tr> </thead> <tbody> {% if ticker %} {% for list_item in output %} <tr> <th scope="row">{{ list_item.symbol }}</th> <td>{{ list_item.companyName }}</td> <td>${{ list_item.latestPrice }}</td/> <td>${{ list_item.previousClose }}</td> <td>${{ list_item.marketCap }}</td> <td>{{ list_item.latestVolume }}</td> <td>{{ list_item.ytdChange }}</td> <td>${{ list_item.week52High }}</td> <td>${{ list_item.week52Low }}</td> … -
Pytest scope='module' fixture not delete model instance after testing module
I create the message instance in a fixture with scope='module', right in the test file. But when the test reaches another module, this message instance still exists in the database. in .../apps/dialogs/test/api/test_message.py @pytest.fixture(scope='module') def message_by_auth_user(django_db_setup, django_db_blocker, message_factory: type, user_factory: type, user_with_auth: User) -> Message: """Return message by auth user.""" with django_db_blocker.unblock(): message = message_factory(written_by=user_with_auth) # Message object (1) message_text = message.message # 'text_message_№_1' return message in .../apps/users/test/api/test_users.py @pytest.mark.django_db def test_get_users_view_with_filter(bool_value: bool, user_count_change: int, filter_pattern: str, api_auth_client: APIClient, user_with_auth: User, user_factory: type): message_count = Message.objects.all().count() # 1 message = Message.objects.first() # Message object (1) message_text = message.message # 'text_message_№_1' -
Python 3.8.5 docker alphine - CompileError: command 'gcc' failed with exit status 1
I'm running Django and Postgres with Docker. Just tried to add Celery to the project and I can't make it run. Dockerfile: FROM python:3.8.5-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ && apk add --no-cache openssl-dev libffi-dev RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ docker-compose.yml: version: '3' volumes: local_postgres_data: {} services: postgres: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - local_postgres_data:/var/lib/postgresql/data env_file: - ./.envs/.postgres django: &django build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app/ ports: - "8000:8000" depends_on: - postgres rabbitmq: image: rabbitmq:3.8.6 celeryworker: <<: *django image: celeryworker restart: always depends_on: - rabbitmq - postgres ports: [] command: celery -A pyrty worker -l INFO celerybeat: <<: *django image: celerybeat restart: always depends_on: - rabbitmq - postgres ports: [] command: celery -A pyrty beat -l INFO Errors: celerybeat_1 | [2020-08-16 17:12:54,206: WARNING/MainProcess] raise VerificationError('%s: %s' % (e.__class__.__name__, e)) celerybeat_1 | [2020-08-16 17:12:54,206: WARNING/MainProcess] cffi celerybeat_1 | … -
django not running with dotenv
I am going to run django project but it is not working because of dotenv. I have virtualenv activated I am getting this error! Traceback (most recent call last): File "manage.py", line 8, in <module> dotenv.read_dotenv('.env') File "/home/test/projects/cname/test_pro/.env/lib/python3.8/site-packages/dotenv.py", line 57, in read_dotenv with open(dotenv) as f: IsADirectoryError: [Errno 21] Is a directory: '.env' manage.py if __name__ == "__main__": dotenv.read_dotenv('') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) If anyone has encountered this kind of error of anyone who knows how to fix please help me with this issue! Your help would be appreciated Thanks in advance!!! -
How to add Wagtail Orderable object (gallery image) programatically?
I have the following Wagtail/Django models: class VenuePage(Page): name = models.CharField(max_length=255, blank=False, null=False) street_address = models.CharField(max_length=255, blank=False, null=False) city = models.CharField(max_length=50, blank=False, null=False) state = models.CharField(max_length=10, blank=False, null=False) zipcode = models.CharField(max_length=10, blank=True, null=False) phone = models.CharField(max_length=15, blank=True, null=False) website = models.URLField(blank=True, null=False) wiki_link = models.URLField(blank=True, null=False) capacity = models.CharField(max_length=8, blank=True, null=False) year_opened = models.CharField(max_length=4, blank=True, null=False) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None etc. ... class VenuePageGalleryImage(Orderable): page = ParentalKey( VenuePage, on_delete=models.CASCADE, related_name="gallery_images" ) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.CASCADE, related_name="+" ) caption = models.CharField(max_length=255, blank=True, null=False) image_author = models.CharField(max_length=255, blank=True, null=False) image_attrib_url = models.URLField(blank=True, null=False) etc. ... I have JSON data structured like so: { "capacity": "1424", "city": "New York City", "image_author": "The original uploader was Mademoiselle Sabina at English Wikipedia.", "image_filename": "Hirschfeldtheatre.jpg", "name": "Al Hirschfeld Theatre", "image_attrib_url": "https://en.wikipedia.org/wiki/File:Hirschfeldtheatre.jpg", "state": "New York", "street_address": "302 W. 45th St.", "wiki_link": "https://en.wikipedia.org/wiki/Al_Hirschfeld_Theatre", "year_opened": "1924" }, I am trying to add the JSON data to my database by applying it to the above models. I have the files stored locally. I am using the following custom command: import json import requests from io import BytesIO from django.core.management.base import BaseCommand from django.core.files.images import ImageFile from django.template.defaultfilters import slugify from wagtail.core.models … -
Bokeh + Holoviews: Input must be a Model, a Document, a Sequence of Models and Document, or a dictionary from string to Model and Document
I am trying to set up a Sankey chart as described here: https://holoviews.org/reference/elements/bokeh/Sankey.html While trying to set this up on Django platform, I am running into some issues to get it rendered properly. import holoviews as hv from holoviews import opts, dim hv.extension('bokeh') def sankey(request): hv.extension('bokeh') # mappings = [(0,1,12), (0,2,13)] p = hv.Sankey(mappings) script, div = components(p) return render(request, 'pages/base.html', {'script': script, 'div': div}) However, I am running into the following error: ValueError: Input must be a Model, a Document, a Sequence of Models and Document, or a dictionary from string to Model and Document My html includes {{ div | safe }}, and I have non-Holoviews graphs that work just fine (just Bokeh). I have read around that maybe I need to render it first, but I am just unsure on how to do it with my current setup. Any ideas? -
NoReverseMatch found in django for app homepage
I am trying to redirect an link from app to another page view function. But after pointing the page correctly I am getting NoReverseMatch Found error on apps main page which haves no connection to it. This is urls.py of main Project urls.py urlpatterns = [ path('', views.home, name="home"), path('admin/', admin.site.urls), path('teacher/', include('teacher.urls')), path('student/', include('student.urls')), ] This is urls.py for respective app which is teacher urls.py urlpatterns = [ path('', views.index, name="index"), path(r'^detailed/(?P<reportid>\d{0,4})/$', views.detailed, name="detailed"), ] I am also including views.py as error is pointing at view.py views.py def index(request): return render(request, 'teacher/report.html') def detailed(request): weeklyr = wreport.objects.all() dailyr = dreport.objects.all() split = SplitOfWeek.objects.all() return render(request, 'teacher/detailed.html') I have tried adding r'^teacher/$' at main urls.py and r'^$' at urls.py of teacher app but after adding it shows there is url found for teacher. This is the detailed error message: Reverse for 'detailed' with no arguments not found. 1 pattern(s) tried: ['teacher/\\^detailed/\\(\\?P(?P<reportid>[^/]+)\\\\d\\{0,4\\}\\)/\\$$'] -
A NameError doing a Product class in views.py at product/1/new
I am doing a Product application, to which I got an error. The error says that redirect is not defined at line 29 in my views.py file. Here is my views.py file from django.contrib.auth.models import User from django.shortcuts import render,get_object_or_404 from .forms import NewProductForm from .models import Product # Create your views here. def home(request): products = Product.objects.all() return render(request, 'home.html', {'products': products}) def product_topics(request, pk): product = get_object_or_404(Product, pk=pk) return render(request, 'topics.html', {'product': product}) def new_product(request, pk): product = get_object_or_404(Product, pk=pk) user = User.objects.first() if (request.method == 'POST'): form = NewProductForm(request.POST) if(form.is_valid()): product = form.save(commit = False) product.starter = user product.save() return redirect('product_topics',pk=product.pk) else: form = NewProductForm() return render(request, 'new_product.html', {'product': product, 'form': form}) What does this error mean, and can you show me how to fix it? -
Printing User Model Attributes on the Navigation Bar
I am trying to print the first name and company name on the navbar but it does not print anything out base.html <nav class="navbar navbar-expand-lg navbar-light bg-lightgrey"> <div class="collapse navbar-collapse" id="navbarNav"> {% if request.user.is_authenticated and request.user.is_student %}: <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'jobs' %}">Jobs</a> </li> </ul> <ul class="navbar-nav ml-auto"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{student.first_name}} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">My Account</a> <a class="dropdown-item" href="#">Change Password</a> <a class="dropdown-item" href="{% url 'logout' %}">Logout</a> </div> </li> </ul> </ul> {% elif request.user.is_authenticated and request.user.is_employer %}: <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Posts</a> </li> <li class="nav-item"> <a class="nav-link" href="jobs-create">Add Jobs</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Students</a> </li> </ul> <ul class="navbar-nav ml-5"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{employer.company_name}} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">My Account</a> <a class="dropdown-item" href="#">Change Password</a> <a class="dropdown-item" href="{% url 'logout' %}">Logout</a> </div> </li> </ul> </ul> {% else %}: <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a> </li> </ul> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a … -
want to pass name of movie while creating new post in django
as i want to pass the name of movie in the create form in the name fields #views.py class PostCreateView(LoginRequiredMixin,CreateView): model = Post context_object_name = 'posts' fields = ['title', 'content','name'] def form_valid(self, form): form.instance.name = self.request.movies return super().form_valid(form) in this i passed the url links urls.py urlpatterns = [ path('user/<str:username>/', UserPostListView.as_view(), name='user-post'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('', MoviesListView.as_view(), name='blog-home'), path('<str:name>/',MoviesDetailListView.as_view(), name='movies-detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about'), ] in this i created all the models and foreign keys models.py class Movies(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100,blank=True,null=True) producer = models.CharField(max_length=100) director = models.CharField(max_length=100) date_released = models.DateTimeField(default=timezone.now) image = models.ImageField(default='default.jpg', upload_to='profile_pics') class Meta: verbose_name_plural = "Movies" def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ForeignKey(Movies, on_delete=models.CASCADE) def __str__(self): return self.title # return reverse('post-detail' , kwargs={'pk':self.pk}) def get_absolute_url(self): return reverse('blog-home') from here i added the button for the post-create post_list.html {% extends "blog/base.html" %} {% block content %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <h1 class="mb-3">Post of {{ view.kwargs.name }} ({{ page_obj.paginator.count }})</h1> <a href="{% url 'post-create' %} "><button class="btn"><i class="fa fa-plus"></i> Add Review</button></a> <style> .btn { background-color: DodgerBlue; border: none; color: white; padding: 12px 16px; font-size: … -
Django rest framework, PUT and Patch creates new objects instead of updating them
I'm trying to make Patch/Put requests on a model with a foreign key. I'm overriding the create and update methods in order to update the instance: class CowManagementSerializer(serializers.ModelSerializer): group = serializers.CharField(required=True, allow_null=False) class Meta: model = Cow fields = ['management_id', 'eid_number', 'group'] def validate(self, attrs): return attrs def create(self, validated_data): try: group_id = validated_data['group'] eid_number = validated_data['eid_number'] management_id = validated_data['management_id'] print(group_id) group = Group.objects.get(group_id=group_id, farm__user=self.context['request'].user) Cow.objects.create(group=group, eid_number=eid_number, management_id=management_id) return validated_data except Group.DoesNotExist: raise serializers.ValidationError("Group with this name does not exist!") def update(self, instance, validated_data): group_id = validated_data.pop('group') group = Group.objects.get(group_id=group_id, farm__user=self.context['request'].user) instance.group = group instance.management_id = validated_data['management_id'] instance.eid_number = validated_data['eid_number'] instance.save() return instance making a patch or put a request just creates another object with the same data. sending the same request returns: { "eid_number": [ "cow with this eid number already exists." ] } Which makes sense because a new object was created. -
Why I have the method get instead of post?
I have a website using http and everything was working but now I update http to https protocol and I get the following problem into celery task : b'{"detail":"Method \\"GET\\" no allowed."}' This is my line using post : requests.post('https://localhost/api/update', data=data, headers={'Content-Type': 'application/json'}) I don't understand why I have a problem with the GET method knowing that I use POST method. Could you help me please ? Thank you very much ! -
please how do I add new key - value pairs to a dictionary without overriding the existing key?
please how do I add new key - value pairs to a dictionary without overriding the existing key? I’m building a project requires users to give an answer that I will use as a key and value pair. Everything is working well but if a user make a mistake and enter a key that already exists, it will override the existing one. -
Trying to use property from child model in parent for charting
I am trying to use an order_total property summing the line items from a child in my django admin changelist. The order_total property displays correctly in my list view, but does not work in the chart function. What I am doing wrong? models.py class Order(models.Model): class Meta: ordering = ['date_needed'] date_ordered = models.DateField(blank=True, null=True,default=datetime.now) date_needed = models.DateField(blank=True, null=True,default=datetime.now) date_shipped = models.DateField(blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders') customer_order = models.CharField(max_length=100, blank=True, null=True) status = models.ForeignKey(Order_Status, on_delete=models.CASCADE) invoice_no = models.CharField(max_length=45, blank=True, null=True) tracking_no = models.CharField(max_length=45, blank=True, null=True) shipping_cost =models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) carrier = models.CharField(max_length=50, blank=True,null=True) service = models.CharField(max_length=100, blank=True,null=True) @property def order_total(self): l = [] for item in self.order_items.all(): p = self.customer.pricings.filter(offering=item.offering).first().price if self.customer.pricings.filter(offering=item.offering).first() is not None else item.offering.wholesale_price, l.append(p[0] * item.lbs) return sum(l) **admin.py** class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemInline] list_display = ['customer','order_number','order_total','date_ordered','status'] ordering = ['-date_ordered'] def changelist_view(self, request, extra_context=None): response = super(OrderAdmin, self).changelist_view(request, extra_context) filtered_query_set = response.context_data["cl"].queryset chart_data = ( filtered_query_set.annotate(date=TruncDay("date_ordered"), month=ExtractMonth('date_ordered')) .values("date", 'month') .annotate(y=sum("order_total")) .order_by("-date_ordered") ) -
Django admin panel lags and doesn't show anything
Today I've launched my Django project and saw a really weird behavior of Django admin panel. At the first sight, everything looks OK but as soon as I click on any model to view, I can't see anything. The most strange thing is that I've got no weird commits that could damage the contents of admin panel recently. The only commit could do that is updating Django to 3.1 version. I've already tried reinstalling Django and installing older versions but nothing works. Here is the typical admin panel homepage Here is what happens when I click on models I really need to know how to fix it as well as both me and my friend have this issue and we can't deal with it. -
added two search bar in django one search by id and other by name .Tried many ways but cannot do it if i try by id then i am not able to do with name
I have to make 2 search bars. I don't know how to add multiple fiels... match= Staff.objects.filter(id=srch1...) here how can I add name=srch1 over here after trying many ways I found it but the problem is all input here is string how to change it to int def search(request): # Catch the data and search in Staff model. if request.method=='POST': srch1 = request.POST['srch'] print(type(srch1)) if type(srch1)== int: match= Staff.objects.filter(id=srch1) if match : return render(request,'search.html',{'sr': match}) else: messages.error(request,'no results,found') elif type(srch1)== str: catch= Staff.objects.filter(name=srch1) if catch: return render(request,'search.html',{'sr': catch}) else: messages.error(request,'no results,found') else: return HttpResponseRedirect("/search") return render(request,"search.html") -
How to use parameters in DRF router
Hello guys so I came to realise that DRF ModelViewSet is a quick way to make rest views, I am trying to use parameters within the router url but the ViewSet does not detect the param Here is how my viewset looks class ClientRequests(ModelsViewSet): serializer_class = serializers.ClientRequestSerializer def get_queryset(self): return models.ClientRequest.objects.filter(cliend_id=self.request.kwargs.get('client_id') now I register the router as below router = DefaultRouter() router.register('/<int:client_id/requests', views.ClientRequests, basename='clients request api endpoint') urlpatterns=[ path('', include(router.urls)) Is this the right way to use restframework router and how can I pass paramters to the url when using router