Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display multiple django database models in a flex box row?
So just to give some information, I know how flexbox works and sorta know how django works and have displayed django database models on a page before already, using a loop. The issue I've encountered is I want to have multiple (three) of these models on a row kinda like if I used a flex box with three divs inside except because of the way the loop is running all three divs are the same. Any ideas on how to change the code for the divs to all be different models? Here is my code : Here is my item-store.html (Html Page to display the items) : {% for item in items %} <div class="triple-item-container"> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> <div class="single-item-container"> <div><p>{{item.name}}</p></div> <div><p>{{item.details}}</p></div> </div> </div> {% endfor %} Here is my item-store.css (Css Page linked to the Html Page) : .triple-item-container{ margin-top: 300px; height: 200px; display: flex; flex-direction: row; justify-content: space-around; } .single-item-container{ padding: 10px; background-color: rgb(226, 215, 113); } Here is my models.py in case you need it : class item(models.Model): name = models.CharField(max_length=100, blank=False, null=False) details = models.CharField(max_length=1000, blank=True, null=True) price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=20) tag_choices = ( ('bakery', 'bakery'), ('meat&seafood', … -
почему сериализатор меняет имя автора , на его айди? [closed]
Comments models.py class Comments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Posts, on_delete=models.CASCADE) text = models.CharField(max_length=500) created = models.DateTimeField(auto_now=True) class META: fields = ['author', 'post', 'text', 'created']` user models.py class User(AbstractUser): status = models.CharField(max_length=120, default='it\s a default user status', null=False) avatar = models.ImageField(upload_to='Network_/static/avatar/') views.py def get_post(self): post = Posts.objects.get(id=self.GET.get('post_id')) post_likes_len = len(Like.objects.filter(product=post)) like_icon = "/static/image/likeHearthicon.png" if Like.check_user_liked(self, user=self.user, post=post): like_icon = "/static/image/likeHearthicon_after.png" post_comments = Comments.objects.filter(post=post) return JsonResponse({ 'post': serializers.serialize('json', [post]), 'Likes':post_likes_len, 'like_icon': like_icon, 'comments': serializers.serialize('json', post_comments) }, safe=False ) Я новичок в dango, и не совсем понимаю что , и из-за чего меняет имя автора комментария на его айди. до этого действия (serializers.serialize('json', post_comments)) все выводиться нормально : 'Test_user_3' но после сериализации вместо 'Test_user_3' я получаю '3' то есть айди может кто-нибудь обьяснить , или хотя бы кинуть ссылку для того чтобы моя ветряная башка хоть что-то поняла -
Django : Dynamically set dropdown options based on other dropdown selection in Django Model Forms
This is a common scenario in frontend where we want a dropdown options set with respect to another selection in another dropdown, but not getting a solution in django admin forms Scenario : django model: class CompanyEmployee(): """ An Emailed Report """ company = models.ForeignKey(Company, on_delete=models.CASCADE, ) employee = models.ManyToManyField(Employee, blank=True, verbose_name='Employes',) class Meta: unique_together = ( ('company', 'name'), ) so in CompanyEmailAdminForm company is in list_filter and Employee as filter_horizontal, that means company is a dropdown and employee as filter with multiple choice. The queryset for employee widget if instance.pk: self.fields['employee'].queryset =Employee.objects.filter(company=instance.company) else: self.fields['employee'].queryset =Employee.objects.all() Company and Employee have a relation. So from company I can get the related Employee records. The issue is in add form where I don't have a saved instance. My requirement is when I select a company say 'ABC' I should get only records related to 'ABC' in the Employee filter. If onChange i can get the value back in the form I can re-evaluate the employee queryset. With django.JQuery the values in the employee section is not remaining permanently. -
How to get "captured values" from a url in get_absolute_url model in django
I have this url: path('<slug:slug>/<slug:product_slug>_<int:pk>/', ProductDetailView.as_view(), name='detail'), and I need access to < slug:slug > in product's get_absolute_url, this slug can be any of user's slug, is not from products. Is for generate the products breadcrumb urls like this: /user-slug/product-slug_product-id/ def get_relative_url(self): return reverse('custom_catalogue:detail', kwargs={ slug: kwargs['slug']??, 'product_slug': self.slug, 'pk': self.id}) any help I will appreciate -
Django ORM: calculation only inside databse-query possible?
I have rather simple dataset that's containing the following data: id | aqi | date | state_name 1 | 17 | 2020-01-01 | California 2 | 54 | 2020-01-02 | California 3 | 37 | 2020-01-03 | California 4 | 29 | 2020-01-04 | California What I'm trying to achieve is the average aqi (air-quality-index) from april 2022 minus the average aqi from april 2021, without using multiple queries. Is this even possible or should I use two queries and compare them manually? From my understanding, I should use the Q-Expression to filter the correct dates, correct? AirQuality.objects.filter(Q(date__range=['2021-04-01', '2021-04-30']) & Q('2022-04-01', '2022-04-30')) Thanks for your help and have a great day! -
Why only 1 value is bound?
The meaning of the program is to select analogues from the list and link them. I always bind only 1 value (to itself). How to fix it My view: def editpart(request, id, **kwargs): if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analogs_zap in analogs: zap = analogs_zap.analog part.analog.add(part.id) My model: class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') -
Pytest: Test user-editing view, object is not updating
I want to test my account_edit view, if the user's/customer's info is being updated properply. I'm new to pytest. View: @login_required def account_edit(request): if request.method == "POST": user_form = UserEditForm(instance=request.user, data=request.POST) if user_form.is_valid(): user_form.save() else: user_form = UserEditForm(instance=request.user) return render(request, "account/user/edit_account.html", {"user_form": user_form}) Factory: class CustomerFactory(factory.django.DjangoModelFactory): class Meta: model = Customer django_get_or_create = ("email",) email = "user1@gmail.com" name = "user1" mobile = "123456789" password = "user1" is_active = True the test_account_views.py: @pytest.mark.django_db def test_account_edit_post(client, customer_factory): user = customer_factory.create() client.force_login(user) response = client.post( "/account/edit/", data={ "name": "newname", "email": "newemail@gmail.com", }, ) print(user.name) assert response.status_code == 200 When Im printing out the email print(user.name) Im expecting it to be updated with newname. However receiving the old one (user1) AND the response status is also OK: 200. So it seems the problem is just that the user isn't updating. The problem is with testing code, not the django app itself(checked it). Thanks in advance for any help. -
Django models. Get all objects and sum duplicates
I have table in MySQl which describe Retail Demand models. row_num full_name quantity 1 4Пивовара - Похищение человеков инопланетянами (IPA - White. OG 17%, ABV 7,5%, IBU 67) 1 2 AF Brew - Autumn Fever Dreams: November (Sour - Fruited. ABV 7%) 1 3 Big Village - ABC-Kölsch (Kölsch. ABV 5.5%, IBU 20) 1 4 Big Village - Distrust (Pale Ale - New England. OG 15%, ABV 6%, IBU 25) 1 5 Big Village - Imaginarium (IPA - American. OG 16%, ABV 7%, IBU 60) 1 6 Big Village - Quartet X (Belgian Quadrupel. ABV 12,5%) 1 7 Gravity Project - It's A Mango (Cider - Other Fruit. ABV 5%) 1 9 Jaws - APA (Pale Ale - American. OG 13,5%, ABV 5%, IBU 43) 2 10 Jaws - Pale Ale (Pale Ale - English. OG 13%, ABV 5,2%, IBU 25) 1 11 Jaws - Pale Ale (Pale Ale - English. OG 13%, ABV 5,2%, IBU 25) 1 12 Jaws - Populism [Mosaic] (IPA - New England. OG 15%, ABV 6,5%, IBU 20) (Банка 0,45) 1 13 Jaws - Атомная Прачечная (IPA - American. OG 16%, ABV 7,2%, IBU 101) 4 14 Saldens - American Pale Ale Tears of Liberty … -
core error - Script timed out before returning headers: wsgi.py
I'm running a Django app on Apache/2.4.6 (CentOS) with mod_wsgi. When I visit my domain, after few minutes I get "Internal Server Error". The log file shows the following error - [core:error] [pid 9361] [client 132.72.41.107:55906] Script timed out before returning headers: wsgi.py The config file in sites-enable folder - <VirtualHost *:80> ServerName www.meshi1.cs.bgu.ac.il ServerAlias meshi1.cs.bgu.ac.il DocumentRoot "/var/www/meshi1.cs.bgu.ac.il" ErrorLog /var/www/meshi1.cs.bgu.ac.il/log/error.log CustomLog /var/www/meshi1.cs.bgu.ac.il/log/requests.log combined Alias /static /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/static <Directory /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/static> Require all granted </Directory> WSGIDaemonProcess djangonautic python-home=/home/cluster/orelhaz/bin/rom_deshe/myenv/lib/python3.6 WSGIProcessGroup djangonautic WSGIScriptAlias / /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/djangonautic/wsgi.py <Directory /home/cluster/orelhaz/bin/rom_deshe/djangonautic1/djangonautic> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Thanks! -
Nested Array search in MongoDB/PyMongo while using aggregate
I am trying to search for a keyword inside array of arrays in a mongo document. { "PRODUCT_NAME" : "Truffle Cake", "TAGS": [ ["Cakes", 100], ["Flowers", 100], ] } Usually, i would do something like this and it would work. db.collection.find( {"TAGS":{"$elemMatch":{ "$elemMatch": {"$in":['search_text']} } }} ) But now, I changed this query to an aggregate based query due to other requirements. I've tried $filter , $match but not able to replicate the above query exactly.. Can anyone convert the above code so that it can directly work with aggregate? (I use PyMongo) -
Newer version of botocore breaks integration test
Imagine the follow functions, that should upload and copy something to S3 class TestAttachments(TestCase): # YAML is the only serializer supporting binary @override_env(AWS_DEFAULT_REGION='eu-west-1') # So the test doesn't fail depending on env. vars @my_vcr.use_cassette(serializer='yaml') def test_copy_attachments_to_sent_folder(self): with self.assertRaises( CopyAttachmentException, msg="Failed to copy attachments to sent folder for attachment URL: http://example.com/foo.jpg" ) as cm: copy_attachments_to_sent_folder(["http://example.com/foo.jpg"]) self.assertEqual(cm.exception.__cause__.__class__, InvalidAttachmentURL) TEST_UUIDS = ["uuid_0"] with patch.object(uuid, 'uuid4', side_effect=TEST_UUIDS): result = copy_attachments_to_sent_folder([ f"https://{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}.s3.amazonaws.com/attachments/Test+video.mov" ]) self.assertEqual( [AttachmentMetadata( s3_key=f"attachments/sent/{TEST_UUIDS[0]}/video/quicktime/Test video.mov", filename="Test video.mov", mime_type="video/quicktime", size=178653, )], result ) It should test the following function: def copy_attachments_to_sent_folder(urls: List[str]) -> List[AttachmentMetadata]: # Copy the attachment to the sent folder in parallel with futures.ThreadPoolExecutor(max_workers=4) as executor: urls_by_future = {executor.submit(copy_attachment_to_sent_folder, url): url for url in urls} results_by_url = {} for future in futures.as_completed(urls_by_future.keys()): try: results_by_url[urls_by_future[future]] = future.result() except Exception as e: raise CopyAttachmentException( f"Failed to copy attachments to sent folder for attachment URL: {urls_by_future[future]}" ) from e # The futures can complete out-of-order, so we need to re-order them to match the original order here return [results_by_url[url] for url in urls] Which finally uses this function inside: def copy_attachment_to_sent_folder(url: str) -> AttachmentMetadata: aws_session = attachments_aws_session() s3_client = aws_session.client("s3") parse_result = urlparse(url, allow_fragments=False) # Allow both with/without AWS region in hostname attachment_hostname_regex = fr"{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}\.s3\.(.+?\.)?amazonaws\.com" … -
How to use for loop inside map python
I have a function that returns a list of numbers. But I know in other languages like JS we don't need to set a variable like c = 0. I see about map in python but I don't know how can I do it Here is my function: def get_bought_passenger_count(self): c = 0 for book in self.bookings.all(): c += book.passenger_count return c I want to do this with map function -
Django orm for multiple foreign key
I have a existing old database and I am trying to join 3 tables with django orm: class Orderlist(models.Model): record = models.IntegerField(db_column='RECORD', unique=True, primary_key=True) vechileid = models.CharField(db_column='vechileid ', max_length=10, blank=True, null=True) class Orderitem(models.Model): ' ' orderid= models.ForeignKey('Orderlist', models.DO_NOTHING, db_column='ORDERID', blank=True, null=True) ' ' class Vehicle(models.Model): ' ' vechileid = models.ForeignKey('Orderlist', models.DO_NOTHING, db_column='vechileid ', blank=True, null=True) ' ' I am trying to join as below: Select ... from Orderlist LEFT OUTER Orderitem ON Orderlist.record=Orderitem.orderid, LEFT OUTER JOIN Vehicle ON Orderlist.vechileid =Vechile.vechileid WHERE ... every time i try to join orderlist and vehicle it joins as orderlist.record=vehicle.vechileid How can i write the above sql query into django orm? -
Django: "SELECT field, count(field) FROM table GROUP BY field" being field an object
I've got next issue. Having next tables: products_table: id product_type serial_number 1 1 FX2002 2 1 FX2003 3 2 FX2004 4 2 FX2005 5 2 FX2006 product_types_table: id element 1 laptop 2 mouse 3 screen In products_table, product_type is a foreign key to product_types_table. I need to execute next query: SELECT product_type, count(product_type) AS quantity FROM products_table And get: product_type quantity 1 2 2 3 I've tried: queryset = products_table.objects.all().values("product_type").annotate(quantity=Count("product_type")) What returns next queryset: [{'product_type':1, 'quantity':2}, {'product_type':2, 'quantity':3}] I need 'product_type' field to be an object instead of integer, so element field can be called as: element = queryset[0]['product_type'].element Getting 'laptop' if I print element variable. I need to convert this data into JSON as well, and I need next response: [ { id: 1, product_type: { id: 1, element: 'laptop' }, serial_number: 'FX2002' }, { id: 2, product_type: { id: 1, element: 'laptop' }, serial_number: 'FX2003' }, { id: 3, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2004' }, { id: 4, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2005' }, { id: 5, product_type: { id: 2, element: 'mouse' }, serial_number: 'FX2006' } ] How can I do it??? Thank all of you for your time. -
Django - database exception - custom exception handler
Does Django provide a possibility to implement a custom exception handler over the database layer? I want to catch database exceptions, check error codes, and on some error codes -> wait for a while and retry the query. Is it possible in the Django? -
Two variables in single url pattern without '/'
I want to add 2 variables in single url pattern without '/' like this /<location-name>-<cityname>/. both are slugs. Location name can have 2-3 words and city name also can have 1-4 words. I tried path(/<location-name>-<cityname>/,..) but django is taking last word as city and rest as location. Like If I try /location-name1-city-name2/ then location-name-city is location and name2 is city. How can I do this? -
How to fix 'ManyToManyDescriptor' object has no attribute 'add'?
My viev def editpart(request, id, **kwargs): PartAllView = Part.objects.order_by('-id') part = Part.objects.get(id=id) form = PartForm(request.POST, request.FILES) if request.method == 'POST': part.name = request.POST.get("name") part.description = request.POST.get("description") analogs = Part.objects.all() for analogs_zap in analogs: zap = analogs_zap.analog Part.analog.add(Part.id) My model class Part(models.Model): name = models.CharField('Название', max_length=100) analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') -
No module named ldap.filter in /usr/local/lib/python3.8/dist-packages/django_auth_ldap/config.py
This error occurs when i was trying to set up a new django project intergreted with django_auth_ldap in Ubuntu server, the environment & prerequisite for ldap are all installed successfully.The other project on the same server runs properly with no issues. Really need help full error message below: Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/ldap/project/ldap/ldap/settings.py", line 17, in <module> from django_auth_ldap.config import LDAPSearch File "/usr/local/lib/python3.8/dist-packages/django_auth_ldap/config.py", line 36, in <module> import ldap.filter ModuleNotFoundError: No module named 'ldap.filter' During handling of the above exception, another exception occurred: … -
Point is not showing on a right place in admin panel while using geodjango?
I have taken my current location longitude and latitude from google Map. And when I'm adding an entry with that log/lat value. The pointer is not identifying the right place. As you can see in the pictures below. This is how I'm adding point in db. Profile.objects.create( owner=obj.owner, name=obj.ground_name, phone_no=obj.phone_no, location=GEOSGeometry('POINT (31.520370 74.358749)', srid=4326), address=obj.address, state=obj.state, city=obj.city, country=obj.country ) on admin panel on google map -
Request URL: Category 404
I have, Page not found (404) I can't know where is the mistake I made. urls.py from .views import ( PostListView, PostListViewHome, CategoryView, ) from . import views urlpatterns = [ path("", PostListViewHome.as_view(), name="Blog-home"), path("category/<str:cats>", views.CategoryView, name="category"), ] views.py def CategoryView(request, cats): return render(request, 'category.html', {'cats':cats}) -
Blacklist token not working in JWT Django?
My view is like this class LogoutView(APIView): permission_classes = (permissions.AllowAny,) authentication_classes = () def post(self, request): try: refresh_token = request.data["refresh_token"] token = RefreshToken(refresh_token) token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) My url config is urlpatterns = [ path('logout/', LogoutView.as_view(), name='logout') ] When i call this api I get bad request error. I also tried using auth logout view but i get this Forbidden (Origin checking failed - chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop does not match any trusted origins.): logout/ -
How to remove date in pandas dataframe
How to remove date in datetimeformat 2022-06-20 14:59:02.559748+05:30 (14:59:02) #only time df = pd.DataFrame(queryset) df['duration'] = pd.to_datetime(df['stoptime']) - pd.to_datetime(df['starttime']) print(df['duration'] ) # "0 days 00:00:09.892016" TO 00:00:09 -
How to redirect after add/edit/delete in django
when i try to redirect after add/edit/delete operation i'm redirecting to the page i wanted but can not see the existing data, but after click on url section of browser and tap enter on it or go to other page and return to this one than it is showing me the data. Let me share a video link of deleting records. - https://drive.google.com/file/d/1Qyt_gxFoBe74DH_2rLbme9PD58Ll1z3I/view?usp=sharing and here is the code of deleting too. views.py def deleteuser(request, id): # user = get_object_or_404(AddContact, id = id) user = AddContact.objects.filter(id=id).delete() context = { 'user' : user } return render (request, "adduser.html", context) URL.py path('deleteuser/<id>', views.deleteuser, name="deleteuser"), html button <a href="/deleteuser/{{vr.id}}" class="btn btn-danger" data-target="success-modal-delete"><span class="fa fa-trash"></span> Delete</a> -
Why doesn't it print logs to the file?
Please tell me why it does not print a 404 error to a file? It is output to the console, but the file is empty Not Found: / [21/June/2022 11:52:02] "GET / HTTP/1.1" 404 2178 LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'special': { '()': 'project.logging.SpecialFilter', 'foo': 'bar', } }, 'handlers': { 'console':{ 'class':'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'class':'logging.FileHandler', 'formatter': 'verbose', 'filename': 'information.log' }, }, 'loggers': { 'main': { 'handlers':['console','file'], 'propagate': True, 'level':'INFO', } } } -
Django 4: problem with auth.authenticate, it returns None
I continue my progression with Django 4. But I have a new problem. my login code does not work, yet I followed the doc (I believe). The problem is at this level in my view.py. user=auth.authenticate(email=email, password=password) it returns none Could someone explain to me why the code does not work. Did I forget something? Here is my html code {% extends 'base.html' %} {% block content %} <section class="section-conten padding-y" style="min-height:84vh"> <div class="card mx-auto" style="max-width: 380px; margin-top:100px;"> <div class="card-body"> <h4 class="card-title mb-4">Sign in</h4> {% include 'includes/alerts.html' %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input type="email" class="form-control" placeholder="Email Address" name="email"> </div> <!-- form-group// --> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" name="password"> </div> <!-- form-group// --> <div class="form-group"> <a href="#" class="float-right">Forgot password?</a> </div> <!-- form-group form-check .// --> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block"> Login </button> </div> <!-- form-group// --> </form> </div> <!-- card-body.// --> </div> <!-- card .// --> <p class="text-center mt-4">Don't have account? <a href="{% url 'register' %}">Sign up</a></p> <br><br> </section> {% endblock %} and my view code def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if user is not None: auth.login(request, user) # messages.success(request, …