Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - ModelForm - Filter by user
I need to filter in EmployeeForm just to show me options of Companies related to user is logged in. I'm using ModelForm and CreateViews This is my code: models.py class Company(models.Model): reg_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255) cuit = models.CharField(max_length=20) class Employee(models.Model): company = models.ForeignKey(Empresa, on_delete=models.CASCADE) name = models.CharField(max_length=255) cuil = models.CharField(max_length=20) forms.py class EmployeeForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... self.fields['name'].widget.attrs['autofocus'] = True What is the code I need to write in the ellipses? It's currently showing me all companies even ones not owned by the user. Thanks in advance. -
How do I copy to the clipboard in JavaScript? tell me
i used this code const copyBtns = [...document.getElementsByClassName('copy')] copyBtns.forEach(btn=> btn.addEventListener('click', ()=>{ content = btn.getAttribute('data-content') navigator.clipboard.writeText(content) btn.textContent = "تم النسخ" })) copy not working on click in mobile, and it's working with any computer. what is the solution? -
HTML template for displaying forms only if form.DELETE doesn’t exist
I want to achieve something like this, actually "DELETE" shouldn’t exist in form itself, or if it does it should be switched off or not checked. {% if not form.DELETE %} <div class="input-form"> <div class="col-md-12 mb-4 mt-4"> {{ form }} </div> </div -
get all many to many field values + the rest of the model fields in a general query to db
I am studing django and I want to do an API endpoint that brings all the employees in the database with all the fields, including the languages field which has a manyToMany relationship to Languages Model. class Employee(models.Model): name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) salary = models.PositiveBigIntegerField() position = models.ForeignKey(Position, on_delete=models.CASCADE, related_name='employees') languages = models.ManyToManyField(Languages, related_name='employees') def __str__(self): return f'{self.name} {self.lastname}' class Languages(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name I managed to do this but with a query that gets only one employee try: emp = Employee.objects.get(id=id) data = { 'name': emp.name, 'lastname': emp.lastname, 'salary': emp.salary, 'position': emp.position.name, 'languages': [x['name'] for x in emp.languages.all().values()] } except ObjectDoesNotExist: return JsonResponse({"message": "No company found"}) except Exception as ex: return JsonResponse({"message": "Something went wrong."}) return JsonResponse({"message": "success", "data": data}) But now I can't do the same with a query such as Employee.objects.all() or Employee.objects.values(). This is what I would need but with all the employees at once: { "message": "success", "data": { "name": "Fred", "lastname": "Wilson", "salary": 28000, "position": "CTO", "languages": [ "JavaScript", "PHP" ] } } I've tried a lot of things including prefetch but I couldn't get it to work. -
How to pass variable from view.py to javascript without using render() in django
return render(request, 'index.html', {"flag": flag, "form": form}) I want to pass flag value which should be read by javascript to change style of an element in template, but since rendering it again the flag value is lost and set back to "none" ,is there any way to not use render and pass the variable to a url where the page is already rendered -
Django app return error when connecting to Postgres Database django.db.utils.OperationalError
I have a Django web app that connects to a postgres database in Azure, some days ago this was working fine, but now i receive the following error when I run the server: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "exampleyv.postgres.database.azure.com" (52.182.136.38), port 5432 failed: FATAL: no pg_hba.conf entry for host "186.31.127.234", user "exampleyv", database "exampleyv", SSL on The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\carlo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File … -
Django-native/ORM based approach to self join
Trying to set up a Django-native query that grabs all rows/relationships when it shows up on the other side of many-to-many relationship. I can explain with an example: # Django models class Ingredient: id = ... name = ... ... class Dish: id = ... name = ... ... class IngredientToDish # this is a many to many relationship ingredient_id = models.ForeignKey("Ingredient", ...) dish_id = models.ForeignKey("Dish", ...) ... I'd like a Django-native way of: "For each dish that uses tomato, find all the ingredients that it uses". Looking for a list of rows that looks like: (cheese_id, pizza_id) (sausage_id, pizza_id) (tomato_id, pizza_id) (cucumber_id, salad_id) (tomato_id, salad_id) I'd like to keep it in one DB query, for optimization. In SQL this would be a simple JOIN with itself (IngredientToDish table), but couldn't find what the conventional approach with Django would be... Likely uses some form of select_related but haven't been able to make it work; I think part of the reason is that I haven't been able to succinctly express the problem in words to come across the right documentation during research. Any help would be appreciated... thank you!! -
django image upload in different template
How can I display uploaded images in a different template from the form> in Django. I don't get it how to render it to another page. I the upload template has the form to upload image. And I want to display those images in profile but I am not able to do so . It is only working ienter image descript -
How to pass a Django Object to Javascript File (template buyed in envato elements)
dears!! I'm trying to get a Django object in a Javascript file. My objective is to to connect a Django template to a Javascript file and render my model info in the website. My models.py: class Event(models.Model): _id = models.ObjectIdField(blank=True, null=False) title = models.CharField(max_length=200) slug = models.SlugField(max_length=100) description = models.TextField(blank=True, null=True) event_date = models.DateTimeField(null=True, verbose_name="Date") event_creation = models.DateTimeField(verbose_name="Creation", auto_now_add=True) start = models.DateTimeField(null=True, verbose_name="Start") end = models.DateTimeField(null=True, verbose_name="End") event_updated = models.DateTimeField(verbose_name = 'Updated',auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'event_{self.title}' class Meta: db_table = 'event' My serializers.py: class EventSerializer(serializers.ModelSerializer): # _id = serializers.ReadOnlyField() channels = Event class Meta: model = Event fields = '__all__' My views.py: class Calendar(LoginRequiredMixin,TemplateView): template_name = "calendar.html" queryset = Event.objects.all() serializer = EventSerializer(queryset, many=True) data = JSONRenderer().render(serializer.data) def get(self, request): context = {'event': self.data} return render(request, 'calendar.html', context) #FOR THE FUTURE: I WANT TO USE POST METHOD # def post(self, request, *args, **kwargs): # serializer = self.get_serializer(data=request.data) # serializer.is_valid(raise_exception=True) # event = serializer.save() # return Response({ # "event": EventSerializer(event, context=self.get_serializer_context()).data, # "token": AuthToken.objects.create(event)[1] # }) the Javascript file (I've detected that the object that render events on calendar are the one in commented lines. What I want is to pass my Django Object into that list, … -
How Can I get a Particular User Group Name in Django Form Query
I have a Django form with a Drop Down from User Groups which is Created from Django Admin Panel. I have 3 groups with various permissions so in this form I want to get only the Group named 'Guest' from the drop down and disabled. What is the best way of doing it. Below is what I have tried but I am getting the following errors: ImportError: cannot import name 'getgroups' from 'os' class GuestUserForm(UserCreationForm): email = forms.EmailField group = forms.ModelChoiceField(queryset=Group.objects.get('Guest'), required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'group'] -
Django can not import site module
I am trying to run a simple Hello World app with Django but for some reason, it does not import myapp from mysite. -
Serve static files from Cloudflare's R2
Architecture Description I have a Django app hosted on an Azure App Service container and proxy through Cloudflare's DNS. The app works great, and using WhiteNoise I am able to serve static files stored in the Azure App Service storage container that is provided with the App Service (10 GB). Thing is, the storage serves files used by the Web App only (files uploaded during build, there's no option to manually add other files), and it is limited to 100GB/month of egress bandwidth. I would like to try and use [Cloudflare's R2] storage, as it has unlimited bandwidth, and allows you to upload any kind of files. I'll mainly be using images. Question How can static files be serve from Cloudflare's R2 on a Django app? -
Reverse Lookup for Inherited Models in Django
I have several Django model definitions. There is a parent class contains a foreign key to another class, and there are multiple model classes that inherit from the parent. class Foo(models.Model): pass class Parent(models.Model): foreign_key = models.ForeignKey(Foo, on_delete=models.CASCADE) class Child1(Parent): pass class Child2(Parent): pass Given an object of type Foo, I am trying to perform a reverse lookup to find all objects that are either of type Parent or subclass Parent and that link to that specific object. However, if I use foo.parent_set I would only get the objects of the Parent class that are related to foo, while if I try doing so with any of the child classes it errors out because those don't directly specify a relationship with the class Foo. Is there any way to get a list of all objects that are of type Parent or inherit from Parent that contain a foreign key to an object of type Foo? -
Django query with conflicting fields returns duplicate answers
Query: cameraSystems = DWCloudSystem.objects.filter(isShared=False).filter(company_key=comp) cameraSystems = cameraSystems | DWCloudSystem.objects.filter(isShared=True).filter(location__owners=comp) DWCloudSystem is a model with that contains: "company_key" a foreign key representing a Company model object, "location" a foreign key representing a place object, "isShared" a Boolean field A place object also contains a "owners" ManyToMany field for company objects. Essentially the goal is to have a DWCloudSystem which is owned by a company which is at a place to be returned if isSharing is false or ifSharing is true then any company that belongs to the place object will be able to access that DWCloudSystem along with its "owner" company which is represented by the company_key field (which may or may not be a member of the "owners" field that is apart of the place model) The issue is this query is returning the same company twice even though isShared is set to True and thus the other query should be empty. Both work correctly if not combined. -
Django REST Framework, implicatoins of [] in search
I have a very basic Django API which makes a query in elasticsearch. The output shows the query_parameters and the search.query. Why I cannot pass the country variable in this case 'DE' to the search.query as shown in the output? Could you please explain the implications of [] in country[]? class ESNumView(APIView): """Obtain number of articles after a search in titles and abstract in ES""" def get(self, request, *args, **kwargs): query = self.request.query_params.get('query') country = self.request.query_params.get('country') print(self.request.query_params) search = Search(index=constants.ES_INDEX) q = Q('bool', must=[ Q('multi_match', query=query, fields=['title', 'abstract']), Q('terms', country=country) ] ) s = search.query(q) pprint(s.to_dict()) num_count = s.count() return Response(data=[{'search_count': num_count}]) The output is; <QueryDict: {'query': ['membrane'], 'country[]': ['DE']}> {'query': {'bool': {'must': [{'multi_match': {'fields': ['title', 'abstract'], 'query': 'membrane'}}, {'terms': {'country': None}}]}}} -
why does the sqlite3 keeps telling me that i don't have a table called User?
i create a model on django this way: class User(models.Model): username = models.CharField(max_length=50) email = models.CharField(max_length=50) password = models.CharField(max_length=50) phone = models.CharField(max_length=80) and i then i use both commands: python manage.py makemigrations python manage.py migrate and still i get the error: django.db.utils.OperationalError: no such table: myapp_User (im using sqlite3 as a default database) is there a way to solve it or should i use PostgreSQL better? -
TypeError NoneType in Python script when running Django application
I get the error: TypeError: 'NoneType' object is not subscriptable. You can view the code below. The strange thing is when I run the code in Notebook it works. But when I run this in Django I get this NoneType error in return. I need this code in my Django application, so can someone please help. def update_pie(year, changed_id): dff = data[data['year'] == year] if changed_id[-1] == "." or changed_id[-1] == "1": dff = dff.groupby('air quality', as_index=False).count() dff = dff.rename(columns = {"country": "count"}) elif changed_id[-1] != "1" and changed_id[-1] != ".": dff = dff[dff['continent code'] == int(changed_id[-1]) - 1] dff = dff.groupby('air quality', as_index=False).count() dff = dff.rename(columns = {"country": "count"}) -
Host match not found. Google firebase messaging
I am buliding uber-like-delivery app using django. I just implemented the firebase messaging but each time i try to add a phone number so that it sends a verification code it give me the error "Hostmatch not foundenter image description here" so please anyone with an idea on how i can solve this. I tried the whitelisting thing , itdoesnt change anything or maybe its my code. ` Phone Number <div id="recaptcha-container"></div> <div id="get-code" class="input-group mb-3 {% if request.user.customer.phone_number %} d-none {% endif %}"> <label> <input type="text" class="form-control" placeholder="Your phone number"> </label> <div class="input-group-append"> <button class="btn btn-warning" type="button">Send code</button> </div> </div> <div id="verify-code" class="input-group mb-3 d-none"> <label> <input type="text" class="form-control" placeholder="Verification code"> </label> <div class="input-group-append"> <button class="btn btn-success" type="button">Verify code</button> </div> </div> <div id="change-phone" class="input-group mb-3 {% if not request.user.customer.phone_number %} d-none {% endif %}"> <label> <input type="text" class="form-control" disabled value="{{ requeat.user.customer.phone_number }}"> </label> <div class="input-group-append"> <button class="btn btn-warning" type="button">Change</button> </div> </div> </div> function onVerify(idToken) { var form = document.createElement("form"); form.method = "POST"; var element1 = document.createElement("input"); element1.name = "id_token"; element1.value = idToken; form.appendChild(element1); var element2 = document.createElement("input"); element2.name = "action"; element2.value = "update_phone"; form.appendChild(element2); var element3 = document.createElement("input"); element3.name = "csrfmiddlewaretoken"; element3.value = "{{ csrf_token }}"; form.appendChild(element3); document.body.appendChild(form); form.submit(); … -
Use data from get_context_data in form_valid method
How can i use value from dictionary context in form_valid? eg. def get_context_data(self, **kwargs): context_data = super(ProductView, self).get_context_data(**kwargs) product_obj = Product.objects.get(id=self.kwargs['pk']) user_id = product_obj.user_id user_obj = User.objects.get(id=user_id) context_data['email'] = user_obj.email return context_data def form_valid(self, form, **kwargs): email = context_data['email'] # need use this value return super(ProductView, self).form_valid(form) -
How to handle API generated reset password routes in Next.js
I'm using Djnago with Djoser as my backend, and Next.js as my frontend. When a user requests to reset their password, they receive an email with a recovery link following this pattern http://localhost:3000/password-reset/{uid}/{token}. I was able to handle the password recovery flow successfully using [...params] catch all dynamic route in Next.js. However, a user can go to http://localhost:3000/password-reset/abc/def and still be able to view the reset password page, even though they obviously won't be able to change any password. Is there a way to verify if the route has been generated by the backend and set the page permission based on that? Any help would be appreciated. Thank you -
Error rendering page: Error: Failed to load script: /_next/static/chunks/pages/_error-2280fa386d040b66.js
This website runs properly locally but then when I deployed it to heroku, it would load halfway and then go blank, the chrome console pops up errors I haven't still been able to find solutions to (It was built using next.js, django and postgresql). I'm new to all of this, please I need help? favourndubuisi.herokuapp.com -
Django Debug Toolbar BaseConnectionHandler.all() error
I am using docker and the debug toolbar gives the following error: BaseConnectionHandler.all() got an unexpected keyword argument 'initialized_only' I wrote the following code in the settings.py file : if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] import os import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] I wrote the following code in the urls.py file : if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] -
Django: Updating Old Migration Files that Have `django_mysql.models.JSONField`?
In older versions of Django, you could use JSON fields in models via django_mysql.models.JSONField. In new versions of Django, JSONField is no longer in django_mysql.models. I've updated my models.py files accordingly, but I still have old migrations files that look like this: # Generated by Django 2.1.7 on 2019-07-17 22:59 from django.db import migrations import django_mysql.models class Migration(migrations.Migration): dependencies = [ ('rss', '0009_delete_patternmatchingkeywords'), ] operations = [ migrations.AddField( model_name='rssoutput', name='industries', field=django_mysql.models.JSONField(default=list), ##<== ERROR ), ] Now when I run makeMigration, I get this error: AttributeError: module 'django_mysql.models' has no attribute 'JSONField' What is the correct procedure to address this? I'm using: Django 4.0 Python 3.9.13 django-mysql 4.7.0 -
forms.Select(attrs={'class': 'form-control' Edit form and get numbers 1-5 in dropdown
Am wondering how i can get this html code into a forms.py in my ReviewForm as widgets. This code: 'rating': forms.Select(attrs={'class': 'form-control',}), Should be as the html code under with 1-5. And also be saved in models so the rating still gets saved when edited. So basicly allow the forms.py when you edit it to render a dropdown with 1-5 atm its just a dropdown with no numbers cant figure out how to get numbers in the dropdown with the widget. <div> <label>Rating</label><br> <select class="form-control" name="rating"> <option value="1">1</option> <option value="2">2</option> <option value="3" selected>3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> forms.py class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ('content', 'rating') widgets = { 'content': forms.Textarea(attrs={'class': 'form-control'}), 'rating': forms.Select(attrs={'class': 'form-control',}), } Models.py class Product(models.Model): category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) description = models.TextField() has_sizes = models.BooleanField(default=False, null=True, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name def get_rating(self): reviews_total = 0 for review in self.reviews.all(): reviews_total += review.rating if reviews_total > 0: return reviews_total / self.reviews.count() return 0 class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = … -
ValueError: Field 'id' expected a number but got 'shafquetnaghmi'
models.py After adding this model,when i run python manage.py migrate this problem arises,there i added default='shafquetnaghmi' in sender but i removed it ,still it is not working. class instantmessage(models.Model): sender=models.ForeignKey(User,related_name='sender', on_delete=models.CASCADE,blank=True,null=True) receiver=models.ManyToManyField(User,related_name='receiver') message=models.TextField(blank=True) def __str__(self): return f'{self.message}' Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, social_django, socialapp Running migrations: Applying socialapp.0006_remove_instantmessage_sender_instantmessage_sender...Traceback (most recent call last): File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1822, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'shafquetnaghmi' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\SHAFQUET NAGHMI\socialnetwork\manage.py", line 22, in <module> main() File "C:\Users\SHAFQUET NAGHMI\socialnetwork\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 253, in hanp_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 2461, in get_db_prep_value value = self.get_prep_value(value) File "C:\Users\SHAFQUET NAGHMI\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1824, in get_prep_value raise e.__class__(ValueError: Field 'id' expected a number but got 'shafquetnaghmi'.