Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bug? <textarea> automatically adding line break
I am trying to simulate a mini wikipedia and one of its functions is to allow the user to edit a page, for that, I am using markdown and converting to HTML, then get user's input and save it as markdown file. The problem is that whenever the page is edited, its add line break automatically. I am probably missing something. Where is my logic fault? Here the page display the HTML for whatever content. Another page -> Edit get_entry() converts markdown to HTML <form action="edit" method="get"> <input type="hidden" name="title" value="{{ title }}"> <input type="submit" value="Edit Page"> </form> def edit(request): if request.method == "GET": title = request.GET.get("title") text = util.get_entry(title) return render(request, "encyclopedia/edit.html", { "title": title, "text": text }) And here the save process. Edit -> Edit <form action="edit" method="post"> <input type="hidden" name="title" value="{{ title }}"> <textarea name="text" rows="10" cols="20" wrap="hard">{{ text }}</textarea> <input type="submit" value="Submit"> {% csrf_token %} </form> def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) elif request.method == "POST": title = request.POST.get("title") text = request.POST.get("text") util.save_entry(title, text) return redirect(f"/{title}") … -
django nginx failed (13: Permission denied)
I get this permission error everytime I try to access media files failed (13: Permission denied) I have tried the solutions provided on the similar questions but they don't seem to be caused for the same reason. Media folder permissions: drwxr-xr-x 3 ubuntu www-data 4096 Jun 26 21:55 media This is also the same for the folder and file I'm trying to access. I checked the nginx site config and everything seems to be okay and pointing at the same path but the problem is still there. When I try to run the command sudo -u www-data ls /home/ubuntu/library/media/ it says ls: cannot access '/home/ubuntu/library/media/': Permission denied I'm new to nginx and ubuntu so I don't know what exactly is the problem here. -
AssertionError on PUT unit TestCase
I'm creating a unit test for a PUT method which purpose is creating new database entry. The problem seems to be I can't retrieve the saved fields string in the right format. The result strings are surrounded with square brackets. Faulty part of tests.py: def test_create_task(self): self.client.login(username='user1', password='password1') data: dict[str, str] = { 'name': 'Nowe zadanie', 'description': 'Nowy opis', 'status': 'Nowe', 'username': 'user1', } response = self.client.post('/api/tasks/', data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Task.objects.count(), 4) self.assertEqual(Task.objects.last().name, 'Nowe zadanie') self.assertEqual(Task.objects.last().description, 'Nowy opis') self.assertEqual(Task.objects.last().status, 'Nowe') self.assertEqual(Task.objects.last().user, self.user1) create method from views.py: def create(self, request, *args, **kwargs): username = request.data.get('username') try: user = User.objects.get(username=username) except ObjectDoesNotExist: raise serializers.ValidationError('Invalid username.') request_data = request.data.copy() request_data.pop('username', None) task = Task.objects.create(user=user, **request_data) serializer = TaskSerializer(task) response_data = serializer.data response_data['username'] = user.username return Response(response_data, status=status.HTTP_201_CREATED) Task model class from models.py(im also using django-simple-history library): class Task(models.Model): objects = models.Manager() STATUS_CHOICES = [ ('Nowe', 'Nowe'), ('W toku', 'W toku'), ('Rozwiązane', 'Rozwiązane'), ] id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False) description = models.TextField(blank=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='Nowe') user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) history = HistoricalRecords() def __str__(self): return self.name console output: ====================================================================== FAIL: test_create_task (tasks_app.tests.TaskTestCase.test_create_task) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\hunes\Desktop\Studia\tasks_project\tasks_app\tests.py", line 48, in test_create_task self.assertEqual(Task.objects.last().name, 'Nowe zadanie') AssertionError: … -
Django filter dynamic field name based on queryset
I have a queryset with a lot of annotations and i have this two fields: price price_after_discount now i want to write a max_filter for it based on value. but i need to do this that if price_after_discount is not 0, do the filter on that and if its is 0 then do the filter based on price. I know this code is not working, just sth that you can understand the question better: value = 200 queryset.filter( Case( When( price_after_static_discount=0, then=F("price") ), default=F("price_after_discount") )__lt=value ) -
Django query for string literal that starts with field value
I am using Graphene with Django, and have a case where I need to retrieve the Django content type that corresponds to a class name with "Node" added, where something like this: ContentType.objects.get(model__something="MyModelNode") would retrieve a ContentType with "model" equal to "MyModel". If it were the other way around, I'd use "model__istartswith='MyModel'". In SQL I'm looking for something like: SELECT * FROM some_table WHERE $1 ILIKE 'MyModel%'; but I don't see how to do that with a queryset. Any ideas? -
django allauth only one email per user
With the django-all-auth default templates / views, the user can have several email address (with only one primary) I'd like to force the user to have only one email address, how can I do that please? -
Pycharm Django connect to MSSQL databse
I am a totally beginner in django. If the question is stupid, please let me know how I should do. I already create the pycharm django project and want to connect to the MSSQL database. I see most of the solving ways is using django-mssql-backend but I am in company computer and our system does not has this package. And I used to use jupyter notebook to connect the databse successfully, here is the code I used in the jupyternotebook database = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};" "Server= DBName;" "Database=Staging;" "Trusted_Connection=yes;") query1 = """ select * FROM [Staging].[dbo].[viewname] df1=pd.read_sql_query(query1,database) df1 I am wondering can I do the same way in django project to connect to database? django project folder Here is the django project folder. If I can do what I do in jupyternotebook, which .py should I add the code in? Sorry for the stupid question and any help is really apprecaited! -
How to filter by table-A from table-B (table-A is linked to table-B, not the otherwise)
I have the following models: # models.py class Movement(models.Model): class Direction(models.TextChoices): SENT = 'S', _('Sent') RETURNED = 'R', _('Returned') case = models.ForeignKey(Case, on_delete=models.CASCADE, unique=False, null=False, blank=False, db_index=True, db_column='case_id') direction = models.CharField(unique=False, null=False, blank=False, db_index=False, max_length=1, choices=Direction.choices, default=Direction.SENT, db_column='direction') date = models.DateField(auto_now=False, auto_now_add=False, db_index=True, default=current_date, db_column='date') class Case(models.Model): class Meta: constraints = [models.UniqueConstraint(fields=['number', 'year', 'kind', 'police_station'], name='unique_case2')] class Kind(models.TextChoices): MISDEMEANOR = 'M', _('Misdemeanor') TRAFFIC = 'T', _('Traffic') police_station = models.ForeignKey(PoliceStation, on_delete=models.PROTECT, unique=False, null=False, blank=False, db_index=True, db_column='police_station_id') name = models.CharField(unique=False, null=False, blank=False, db_index=True, default='', max_length=100, db_column='name') number = models.SmallIntegerField(unique=False, null=False, blank=False, db_index=True, db_column='number') year = models.SmallIntegerField(unique=False, null=False, blank=False, db_index=True, default=current_year, db_column='year') kind = models.CharField(unique=False, null=False, blank=False, db_index=False, max_length=1, choices=Kind.choices, default=Kind.MISDEMEANOR, db_column='kind') registered_at = models.DateTimeField(auto_now=False, auto_now_add=False, db_index=True, default=current_datetime, db_column='registered_at') Some facts about the Movement table: The Movement table may have multiple records for the same case. The direction field can not have the same value for two records in a row. (ex: if the last Movement record for case_id = 2 is the direction = 'S', the next movement must be direction = 'R'). And I would like to filter cases by their last movement's directions from CaseAdmin class, into three types: Sent. Returned. Has no movement yet. Now how to build a … -
How to include django template file from an install python package?
I have an install python package with structure myapp templates/ myapp/ base.html and my project with structure myproject testapp/ templates/ layout.html I install the package myapp into myproject and from the layout.html file I want to extend the file base.html from the package myapp. Normally, if myapp is a local app inside myproject I can simply do {% extends myapp/base.html %} But if myapp is a install package how can I do that ? -
How do I upload a picture to my blog using the Django administration
I'm a complete beginner in Django, now after reading some articles I've managed to build a blog in Django where I can post (all through the Django administration). However, I also wanted to be able to add an image to my post, so I created an image field in my model, now it is also possible to upload images through the Django administration, these are then stored in the media/images folder. However, until now (after reading some articles) I haven't managed to display these pictures in my blog posts. Please excuse the probably a little stupid question and thanks a lot for the help Bennet My models.py file from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length= 255) slug = models.SlugField() intro = models.TextField() body = models.TextField() image = models.ImageField(upload_to='images/') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['-date_added'] the page where I want to display the image {% block content %} <div class="section title is-size-5 has-text-centered"> <div class="title">{{post.title}}</div> <div class="subtitle">{{post.date_added}}</div> </div> <div class="container"> <div class="columns"> <div class="column is-8 is-offset-2"> <div class="blob"> <img src="{{post.image}}" alt=""> {{post.body}} </div> </div> </div> </div> {% endblock content %} -
Integrity Error on Django ForeignKey relations
I have three django models related by Foreign keys as shown below class Table1(models.Model): ... class Table2(models.Model): table1 = models.ForeignKey("Table1", on_delete=models.CASCADE, related_name="rel_table2") class Table3(models.Model): table2 = models.ForeignKey("Table2", on_delete=models.CASCADE, null=True, default=None, related_name="rel_table3") So in essence, each Table1 object has one or more Table2 objects and each table 2 object also has one or more Table3 objects. When I delete a Table1 object, I expect the related Table2 and Table 3 to be cascade-deleted. But instead I get an Integrity error IntegrityError: FOREIGN KEY constraint failed unless I first delete in order the related Table3 and Table2 objects. (Same for when I delete a Table2 object -I'm only able to delete it when I delete manually all the related Table3 objects) Am I doing something wrong? (I am using Django 3.2) I changed the Table3 model by removing the options null=True and default=None as shown below class Table3(models.Model): table2 = models.ForeignKey("Table2", on_delete=models.CASCADE, related_name="rel_table3") and the cascading delete works for this. But that is unexpected. Why does it work? -
Django templating to wrap code in separate html syntax
I've picked up an older application that uses Bootstrap3 on Django. With Django templating I want to wrap a block of code in it's own template file which would sit outside of the bootstrap container. It's for a step menu that has two buttons "Back" and "Next" and at each step it has unique logic so I want to keep that in the file but just wrap the buttons in a new template that allows me to break out of the page container and stick the nav to the bottom of the page. Does Django have a template tag for this? -
What is `@stringfilter` in Django?
I sometimes see @stringfilter with @register.filter. So, I created test filter with @stringfilter as shown below: # "templatetags/custom_tags.py" from django.template import Library from django.template.defaultfilters import stringfilter register = Library() @register.filter(name="test") @stringfilter # Here def test_filter(num1, num2): return But, it accepted int type values without error as shown below: # "templates/index.html" {% load custom_tags %} {{ 3|test:7 }} # Here I thought that @stringfilter only accepts str type values giving error for the other types. So, what is @stringfilter in Django? -
Line graphs overlap in JavaScript used with Django
I am using Google Chart JS lib for chart display with Django. I am sending the data to be shown in the graph as an array by packing it piece by piece in python. Everything is fine, including the processing of the data. But while it normally needs to plot 3 different graphs, it uses the data of 3 graphs in all 3 graphs and overlaps them. My Code: {% for graph_index in 1|custom_range:all_graph_data %} var graphId = 'curve_' + '{{ graph_index }}' var data_{{ graph_index }} = new google.visualization.DataTable(); data_{{ graph_index }}.addColumn('number', 'Time'); data_{{ graph_index }}.addColumn('number', 'Current'); data_{{ graph_index }}.addColumn('number', 'Voltage'); {% for graph_values in all_graph_data|index:graph_index %} data_{{ graph_index }}.addRow([{{ graph_values|index:2 }}, {{ graph_values|index:0 }}, {{ graph_values|index:1 }}]); {% endfor %} var chart = new google.visualization.LineChart(document.getElementById(graphId)); chart.draw(data_{{ graph_index }}, options); {% endfor %} // add graph {% for graph_index in 1|custom_range:all_graph_data %} <div class="container" id="curve_{{ graph_index }}"></div> {% endfor %} Normally a graph should look like this: https://prnt.sc/nEQv6-eTk1lw But my graph:https://prnt.sc/gOaN_08yDulN Version: Python: 3.9.0 Django: 4.2.2 I sent my data packaged in several different ways. Same problem. -
How would end-to-end encryption work in a file transfer website? [closed]
With Django, I'm doing a file transfer website. One use will upload a file and then the recipient will download the file. I want to encrypt this file securely so that the encryption key is not stored on the server. I understand how end-to-end encryption works, but I can't achieve this with a Django website since you need to store a private key on a device (websites can't do this, unless you know a way to do this). How can I encrypt a file when it is uploaded to the server, then somehow decrypt the same file in the recipients end without having to store the encryption key. -
How to display duplicates objects in a queryset
I have a model Stock and I'm trying to find duplicates in db. When I do the filter Stock.objects.filter(component__in=components), I expect to see duplicates, but this filter excludes dups, but I need to display all of them. For example: my list of components is: 1 2 3 1 (this ones are subcomponents of components but I can convert it to component objects) 2 (this ones are subcomponents of components but I can convert it to component objects) 3 (this ones are subcomponents of components but I can convert it to component objects) 4 5 6 etc. Here comes my problem, in the filter, it deletes the 1, 2 and 3 objects under the first 3 object because it has the same ID, but I want to display them all. def get_custom_queryset(self): params = {} reference = False for param in iter(self.request.GET): if param.startswith('Search_'): search = param[7:] if search == 'inventory': try: inventory = self.request.GET[param] if inventory == 'on': components, stock_codes = [], [] stock = Stock.objects.filter(is_inventory=True) # Cannot be first() because in self.table it requires a queryset instead of a list for s in stock: stock_codes.append(s.component.code) components_on_inventory = Component.objects.filter(code__in=stock_codes) for coi in components_on_inventory: if coi.has_subcomponents(): qs_sc = [] components.append(coi) for … -
AttributeError: 'function' object has no attribute 'register_battery'
I have been getting this error in my views.py file.: AttributeError: 'function' object has no attribute 'register_battery' [26/Jun/2023 21:39:53] "POST /fontriden/fontriden/manufacturer/battery/registration/ HTTP/1.1" 500 69541 views.py def battery_registration(request): if request.method == 'POST': form = BatteryRegistrationForm(request.POST) if form.is_valid(): manufacturer = request.user.manufacturer # Process form data and register battery battery_id = interact_with_smart_contract.register_battery( form.cleaned_data['product_name'], form.cleaned_data['certification_mark'], form.cleaned_data['serial_number'], form.cleaned_data['watt_hours'], ) request.session['battery_id'] = battery_id return redirect('battery_registration_success') else: form = BatteryRegistrationForm() return render(request, 'battery_registration.html', {'form': form}) blockchain.py # Define the functions for interacting with the smart contract def register_battery(w3, contract, product_name, certification_mark, serial_number, watt_hours): tx_hash = contract.functions.registerBattery( product_name, certification_mark, serial_number, watt_hours ).transact() receipt = w3.eth.waitForTransactionReceipt(tx_hash) # Process the transaction receipt or handle any events emitted by the contract # ... models.py from django.db import models from django.contrib.auth.models import User class Manufacturer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=100) # Add any additional fields for the Manufacturer model def __str__(self): return self.user.username class Battery(models.Model): manufacturer = models.ForeignKey(to='fontriden.Manufacturer', on_delete=models.CASCADE, null=True) product_name = models.CharField(max_length=100) certification_mark = models.CharField(max_length=100) serial_number = models.CharField(max_length=100) watt_hours = models.IntegerField() qr_code_url = models.URLField(blank=True) qr_code_filepath = models.CharField(max_length=255) def __str__(self): return self.product_name I had tried placing the functions from the blockchain.py in the views.py but it just gave me more error. I am not sure what to do. This is … -
How to display tasks based on condition and user in a view
I want to check each task that is stored in the model and is supposed to be displayed based on the value stored in the condition field. When I am checking each task during display, if the value inside the condition is equal to True, I want that task to be displayed for all users except users with usernames [‘Electric_Motor_Winding’, ‘Electrical_Panels’, ‘Seller’] until three months after being saved. If the condition is equal to False, I want that task to be displayed only to the user who saved it and only on the day it was saved. So for displaying tasks, tasks must be checked for the date and user they were saved by and then checked for the value of the condition. If the value of the condition is equal to True, that task should be displayed for all users except users with usernames [‘Electric_Motor_Winding’, ‘Electrical_Panels’, ‘Seller’] until three months after being saved. If the value of the condition is equal to False, that task should only be displayed on the day it was saved and only to the user who saved it. class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' ordering = ['-posted_time'] def get_shamsi_time(self): timezone.activate('Asia/Tehran') now … -
How to use a SASS in a Django Framework?
How to compile a SASS ( Syntactically Awesome Style Sheets) using Django Framework? I can't compile the sass file in django. SASS is a one of the framework of CSS (Cascade style sheet). Using sass in django, 1st need to compile the sass ( to convert into css) and again run the manage.py files . How to rectify that in single compilation? -
Custom user level throttling with Django rest framework
I am trying to set API call limits by tier group. Basically a free tier, a paid tier and another paid tier with more limits. I am using Django rest framework and the issue I keep running into is regardless of what tier the user is set at, I still get throttled at the default rate which in this case is 3/minute. Also wondering if there is a way to have a custom response for each tier level rather than the default throttle response. These are dummy numbers I'm using for testing. Herre is my code throttling.py from rest_framework.throttling import UserRateThrottle class TierBasedRateThrottle(UserRateThrottle): def allow_request(self, request, view): user = request.user if user.is_authenticated: if user.tier_level == 'tier_1': self.rate = '4/minute' # Rate limit for tier 1 users elif user.tier_level == 'tier_2': self.rate = '6/minute' # Rate limit for tier 2 users elif user.tier_level == 'tier_3': self.rate = '10/minute' # Rate limit for tier 3 users return super().allow_request(request, view) settings.py REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ], 'DEFAULT_AUTHENTICATION_CLASSES':[ 'knox.auth.TokenAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'accounts.throttling.TierBasedRateThrottle', ], … -
'Error 404 Page not found' api REST-FRAMEWORK
I've just started using rest-framework and I can't get my page to display.I have a 404 error the page was not found but when I arrive on the home page it knows the destination url . I've added my app in setting.py, I've done my serializer in serializer.py. I've tried all the solutions I've found on stack overflow but nothing works. I'll take any advice and solution you can offer, thank you in advance for your time. (this is my first question on a forum if there are things that are not correct do not hesitate to point them out to me ) lesite/ |--urls.py | |--recup_fichier_api/ | |---urls.py |---views.py lesite\urls.py urlpatterns = [ path("backend_recup_fichier/", include("backend_recup_fichier.urls")), path("admin/", admin.site.urls), path("page_accueil/",include("page_accueil.url")), path('table_config/', include('recup_fichier_api.urls')) ] lesite\recup_fichier_api\views.py class table_configVisewset(viewsets.ModelViewSet) : queryset = table_config.objects.all() serializer_class = config_serializer lesite\recup_fichier_api\urls.py urlpatterns = [ ] router = routers.DefaultRouter router.register = ('table_config', table_configVisewset ) -
how to import all products with a same feature in django import-export
I need to import all products with the same brand. I understand that they need to be selected together, but other than manually, I don't know how to do it. How to select automatically all items with the same characteristics or maybe there is another way. -
django project - problem because the sql server database has column names with spaces, i got how to use it in models.py but not in the template file
the sql server I'm connecting to has column name with spaces in between I changed the models.py but I don't know what to do in the templates file. Code for the template file: <div id="CPU Utilization" class="tabcontent"> <h1>CPU Utilization</h1> <center> <table border = "1"> <tr> <th>SQL Server Process CPU Utilization</th> <th>System Idle Process</th> <th>Other Process CPU Utilization</th> <th>Event Time</th> </tr> {% for datadisplay in sqlserverconn2 %} <tr> <td>{{datadisplay.SQL Server Process CPU Utilization}}</td> <td>{{datadisplay.System Idle Process}}</td> <td>{{datadisplay.Other Process CPU Utilization}}</td> <td>{{datadisplay.Event Time}}</td> </tr> {% endfor %} </table> </center> </div> I tried the using the custom filters and defining attribute but it said it is not a registered tag library. -
pip install -r requirements_dev.txt
I am trying to install requirements for python django using command "pip install -r requirements_dev.txt" but I am getting the following error: × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [2 lines of output] <string>:8: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html proj executable not found. Please set the PROJ_DIR variable.For more information see: https://pyproj4.github.io/pyproj/stable/installation.html [end of output] anyone can help with that ? I tried to install "pyproj" and "proj" but with no hope, and try to set "PROJ_DIR" as mentioned in the error to "venv/bin/proj" but getting: subprocess.CalledProcessError: Command '/Users/../venv/bin/proj' returned non-zero exit status 1. -
I get error 404 on all URLs (when I click on a menu item on home page) in production. Everything works on localhost. What am I missing please?
I have deployed a django app on a shared hosting server using cpanel. The home page loads fine (I see only 1 error - 404 on favicon on developer's console). All the pictures and styling are showing as expected on the home page. I have placed my images on a google cloud bucket and I am referencing CSS/js from CDNs. My problem is that when I click on menu items, none of the the URLs are working. 'File not found' is displayed. On the dev console/Network I see error 404. There are no errors in the logfile. This exact question was asked previously but there was no resolution as far as I can tell: URL working on localhost but not in production I have tried so many things including: Setting DEBUG=True in settings, TEMPLATE_DEBUG=True, specifying default django template loaders one by one then together in TEMPLATES. I have made sure that all my apps are listed in INSTALLED_APPS. I even ran collectstatic and tried pointing DIRS to this static folder. After every change I restart the Python App in Cpanel and clear the browser cache Initially I had installed whitenoise to serve static files but I commented it out in …