Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url pattern data
If inside of urls.py I had a url pattern that depended on input sent to it from a template, what data would be sent to the url, and what data to the view? For example, urls.py:path('post/<int:post_id>/<str:post_title>', views.view_post, name='view_post'), blogposts.html template: <a href="{% url 'blogs:view_post' post.id post.title%}">Read More</a> views.py: def view_post(request, post_id, post_title):. What if I wanted only the post id to be sent to the view, but for the url to look the same? -
I am creating a project in Pycharm, I am working on django, whenever I am installing OpenCv and trying to use it I am getting following error
Traceback (most recent call last): File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy__init__.py", line 142, in from . import core File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core__init__.py", line 24, in from . import multiarray File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\multiarray.py", line 14, in from . import overrides File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\overrides.py", line 16, in add_docstring( RuntimeError: implement_array_function method already has a docstring Traceback (most recent call last): File "C:/Users/Dell/Desktop/pp/test2/templates/ex.py", line 1, in import cv2 File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\cv2__init__.py", line 5, in from .cv2 import * ImportError: numpy.core.multiarray failed to import -
How to store multiple values on a django model field
I have a model where I store the recurring sessions on my gym. DAYS_OF_WEEK = ( (0, _("Monday")), (1, _("Tuesday")), (2, _("Wednesday")), (3, _("Thursday")), (4, _("Friday")), (5, _("Saturday")), (6, _("Sunday")), ) class RecurringSession(models.Model): session = models.ForeignKey(SessionType, db_index=True, on_delete=models.CASCADE) dayofweek = models.PositiveSmallIntegerField(choices=DAYS_OF_WEEK) time = models.TimeField() However some classes happen more than once a week. Whats the best way to store multiple values (between 1 to 7) on that modelfield? I'm using Django Mysql 8.0, and from what I understand it supports JSON field but from the django docs it seems that is only supported by Postgres so far. I was inclined to So I'm inclined to change the dayofweek model field to a JsonModel Is there a specific django way to do this? Maybe storing a charfield with comma-separated values? I wont need to search by that field. Using Django 3.0.6, Python 3.8.2, and MySQL 8.0.20. thanks -
How to make Django Admin TabularInline sortable by custom field?
In Django Admin, it's easy to create a custom field on the model list page, e.g.: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('id', 'field1', 'field2', 'custom_field3') def custom_field3(self, obj): return obj.get_custom_field3_display() custom_field3.short_description = 'Custom Field 3' custom_field3.admin_order_field = 'field3' # makes column header sortable MyModel.field3 will be used to sort the now clickable "Custom Field 3" column header on the model list page. How can I achieve the same on an inline model? I can easily define a custom field in the same way, but the admin_order_field line doesn't achieve the same result: class MyModelInline(admin.TabularInline): model = MyModel fields = ('id', 'field1', 'field2', 'custom_field3') def custom_field3(self, obj): return obj.get_custom_field3_display() custom_field3.short_description = 'Custom Field 3' custom_field3.admin_order_field = 'field3' # doesn't seem to have any effect -
filter by count of reverse lookup
I have two models, for example, class Student(models.Model): name = models.CharField(max_length=160) teams = models.ManyToManyField("Team", related_name="student", blank=True) class Team(models.Model): name = models.CharField(max_length=160) I want to retrieve all the teams which is not assigned to any student , ie all teams where students.count() is 0. How can i query this? I have tried Team.objects.filter(student=None) -
How to save user input data from multiple forms (in a single template/web page) to the sqlite database in django?
I have multiple ModelForms to be displayed in a single web page with one submit button and i want all the user input data to be stored in the db. forms.save() doesn't seem to be working if there are more than 1 forms. How do i write views for this? -
Javascript: Map Container is already initialized in django-leaflet
While trying to load geojson of point data from database in django-leaflet and djeojson i get an error. Uncaught Error: Map container is already initialized. I have used another script in base.html to initialize the map, I understand , but how do I solve it so that I can render the points from database to the template? base.html: <script type="text/javascript"> function map_init_basic (map, options) { L.marker([8.9806,38.7578]).addTo(map); } </script> index.html: <body> <h1>Django-Leaflet</h1> {% leaflet_map "map" callback="main_map_init" %} <script type="text/javascript"> function main_map_init (map, options) { var dataurl = '{% url "rent_app:data" %}'; // Download GeoJSON via Ajax $.getJSON(dataurl, function (data) { // Add GeoJSON layer L.geoJson(data).addTo(map); }); } </script> </body> -
Authentication without a passwrod Django
As the title states I'm trying to authenticate a user without a password. I've already used this: django authentication without a password to solve my problem with on of my apps (on Django 2.0), but I want to do the same thing in another app but It's on Django 2.1. When I do the same implementation my custom authenticate fuction is never called. Thus it doesn't work. Current setup in auth_backend.py: from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class PasswordlessAuthBackend(ModelBackend): """Log in to Django without providing a password. """ def authenticate(self, username=None): try: return User.objects.get(username=username) except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None setup in settings.py: AUTHENTICATION_BACKENDS = [ # auth_backend.py implementing Class YourAuth inside yourapp folder 'yourapp.auth_backend.YourAuth', # Default authentication of Django 'django.contrib.auth.backends.ModelBackend', ] but when I try in my views user = authenticate(username=user.username) It never hits my custom authentication method. Any and all help is appreciated! -
I have a bug in Django
======================= File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax created a project launched it and gives such an error what is the problem? -
how do I change default font of Summernote in Django?
So I'm using django-summernote (I'm using Django ver 3.x), and trying to change the default font in the editor. Here's my code. (part of) forms.py: from .models import MyModel class MyInputForm(forms.ModelForm): contents = SummernoteTextFormField() class Meta: model=MyModel fields=['contents'] widgets = { 'contents': SummernoteInplaceWidget() } (part of) my template : <form method="post" class="form-group"> {% csrf_token %} <div class="row"> <div class="col col-8"> {{form.contents|as_crispy_field}} </div> </div> </form> And in case you need to take a look, (part of) my settings.py SUMMERNOTE_CONFIG = { 'iframe': True, 'lang' : 'ko-KR', 'summernote': { 'width': '100%', 'height': '400px', 'toolbar': [ ['style', ['style',]], ['font', ['fontname', 'fontsize', 'bold', 'italic', 'strikethrough', 'clear',]], ['color', ['forecolor', 'backcolor', ]], ['para', ['ul', 'ol', 'height']], ['insert', ['link']], ['misc', ['picture', 'fullscreen', 'codeview', 'print', 'help', ]], ], }, 'js': ( '/static/summernote-ext-print.js', ), 'js_for_inplace': ( '/static/summernote-ext-print.js', ), 'css': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', ), 'css_for_inplace': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', ), 'codemirror': { 'theme': 'base16-dark', 'mode': 'htmlmixed', 'lineNumbers': 'true', }, 'lazy': False, } SUMMERNOTE_THEME = 'bs4' X_FRAME_OPTIONS = 'SAMEORIGIN' I have no idea on how or where to write my code for changing the default font. I would really appreciate your help. Thanks. :) -
TemplateDoesNotExist Heroku issue
I know there is already a lot of posts dealing with this problem however i don't find any solution.. I developped a Django website in local and know i would like to host it thanks to Heroku. I configured everything but when I launch the website i get this error : "TemplateDoesNotExist at /index.html" There is my configuration : my settings files my prod_settingsFiles my variable BASEDIR And finally : The organisation of my project -
Adding Items to cart Bug
I'm facing a problem with the code, a bug to be more specific, that is when I'm adding an item to the cart for the first time(with variations let's say Red and Medium), it's being added nicely. Then when I'm adding another item(let's say Blue and Large), it's also working. But when, I'm increasing the item quantity from the order_summary.html, it's increasing the quantity of the other item not the one I clicked(if I clicked Red and Medium, Blue and Large's quantity is increased) and says : Please specify the required variations. Why is this happening? Can anyone please help me out? Thanks in advance! My models.py: class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50) # size, color class ItemVariation(models.Model): variation = models.ForeignKey(Variation, on_delete=models.CASCADE) value = models.CharField(max_length=50) # small, medium large etc class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) item_variations = models.ManyToManyField(ItemVariation) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20) ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add= True) ordered_date = models.DateTimeField() My views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) variations = request.POST.getlist('variations', []) print(variations) print(request.POST) minimum_variation_count = … -
I am trying to decrypt PDF file, using PyPDF2, but getting this error: NotImplementedError: only algorithm code 1 and 2 are supported
pdf_file = io.BytesIO(decrypt_file(protected_path)) user_pdf = PdfFileReader(pdf_file) if user_pdf.isEncrypted: user_pdf.decrypt('') The Pdf is encrypted, without password! I am on Windows, is there some other solutions except using qpdf to deal with decryption? -
In a Django view, how do I format a date like in a template?
If I have a datetime object, and I render it in a Django template like this: {{ foobar }} Then Django will format it to look pretty: July 18, 2019, midnight How to do the same thing inside a Django view in Python code? I'm imagining a function named render_date in this example: def example_view(request): # ... example = "Date is: " + render_date(foo_date) I would like it to render exactly the same way as it would in the template. How do I do this? It should respect the settings DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT, SHORT_DATE_FORMAT and USE_L10N. -
In Django how to test reversing urls with namespaces?
I want to write tests to see if reversing URLs works properly. This includes testing namespaces. But reversing urls with namespaces doesn't work in my test cases. tests/urls.py from myMainApp.urls import urlpatterns as urlpatternsBase urlpatterns = urlpatternsBase tests/test_urls.py from http import HTTPStatus from django.test import Client from django.urls import reverse from django.test import TestCase class URLTests(TestCase): def setUp(self): self.client = Client() def test_foo(self): response = self.client.get(reverse('fooNameSpace:index')) self.assertEqual(response.status_code, HTTPStatus.OK) The test fails with this error: django.urls.exceptions.NoReverseMatch: 'fooNameSpace' is not a registered namespace Testing non-namespaced URLs works however. -
Best tools for Data Analytics on django microservices
I have a django microservice architecture and am looking for a third party tool for analysing data which will be served by another "analytics" microservice. My data is stored in AWS S3 buckets. What is the best way of going about doing this architecturally? I am looking at tools like splunk, datadog, mixpanel, new relic and AppDynamics. What should I consider for a more robust, flexible and scalable way of collecting data and analysing it in a distributed architecture such as mine? -
How to check or set room availability in Django
I am building a hotel booking system. I am quite new to Django and i am kindly asking for directions on how to carry out setting or checking for room availability implementation. I have designed my room model in a way that a specific room type can have several quantities. I want to implement the system in such a way that before a user makes a booking the room should have enough quantity and also be available on that specific date duration specified by the user. The following is code for room and booking model Room Model class Room(models.Model): """Creates room details""" ROOM_CHOICES = ( ('Single', "Single"), ('Double', "Double"), ('Family', "Family"), ('Suit', "Suit"), ) hotel = models.ForeignKey( Hotels, on_delete=models.CASCADE, null=True, blank=True,) room_Type = models.CharField( max_length=20, choices=ROOM_CHOICES, default='Please Select', ) room_photo = models.ImageField( default='default.jpg', upload_to='room_photos') room_Name = models.CharField(max_length=200) room_details = models.CharField(max_length=500) room_Capacity = models.PositiveIntegerField(default=0) slug = models.SlugField(unique=True) room_Price = models.PositiveIntegerField(default=0) total_Rooms = models.PositiveIntegerField(default=0)#room quantity Booking (Cart) Model class CartItems(models.Model): cart = models.ForeignKey( 'Cart', on_delete=models.CASCADE, null=True, blank=True) rooms = models.ForeignKey( Room, on_delete=models.CASCADE, null=True, blank=True) quantity = models.PositiveIntegerField(default=1) line_total = models.DecimalField( max_digits=1000, decimal_places=2, default=0.00) CheckIn = models.DateField(null=True, blank=True) CheckOut = models.DateField(null=True, blank=True) stay_duration = models.PositiveIntegerField(default=1) updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) … -
Django. How to save the generated file in FileField?
I am inexperienced in Django and I need help. I tried to override the save () method so that QR code generation and subsequent saving occurred along with it. However, when I save the entry in the media folder, I get two files. picture The "17.png" file consists of the "slug" field of the model and the extension. The file is created after this line is executed: self.qr.save(self.slug+'.png', BytesIO(qr), save=False) The name of the other file is generated by Django itself (after creating the first file) and saves it in the "qr" field of the model. How to make sure that only one file is created (only "10.png") and it is saved in the field? models.py class Url(models.Model): slug = models.CharField(max_length=50, unique=True) qr = models.FileField(upload_to='', blank=True, null=True) def save(self, *args, **kwargs): qr = self.qr_generate(self.slug) self.qr.save(self.slug+'.png', BytesIO(qr), save=False) super(Url, self).save(*args, **kwargs) def __str__(self): return self.slug @staticmethod def qr_generate(slug): qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data("somedata" + str(slug)) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") qrByte = BytesIO() img.save(qrByte) return qrByte.getvalue() -
How to implement validation error messages in django rest
I am hust start learning python and django rest framework.I am creating the sample apis in django. I have coming into problem where i need to set the validation error messages. For example email is requied or email already exists Here is my code: Serializer Class: class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article #fields = ['id','title','author','date'] fields = '__all__' views.py def post(self,request): serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error,status = status.HTTP_400_BAD_REQUEST) Model: class Article(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) email = models.EmailField(max_length=100) date = models.DateTimeField(auto_now_add = True) def _str_(self): #self.fields['email'].required = False return self.title Error is: 'ArticleSerializer' object has no attribute 'error' -
Prefetch related inside Prefetch inside Prefetch related
I need a nested filter in a view. I will start with model description. A device is linked to one or many gateways. class GatewayDevice(models.Model): gateway = models.ForeignKey( Gateway, on_delete=models.CASCADE, related_name="devices" ) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="gatewaydevices" ) I start from the device and I need the active gateway (the gateway which has end_date = None) This is my filter: devices = ( Device.objects.filter() .prefetch_related( Prefetch( "site__users", queryset=UserSite.objects.filter(owner=True).all() ), "software_update_history", "supplier", Prefetch( "gatewaydevices", queryset=GatewayDevice.objects.filter(end_date=None) .prefetch_related("gateway") .all(), ), ) .all() ) In my serializer I do this: @staticmethod def get_gateway(device): return ( GatewaySimpleSerializer(device.gatewaydevices.gateway).data if device.gatewaydevices.gateway else None ) What am I doing wrong? -
when i migrate i get error.makemigrations not causing any error
Why im getting this type error?When '''makemigrations''' no problem at all .Everything was fine.but '''migrate''' make error. django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary ke y '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a va lue '1' that does not have a corresponding value in main_tutorialseries.id. System check identified no issues (0 silenced). May 07, 2020 - 18:11:59 Django version 3.0.6, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. C:\Users\Toshiba\Desktop\mysite> C:\Users\Toshiba\Desktop\mysite>python manage.py makemigrations Migrations for 'main': main\migrations\0005_auto_20200507_1813.py - Create model TutorialCategory - Add field tutorial_slug to tutorial - Alter field tutorial_published on tutorial - Create model TutorialSeries - Add field tutorial_series to tutorial C:\Users\Toshiba\Desktop\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: Applying main.0005_auto_20200507_1813...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Toshiba\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Toshiba\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Toshiba\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Toshiba\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Toshiba\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Toshiba\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Users\Toshiba\AppData\Local\Programs\Python\Python38-32\lib\site-pack ages\django\db\migrations\executor.py", line … -
django pass data using anchor tag
I am trying to pass data using anchor tag to django views. My html file: <div class="card-body dropdown"> <button class="dropbtn">Pay</button> <div class="dropdown-content"> <a href="{% url 'payments' data='wallet'%}">Payments Wallet</a> <a href="{% url 'payments' data='credit_card'%}">Payments Credit card</a> <a href="{% url 'payments' data='debitcard'%}">Payments Debitcard</a> <a href="{% url 'payments' data='bitcoin'%}">Payments Bitcoin</a> </div> </div> </div> My urls.py file urlpatterns = [ path('payments/<str:data>',views.payments,name="payments"), ] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) my views.py file def payments(request): query = request.GET.get('data') print(query) return render(request, '403.html') Error : Reverse for 'payments' with no arguments not found. 1 pattern(s) tried: ['customerspayments\/(?P[^/]+)$'] Please help. -
Adding a user to a group Django Rest Framework
I want to use an API to create a user and add it to a selected group. But when I execute the POST request with Postman I get an error saying this group already exists, I don't want to make a new group. I just want to add the user to it. POST body This is what I send in the post. { "email": "user@example.com", "username": "Laerie", "first_name": "Laerie", "last_name": "koek", "password": "password", "groups": [{"name":"user"}] } Response I keep getting this error { "groups": [ { "name": [ "group with this name already exists." ] } ] } Serializer class CustomUserSerializer(serializers.ModelSerializer): email = serializers.CharField( required=True ) username = serializers.CharField(required=True) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField() last_name = serializers.CharField() groups = GroupSerializer(many=True) class Meta: model = CustomUser fields = ('id', 'email', 'username', 'first_name', 'last_name', 'password', 'groups') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) group = Group.objects.get(name=validated_data.pop('groups', None)) user = CustomUser.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) if group is not None: user.groups.add(group) else: user.groups.add('user') if password is not None: user.set_password(password) user.save() return user Views.py class CustomUserView(APIView): permission_classes = [IsAuthenticated, IsAdmin, ] def get(self, request, format='json'): queryset = CustomUser.objects.all() serializer = CustomUserSerializer(queryset, many=True) filterset_fields = ['id', 'name', … -
Django, difference between two queryset
I have the following queryset: Iva_total= {'Iva a debito': [0, 0, 0, 0, 44.0, 0, 0, 0, 0, 0, 0, 0]} Ricavi_total= {'Ricavi': [0, 0, 0, 0, 200.0, 0, 0, 0, 0, 0, 0, 0]} I want to do the difference between two list() Ricavi_total and Iva_total to obtain the following result: Difference = {'Difference': [0, 0, 0, 0, 156.0, 0, 0, 0, 0, 0, 0, 0]} -
Django GENERIC VIEW V/S FUNCTION VIEW
After using function views when i started using generic views . So, which one is better for development. So ,as to be developer which would be good. Is their any issue if i continuing using function views as i found class view little hard.