Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django: Is it possible to use a capitalization method such as capfirst in templates but instead in forms.py
In templates a usual statement such as {{field.value|capfirst}} capitalize the first letter of a string. In an input field this looks like <input type="text" name="{{field.name}}" value="{{field.value|capfirst}}"> In my template I do not define explicitly the input fields, instead I have the following: {% for field in form %} {{ field }} {% endfor %} If I do {{field|capfirst}} it won't work. All my fields are given in forms.py, for example: class MyForm(forms.ModelForm): name = forms.CharField() description = forms.CharField() class Meta: model = Project fields = ('name', 'description') How can I define capfirst in forms.py (or views.py or templatetags)? I want to keep a simple for loop in my template as shown above. As you can see I just want to capitalize the first letter of field.value to show it on the screen, no need to transfer this info to the database or store it or update, i just want to show it... is it possible? -
Cloning GITHUB project to ubuntu 22
I've had to wipe and reinstall my ubuntu server twice now due to failing and some how corrputing/locking my self out of the server when it comes to setting up the SSH. I'm going out on a whim and hoping some one who reads this knows where to find an easy to follow tutorial for cloning a project to ubuntu using SSH as they dont allow HTTP cloning now. Many thanks. -
Reverse for 'detail' with arguments '('2022/11/29/oddballers-29112022',)' not found. 1 pattern(s) tried: ['page/(?P<key>[^/]+)\\\\Z']
I'm getting error NoReverseMatch at /, here I'm trying to catch the key like this enter image description here and I can't get the key, when I take it and an error like the one above comes out The code details are like this: enter image description here enter image description here detail error like this: enter image description here thank you. what I want is to capture the key and then I make it as a parameter for the details of the article, when I catch the key but what comes out is an error.. sorry if my English is difficult to understand, I'm not good at English -
Most efficient way to migrate data from temporary Django table to main table?
I have a data engineering pipeline that is essentially doing nightly scans of data tables to populate a main table with calculations for the frontend clients to view. The pipeline takes around 6 hours to complete. Instead of deleting the main table and writing the calculations over a 6 hour period, I am instead writing the calculations to a temporary table (so the main table still has prior day's calculations while the today's calculations are generating). Once complete, I am trying to have the Django ORM essentially delete the main table and insert all of the new calculations from the temp table into the main table in a transaction. Is there an efficient way using the Django ORM to do this? Thank you! Also note that the temporary model and main model have the exact same copy of fields. -
Python Django - Trying to make a dynamic name from string to call serializer function
So I was trying to access a serializer using the serializer name, and the model query set as a parameter, using the python gettattr() function. After running the code, Django returns the following error: 'str' object has no attribute '<module 'django.db.models' from 'C:\\Python310\\lib\\site-packages\\django\\db\\models\\__init__.py'>' However I can't really understand what it means, I've been stuck on trying to access the serializer this way, as I have a dyanmic url. Anyhelp with the problem or explanation of the error would be appreciated. I was expecting the serializer to be processed normally, and return the data in the respone, I implemented it this way. @api_view(['GET']) def List_all_part(request, part): table = apps.get_model('Parts', part) model = table.objects.all() serializer = getattr(str(part.lower()), str(models)) return Response(serializer.data) -
How to implement `left outer join` with additional matching condition, with `annotate()` or something else?
We are implementing a design pattern that assembles EAV data with the entities by a series of left outer join actions in SQL query, briefly as the following: First, we have retrieved the meta data, e.g. postalcode corresponds to attribute_id of 22, phone corresponds to 23, and etc. Then, we want to construct a QuerySet by adding annotate() method calls following the meta data. And we are open to other methods other than annotate(). Like the below SQL query, the system behaviour is to repeat left outer join on the same eav_value table, however, besides the foreign key, the matching condition also requires a specific attribute_id. So, each join assembles one attribute. Our Question: We tried to assemble the first attribute appending an annotate() call to the existing QuerySet but got an error saying AttributeError: 'WhereNode' object has no attribute 'select_format'. We wonder how to fix the issue and make the prototype run. And we are also OK to use something else other than annotate() within the Django framework, not raw query. We are new to this area of Django ORM, so we appreciate any hints and suggestions. Technical Details: 1. SQL query for assembling EAV data with entities: select … -
how to display subcategories title and its items under parent category in django?
I want to display subcategories title and its items under parent category in Django e.g. I have 1 parent category then it hast 2 sub cats and then each of them has 3 sub cats. in every sub category there are 10 items. Parental category1 item1 item2 subcategory 1 item3 item4 item5 child category 1 from subcategory1 item6 item7 subcategory 2 item8 item9 item10 here is my codes: Models.py from django.conf import settings from django.db import models from django.urls import reverse from django.utils.text import slugify from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=settings.BLOG_TITLE_MAX_LENGTH, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = models.SlugField(max_length=settings.BLOG_TITLE_MAX_LENGTH, null=True, blank=True) description = models.TextField(null=True, blank=True) class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def save(self, *args, **kwargs): value = self.name if not self.slug: self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('items-by-category', args=[str(self.slug)]) class Item(models.Model): title = models.CharField(max_length=settings.BLOG_TITLE_MAX_LENGTH) category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(null=True, blank=True) slug = models.SlugField( max_length=settings.BLOG_TITLE_MAX_LENGTH, ) def __str__(self): return self.title def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('item-detail', kwargs=kwargs) def save(self, *args, **kwargs): if not self.slug: value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) Views.py from … -
MQTT async worker in Django
In my Django application, I need to connect to a MQTT broker from several locations. It will be great if I can create some kind of MQTT worker, which will run in the background/different thread and I can use this worker to publish/subscribe for messages and I don't have to create a separate MQTT connection for each function. Example: Create MQTT worker with connection details. On startup, this connection is started and handled, restarted if connection lost, etc... (maybe use Celery for this?) Create functions which is available inside my Django projects for publish and subscribe. Publish seems more straighforward, but I'm not sure about the subscribe part. I have found mqttasgi but I don't know if it will fit my needs. -
Server Error (500) Django App on AWS server
Good day, i have currently my django project running on an aws server. I have used Nginx and configured it all. The application is running, but when i try to login via the login page i have created or try to login via the admin panel it gives me a Server Error (500). I have my DEBUG=False and added my server dns to ALLOWED_HOSTS. As for the Database. I have got my SQL Database running on an Azure server and used environment variables (that i have permanently set in my ubuntu terminal) to get my password and username. I have also tried to set DEBUG to False and trying to figure out the issue when running python manage.py runserver so i could experiment with it on my localhost, but no luck. I cant access 127.0.0.1 eventhough i have added it to my Allowed hosts. How could i see what the error is? Thank you in advance