Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling MPTTModel model that is child
I have 2 models, Lucrare and Deviz. Deviz is a MPTTModel and has ForeignKey reference to Lucrare. Deviz models will have this form: Chapter 1 -Subchapter 1 --SubSubchapter 1 ---Article 1 ---Article 2 ---Article 3 Chapter 2 -Subsubchapter1 --Article 1 --Article 2 And only the Chapter will have the foreignkey reference to Lucrare. models.py: class Lucrare(models.Model): name = models.CharField(default='',max_length=100,verbose_name="Name") class Deviz(MPTTModel): lucrare = models.ForeignKey(Lucrare, on_delete=models.CASCADE,default='',null=True) parent = TreeForeignKey('self', on_delete=models.CASCADE,null=True,blank=True) Name = models.TextField(default='',verbose_name="Name") Created a class based view for Lucrare views.py: class LucrareDetail(LoginRequiredMixin, DetailView): template_name = "proiecte/lucrare_detail.html" context_object_name = "lucrari" model = Lucrare def get_queryset(self, **kwargs): context = super().get_queryset(**kwargs) return context I do not understand how to use this part in the template so that I create a table with Deviz data referenced to my Lucrare model: {% load mptt_tags %} <ul> {% recursetree genres %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> -
why is the pip install django Why does it take so long? ''Installing collected packages" step?
I'm trying to pip install django but installation takes a long time "Installing collected packages" step? like 40 min $ python -m pip install django Collecting django Using cached Django-4.1.4-py3-none-any.whl (8.1 MB) Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB) Installing collected packages: sqlparse, asgiref, django -
How to execute django query from string and get output
I want to run a django query from a string and put the output into a variable i tried using exec('model.objects.all()') but i can't assign the output to a variable, i also tried using subprocess.run([sys.executable, "-c", 'model.objects.all()'], capture_output=True, text=True) but subrocess doesn't find the model -
how to reverse page after deleting any data in django?
i wanted to redirect my page to index after deleting row so i use ` return HttpResponseRedirect(reverse('index')) to reverse . i wanted thishttp://127.0.0.1:8000/indexbut it is showinghttp://127.0.0.1:8000/index/index` what is the proble please help me. this is my view.py ` def index(request): return render(request, "card/index.html") def delete(request, id): dishes = dish.objects.get(id=id) dishes.delete() return HttpResponseRedirect(reverse('index')) this is urls.py path('index', views.index, name="index"), path('check', views.check, name="check"), path('delete/<int:id>', views.delete, name='delete'), ` -
counter with date information from django with javascript
I have a project in django, I have a field called delivery_time in the database, this is a datetimefield. I want to take this value and use it in javascript to make a counter. The date I'm talking about comes as text in html, I can use it too. I don't know how to use a text written in html.  my code ss -
Ajax call for form
What is django-ajax-selects and how to use it? an example. I want to create a filter app that show filtered data as soon as possible when selected option from form selector. -
Django - Failed to load resource: the server responded with a status of 404 (Not Found)
I'm trying to deploy a Django app that works locally, but doesn't on my website. The Django index.html (template) is shown but the errors below are shown and no css / js is loaded. Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/js/main Failed to load resource: the server responded with a status of 404 (Not Found) - http://example.com/static/css/style.css Lines I think are relevant in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'src.pages' ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] How I include the files in index.html template {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> </head> <body> <script src="{% static 'js/main.js' %}"></script> </body> </html> App structure is as follows web_app/ ├── src/ │ ├── config/ │ │ └── settings.py │ ├── pages/ │ │ ├── static/ │ │ │ ├── css/ │ │ │ │ └── style.css │ │ │ ├── js/ │ │ │ │ └── main.js │ │ │ └── fonts/ │ │ ├── templates/ │ │ │ └── pages/ │ │ │ └── index.html │ │ ├── urls.py │ … -
Django template == condition on string doesn't work
I want to display in an email template some conditional informations but even if the {{ error }} confirms the value of my error is list index out of range , the condition is not applied and else is taken in account. I send to my (email) template this: views.py try: [...] except Exception as e: error_product_import_alert( {'order_increment_id': order_increment_id, 'product': item['sku'], 'error': e, 'request': request}) error_product_import_alert() def error_product_import_alert(context): product = context['product'] order_id = context['order_increment_id'] error = context['error'] sujet = f' Anomalie : Import SKU {product} ({order_id}) impossible ({error})!' contenu = render_to_string('gsm2/alerts/product_import_ko.html', context) [...] email template <p>--{{ error }}--</p> {% if error == 'list index out of range' %} <p><strong>Le produit est introuvable dans la base.</strong></p> {% else %} <p><strong>Erreur inconnue : veuillez contacter l'administrateur.</strong></p> {% endif %} Maybe my error is so big that I even can't see it. Is there one ? -
How do I visualize NetCDF files in Python using the Django framework?
How to visualize the netCDF files in python using Django Framework? I tried using Folium map, but it doesn't support JavaScript. JavaScript is required to interact with map, like on-click function, pagination, etc. While using JavaScript, I need to go with conversion of netCDF File to GEOJSON file. But, it takes lots of storage space. Is there any alternate method to proceed with my requirement? -
Django ORM LEFT JOIN SQL
Good afternoon) Please tell me, there is a foreign key in django models in the Foreign Key, when creating a connection, it creates a cell in the _id database by which it subsequently performs JOIN queries, tell me how to specify your own cell by which to do JOIN, I can't create tables in an already created database I need a banal simple LEFT JOIN without connection with _id. Or specify another cell in the database for JOIN instead of _id, for example CastleModels.id = ClanModels.hasCastle class ClanInfoModels(models.Model): clan_id = models.IntegerField() name = models.CharField(max_length=80) class Meta: db_table = 'clan_subpledges' managed = False class ClanModels(models.Model): clan_id = models.IntegerField() hasCastle = models.IntegerField(primary_key=True) class Meta: db_table = 'clan_data' managed = False class CastleModels(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=11) class Meta: db_table = 'castle' managed = False ordering = ['id'] need sql query = SELECT castle.name, castle.id, clan_subpledges.name as 'name_clan' FROM castle LEFT JOIN clan_data ON clan_data.hasCastle = castle.id LEFT JOIN clan_subpledges ON clan_subpledges.clan_id = clan_data.clan_id -
Weather Api Right/wrong city filter not working
Openweather api call replay same message with differnt 'cod' 200 (200 for city that exist) or 404(404 for city does not exist). it was easy to set if condittion if cod == 200: form.save() else: print("City does not exist") but api.weatherapi.com gving me two differnt reply for city that exist or city that not exist when i am trying to add Wrong city i am geting this replay from api. {'error': {'code': 1006, 'message': 'No matching location found.'}} when i am writing right city name i am geting this reply from api. {'location': {'name': 'Texas City', 'region': 'Texas', 'country': 'United States of America', 'lat': 29.38, 'lon': -94.9, 'tz_id': 'America/Chicago', 'localtime_epoch': 1670842210, 'localtime': '2022-12-12 4:50'}, 'current': {'last_updated_epoch': 1670841900, 'last_updated': '2022-12-12 04:45', 'temp_c': 18.9, 'temp_f': 66.0, 'is_day': 0, 'condition': {'text': 'Overcast', 'icon': '//cdn.weatherapi.com/weather/64x64/night/122.png', 'code': 1009}, 'wind_mph': 9.4, 'wind_kph': 15.1, 'wind_degree': 60, 'wind_dir': 'ENE', 'pressure_mb': 1016.0, 'pressure_in': 30.01, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 93, 'cloud': 100, 'feelslike_c': 18.9, 'feelslike_f': 66.0, 'vis_km': 11.0, 'vis_miles': 6.0, 'uv': 1.0, 'gust_mph': 10.1, 'gust_kph': 16.2, 'air_quality': {'co': 260.3999938964844, 'no2': 17.0, 'o3': 1.100000023841858, 'so2': 6.5, 'pm2_5': 4.0, 'pm10': 5.800000190734863, 'us-epa-index': 1, 'gb-defra-index': 1}}} How can i use code 1006 to filter out city that exist or not exist before … -
'Read' status of the message in Django chat built with django-channels
How can I show read or unread status of the message for the user? I thought about store IDs of messages seen by user - too much info to store. Maybe store tuple(first_seen_message, last_seen_message) - much less memory in use, but we have many chatrooms and direct messages - all messages get IDs in common pull. How to do it? I haven't tried anything in particular, bc I have no idea howto :D -
My if statement is not working, I am using django and python and I know the if statement is true
I am working with django and python trying to create an application, for some reason the following if statement is not working, but I know it should work because the if statement is true. `{% if reservation_breakfast %} {% for zone in zones %} <table class="table"> <thead class="thead-dark"> <tr> <td></td> <td></td> <td>{{zone.place_of_table}}</td> <td></td> <td></td> </tr> </thead> <tbody class="table-group-divider"> {% for x in reservation_breakfast %} <p>{{x.table_place_preference}} == {{zone.place_of_table}} ?</p> {% if zone.place_of_table == x.table_place_preference %} <tr> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> {% endif %} {% endfor %} </tbody> </table> {% endfor %} {% endif %}` The output is the following: It should print the table line with the words Mark Otto and @mdo right? So does anyone can tell me what am I doing wrong? I am expecting to know what am I doing wrong... -
Django-App: IIS Permission for Network Harddrive
I have a Django app that displays files in a folder via "os.listdir" in my Django app. However, the files are on a network hard drive with the drive letter "W". When I start Django as a development environment, this also works. I have deployed Django via IIS but due to lack of permissions, presumably these files cannot be displayed. I then added the user "IIS AppPool\DefaultAppPool" in the "Security" tab for the entire hard drive for testing with "Full Access" but still my Django app cannot read this folder on the external hard drive. Which user rights do I have to set so that Django can access a network hard disk via IIS to read data there? -
Django: combine values of two models fields into one new model field (3 different models)
I have three different models. class A(models.Model): department = models.CharField(max_length=50, blank=False, null=False) class B(models.Model): state = models.CharField(max_length=50, blank=False, null=False) class C(models.Model): db_name = models.CharField(max_length=50, blank=False, null=False) @property def db_name(self): return f"{A.department}_{B.state}" I would like to auto populate the db_name column as follow "DEPARTMENT_STATE". I thought that db_name would do this, but for some reason it isn't working at all, and I don't get why? There is relation on ID between model A -> B, A -> C (but for some reason the values are NULL in the table of model B and C). Does someone know how I can auto populate db_name which requires not manual/user input? -
Pytest parametrized django_db mark required
I am writing unit tests for a function. In parameterize, I am generating tests cases by making some DB calls when required. def my_function(tokens): pass def generate_tokens_helper(): tokens = list(MyTable.objects.values()) return tokens @pytest.mark.django_db class TestMyClass: @pytest.mark.parameterize( "tokens, expected_result", [ ( generate_tokens_helper(), True ) ], ) def test_my_function(self, tokens, expected_result): assert expected_result == my_function(tokens) This is generating the following error: test_file.py:47: in <module> class TestMyClass: test_file.py:17: in TestMyClass generate_token_helper(), test_file.py:5: in generate_token_helper items = list(MyTable.objects.values()) spm/accessors/variable_accessor.py:182: in get_all_operators operator_list = list(qs) venv/lib/python3.9/site-packages/django/db/models/query.py:269: in __len__ self._fetch_all() venv/lib/python3.9/site-packages/django/db/models/query.py:1308: in _fetch_all self._result_cache = list(self._iterable_class(self)) venv/lib/python3.9/site-packages/django/db/models/query.py:53: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py:1154: in execute_sql cursor = self.connection.cursor() venv/lib/python3.9/site-packages/django/utils/asyncio.py:26: in inner return func(*args, **kwargs) venv/lib/python3.9/site-packages/django/db/backends/base/base.py:259: in cursor return self._cursor() venv/lib/python3.9/site-packages/django/db/backends/base/base.py:235: in _cursor self.ensure_connection() E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I have already marked TestMyClass with django_db but I am still getting this error. -
Django - Form is getting submitted but nothing saves in database
My form is getting submitted by in phpmyadmin nothing get saved please help. Models.py from django.db import models class Customers(models.Model): first_name=models.CharField(max_length=100) . . . address=models.CharField(max_length=100) mar_stat=models.CharField(max_length=100) class Meta: db_table="customers" Views.py def customerreg(request): if request.method=='POST': if request.POST.get('first_name') and request.POST.get('last_name') and request.POST.get('gender') and request.POST.get('dob') and request.POST.get('email') and request.POST.get('phno') and request.POST.get('designation') and request.POST.get('address') and request.POST.get('mar_stat'): saverecord = Customers() saverecord.first_name=request.POST.get('first_name') . saverecord.mar_stat=request.POST.get('mar_stat') saverecord.save() messages.success(request, "New User Registration Saved Successfully. You may close the window!") return render(request,'index.html') else: return render(request,'index.html') Index.html <form method='POST'> {% csrf_token %} <table border="7"> <tr> <td>First Name</td> <td><input type="text" placeholder="Enter First Name" name="first_name" required/></td> . . . . </select> </td> </tr> </table> <hr> <input type="submit" value="Submit"/> {% if messages %} {% for result in messages %} <b style="color: green;">{{result}}</b> {% endfor %} {% endif %} </form> </body> </html> I have tried everything and im mostly sure that my indentation is right still it throws an error. What to do? -
Twilio Whatsapp Sandbox Configuration for deploying application via AWS elastic beanstalk
enter image description here Currently I am developing a chatbot for my application with django, using a twilio trial account. The chatbot functions properly with ngrok.io, i.e. when the server is operating locally, which mean that when I send a whatsapp message to the twilio sandbox with operation of simply "python manage.py runserver", he will automatically reply me according to my script. However, as I started deploying the application using the AWS elastic beanstalk, I found that it is only possible for the sandbox to send out whatsapp message by POST request on the web application, but not capable to respond to POST request sent out from whatsapp. In what way I can deal with it? Is it related to AWS settings or Twilio settings? Some CORS related issues? Great thanks in advance. (Please forgive me if my use of language is not accurate as I am not with computer science background.) Below is part of the code that I applied. @csrf_exempt def message(request): account_sid = 'xxx' auth_token = 'xxx' client = Client(account_sid, auth_token) client_phone_number = request.POST.get('From').removeprefix("whatsapp:+852") client_phone_number.removeprefix("+852") incoming_message = request.POST.get('Body') conversation_sid = request.POST.get('conversation_sid') incoming_message = incoming_message.lower() response = MessagingResponse() #processing the incoming message to produce the text resp = … -
Django-filebrowser doesn't support forms.py?
Django-filebrowser doesn't support forms.py? Can't I use the FileBrowseField of the file browser provided by models.py in forms.py where users can write in my Django project? I couldn't find it in the official guide. -
Why with django-postman that's doesn't work with this -> url(r'^messages/', include('postman.urls', namespace='postman', app_name='postman')),
I'm new with django, I would like use django-postman, and when I put : url(r'^messages/', include('postman.urls', namespace='postman', app_name='postman')), I have this error, idk why ? NameError: name 'url' is not defined Why is it not defined ? Just for test I replace url by path but that's doesn't work, I tried to install django postman in the terminal with pip, but that's doesn't work too.I really would like have a solution for a messaging system between users for my project. -
Django : in a ManyToManyField how can I find if a relationship exists?
I'm creating a Truth System for my project PoopFacts, where people can vote for True, False, or remove their vote. I have the voting system working, but I'm trying to make the button change colors to show if they've voted for True of False already or uncasted their vote. I'm showing the "Like button" code, cause it's simpler and uses the same logic. .models PoopFact(models.Model): likes = models.ManyToManyField(User, related_name='likes') .views def home(request): poopfacts = PoopFact.objects.all().order_by('-date') context = {'form': form, 'poopfacts':poopfacts,} return render(request, 'home.html', context) The idea is pretty much something like this html {% for poopfact in poopfacts %} {% if poopfact.likes.user.exists() %} <button type="submit" class="btn btn-primary btn-block">Like</button> {% else %} <button type="submit" class="btn btn-block">Like</button> {% endif %} So if they've liked it, the button will be blue, and if they click it again it will uncast their vote and make it normal. Does anybody have a good idea to make this work? I've been trying so many things with no luck. -
Django testcase for logout API with LoginRequired mixin, but for anonymous user it is redirecting to login API with ?next= parameter
But what if I want to check without login. For example, I have one api logout which is having LoginRequired mixin, I want to test that anyone cannot hit logout if hes not logged in. So I created testcase as below. @pytest.mark.django_db def test_user_logout_logged_in_user(self, client): url = reverse('logout') response = client.get(url) assert response.status_code == 302 assertRedirects(response, reverse('login')) but I got this error, AssertionError: '/auth/login-view/?next=%2Fauth%2Flogout-view%2F' != '/auth/login-view/' Means I get ?next={something for after login api}. How do I check that redirected api is login api. My logout api is as below: class LogoutView(LoginRequiredMixin, View): """ description: This is user logout view. GET request will log out user and redirects to home page. """ def get(self, request): return LogoutService.logout_user(request=request) class LogoutService: @staticmethod def logout_user(request): logout(request) messages.success(request, ACCOUNT_LOGOUT_SUCCESS) return redirect('home') Django test for a page that redirects I tried this answer, but it is for logged-in user. I want to test for un authenticated user. -
Video link to the html video element is not shown in AWS in React and Django app. Locally it works
We are trying to show a video link by creating an video element in html/javascript. It works in local system however do not work in AWS cloud. The app is in React and Django. The content of element is var cont="https://172.31.80.50:8000/api/getVideo?fn="person1_amar.mp4" or var cont="//172.31.80.50:8000/api/getVideo?fn="person1_amar.mp4" or var cont="https://localhost:8000/api/getVideo?fn="person1_amar.mp4" Note: Request has IP address of AWS machine. Localhost works in local system with http protocol. getVideo code on server side is vid = open('frontend/inoutfiles/'+fileN, 'rb') response = FileResponse(vid) We are getting below 2 errors: 'Failed to load resource: the server responded with a status of 499 ()' Failed to load resource: net::ERR_CONNECTION_TIMED_OUT Please let us know how to resolve this issue. Thanks, Amar Joshi We tried 2-3 solutions as mentioned in description. It did not work. We expect an answer to the issue so that we can show the video from server to the frontend in React in playing form. -
Reviews showing on the reviewer's own profile page instead of the profile that it was written on
I am adding a simple review function on my Social platform Django project, where Users can write a review on another user's profile. But after posting the review, it's only showing on the profile page of the user that I'm currently signed in to. This is my models.py ` class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reviewmsg = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.reviewmsg)` views.py ` def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() reviews = user.review_set.all() if request.method == 'POST': review = Review.objects.create( user=request.user, reviewmsg=request.POST.get('reviewmsg') ) return redirect('user-profile', pk=user.id) context = {'user':user, 'rooms':rooms, 'reviews':reviews} return render(request, 'pages/profile.html', context)` excerpt from my profile page template ` <div> {% for review in reviews %} <div class="comment-sect" style="margin-top: 0.5rem;"> <div class="comment-photo" style="margin: auto;"> <a href="{% url 'user-profile' review.user.id %}"> <div class="profile-photo"> <img src="{{review.user.avatar.url}}"> </div> </a> </div> <div class="comment-info" style="width: 300px;"> <small>@{{review.user}}</small> <small>{{review.created|timesince}} ago </small> <p style="margin-bottom:0;">{{review.reviewmsg}}</p> </div> </div><!--end of comment-sect--> {% endfor %} <div class="comment-form" style="margin-top: 0.5rem; text-align:center;"> <form method="POST" action=""> {% csrf_token %} <div>Submit a Review <input type="text" name="reviewmsg" placeholder="What do you think about this User?"/> </div> </form> </div>` -
Django views not retrieving data from database
Can Anyone know what's the problem with this? i can't display the data retrieve from db even the code is ok Here is my template addCategory.html Here is my views.py Here is my model.py When I Add Category, it didn't show/display the queried data from database like this can anyone solve?