Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Multiple LDAP3 Authentication
I have two questions...the first is I can authenticate using the below with my email address but I cannot with my AD Username. I have changed "username": "mail" --> "username": "sAMAccountName" didn't work...also tried "uid" nothing doing...so what's the deal? LDAP_AUTH_URL = "ldap://some_address" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_SEARCH_BASE = "dc=various_dc_values,dc=com" LDAP_AUTH_OBJECT_CLASS = 'Person' LDAP_AUTH_USER_FIELDS = { "username": "mail", "first_name": "givenName", "last_name": "sn", "email": "mail", } Second question is that I want to authenticate on multiple domains so as I couldn't work out how to add the other domain into the settings file I added my own function. #Authenticate User using backend #User object is returned with forename and surname. Referenced in Templates. user = auth.authenticate(username=email, password=password) #did it work or is this a user that belongs to a different domain? if user is None: #Create new User object. This line doesn't work. authenticated User object user = django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) #Authenticate User with different domain #Request comes back with forename and surname set TryOtherAuthentication( email, password, request) #Code breaks here - 'AnonymousUser' object has no attribute 'first_name' user.first_name = request.user.first_name user.last_name = request.user.last_name user.is_staff = request.user.is_staff user.save() So the question I guess is how do I create a User object like the … -
dbbackup with docker/celery/celery-beat not working: [Errno 2] No such file or directory: 'pg_dump'
I am setting up a backup to use dbbackup. However, I am receiving an error when backing up my data. There is a similar question where the person was able to resolve it, however, the answer doesn't show how. here My dbbackup version is django-dbbackup==4.0.2 Please find below my dockerfile: database: build: context: . dockerfile: pg-Dockerfile expose: - "5432" restart: always volumes: - .:/myworkdir environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_DB: faranga_db redis: image: redis restart: on-failure volumes: - .:/myworkdir expose: - "6379" celery: build: . restart: on-failure command: bash -c "sleep 10; celery -A project worker -l info" volumes: - .:/myworkdir env_file: - .env depends_on: - database - redis beat: build: . restart: on-failure command: bash -c "sleep 10; celery -A project beat -l info --pidfile=/tmp/celeryd.pid" volumes: - .:/myworkdir env_file: - .env depends_on: - database - redis my celery task: @app.task def database_backup(): management.call_command('dbbackup') # media backup works just fine @app.task def media_backup(): management.call_command('mediabackup') DB backup settings # django db backup https://django-dbbackup.readthedocs.io/en/master/installation.html DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': '~/myworkdir/backups/db/'} def backup_filename(databasename, servername, datetime, extension, content_type): pass DBBACKUP_FILENAME_TEMPLATE = backup_filename DBBACKUP_CONNECTOR = "dbbackup.db.postgresql.PgDumpBinaryConnector" Error stack trace: [2023-02-09 14:44:00,052: ERROR/ForkPoolWorker-6] CommandConnectorError: Error running: pg_dump --dbname=postgresql://postgres:password@database:5432/faranga_db --format=custom faranga-celery-1 | [Errno 2] No such … -
Is it possible to put tooltips on django list view that could appear onClick or mouse hover
I'm pretty sure that could be possible by customising the django admin site for that specific feature. I'm trying to add this functionality using admin.py but no better luck since a week. In the picture you can see I put a circle where I will like to add and icon that will show a tooltip saying information about that specific field or column. List View Image So is there any way to do it easily without customising it from templates. Because the List view is so much complex and we do not want to complicate the things doing it hard way. I tried to find it online and in the django official docs but every time its about customising it from templates, also I can html from admin.py but it doesn't invokes the tooltip as I wanted. -
Django prepopulate form in UpdateView
would like to know if it's possible to prepopulate my CommentForm in UpdateView. Updating comments work's except that the form is not loaded prepopulated. When testing using a separate template it's loaded prepopulated, but I would like to use the same template (PostDetail) using a modal to update the comment. views.py: class PostDetail(View): def get(self, request, slug, pk, *args, **kwargs): queryset = Post.objects.all() post = get_object_or_404(queryset,slug=slug, pk=pk) comments = post.comments.order_by('-created_on') return render( request, 'blog/post_detail.html', { 'post': post, 'comments': comments, 'comment_form': CommentForm() }, ) def post(self, request, slug, pk, *args, **kwargs): if request.user.is_authenticated: queryset = Post.objects.all() post = get_object_or_404(queryset, slug=slug, pk=pk) comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = post comment.author = request.user comment.save() messages.info(request, 'Kommentar tillagd') return HttpResponseRedirect(reverse('post_detail', args=[slug, pk])) class CommentUpdate(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView): model = Comment template_name = 'blog/post_detail.html' form_class = CommentForm def get_success_url(self): post = Post.objects.get(pk=self.object.post.pk) messages.info(self.request, 'Comment updated') return post.get_absolute_url() def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True return False` forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) post_detail.html (form): <form action="{% url 'comment_update' post.slug comment.pk %}" method="POST"> {% csrf_token %} {{ comment_form | crispy }} <button type="submit" class="btn">Update</button> </form> Please … -
I want to deploy my website on host cpanel when I (pip install migrate ) run this on terminal I have issue
enter image description here do you think its problem with host or the code because my code in local system runs without problem. I want to deploy my website on host cpanel when I (pip install migrate ) run this on terminal I have issue. -
Changing Django ManyToMany "through" value across model inheritance?
This is a simplified part of my model that causes me some troubles: class Node(models.Model): objects = InheritanceManager() node_id = models.AutoField(primary_key=True) links = models.ManyToManyField( "self", through='NodeLinks', blank=True, through_fields=('source', 'target')) class NodeLinks(models.Model): source = models.ForeignKey('Node', related_name='r_source', on_delete=models.CASCADE) target = models.ForeignKey('Node', related_name='r_target', on_delete=models.CASCADE) class Meta: unique_together = (('source', 'target',),) class Tag(Node): label = models.CharField(max_length=200) class TagLinks(NodeLinks): order = models.IntegerField(default=0) TagLinks._meta.get_field('target').related_model = Tag TagLinks._meta.get_field('source').related_model = Tag If I only want to retrieve Tag objects for example by executing this query: TagLinks.objects.all().values_list('target__label', flat=True) I got NodeLinks objects which don't have the label field instead of TagLinks objects. To simplify, currently Tag.links.through is defined as NodeLinks . Is it possible to change it to TagLinks ? Thank you very much. -
setup Python Django app on ubuntu with Nginx and no reverse proxy
I have an Python Django project running on port 8000. Then I used the Nginx and reverse proxy to route the traffic from port 80 to port 8000. The Problem Reverse proxy is rejecting the request if we exceed more than 200 concurrent users to the app where our API is hosted. I need help on how to remove the reverse proxy and route the traffic to port 80 or increase the limit so it doesn't refuse the request. Any help would be appreciated. -
How should I send a Post request to create an object that has a foreign key relationship
i have a model called Product which has a bunch of fields for all the product details, one of those fields (brand) is a foreign key to another table containing all my brands when sending a post request to create a new product i want to be able to pass in an id for a brand and it should save the serializer for the product model has the brand nested in it and i cant figure out how to properly structure the product info in the post request serializers.py class ProductSerializer(serializers.ModelSerializer): brand = BrandSerializer(required=False, read_only=False) vendors = VendorSerializer(many=True, required=False) class Meta: model = Product fields = "__all__" def create(self, validated_data): product_brand = validated_data.pop("brand") print(product_brand) product_instance = Product.objects.create(**validated_data) Brand.objects.create(product_brand) return product_instance models.py class Brand(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) sku = models.CharField(max_length=50) upc = models.CharField(max_length=12, blank=True) asin = models.CharField(max_length=10, blank=True) brand = models.ForeignKey( Brand, on_delete=models.CASCADE, null=True, blank=True ) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name + ": " + self.description example JSON of POST request { "id": 1, "brand": { "id": 2, "name": "Dewalt" }, "name": "Product1", "description": "the first product", "sku": "111111111", "added": "2022-12-28T19:09:30.007480Z", "updated": "2022-12-29T15:10:36.432685Z" } … -
django authenticate with phone number and otp
I want to implement authenticate for my project to user can register and login just with phone number and without password. this is my map: user register with this fields username email phone number after this user redirect to confirm opt page if otp is correct register and authenticate user without password in my database user cat login with phone number and otp i know i should have AbstractUser model like this: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_superuser(self,username, email, phone_number,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') user = self.create_user(username,email, phone_number, password, **other_fields) user.set_password(password) user.save() return user def create_user(self, username, email, phone_number,password,**other_fields): if not email: raise ValueError('آدرس ایمیل اجباری میباشد.') email = self.normalize_email(email) if password is not None: user = self.model(username=username,email=email, phone_number=phone_number,password=password, **other_fields) user.save() else: user = self.model(username=username,email=email, phone_number=phone_number, password=password,**other_fields) user.set_unusable_password() user.save() return user class CustomUser(AbstractUser): phone_number = models.CharField(max_length=15) objects = MyAccountManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['email', 'username'] also this is my authenticate backend: from django.contrib.auth.backends import ModelBackend class PasswordlessAuthBackend(ModelBackend): def authenticate(self, request, phone_number): User = get_user_model() try: … -
axios post request 403 "CSRF Failed: CSRF token missing or incorrect."
I'm new to web development and am currently stucked at a problem I can't solve easily. I'm using Django3.2.6, django restframework (DRF) 3.14, vue3.0 and axios (to make API calls). I wrote an APIView to lock a model while editing an it's instance: class LockCmAPI(APIView): def post(self, request, **kwargs): obj = get_object_or_404(CM, id=self.kwargs['pk']) obj.lock() print('locking object') return HttpResponse(status=status.HTTP_200_OK) For the frontend I created a Vue app that calls periodically my LockCmAPI to lock the instance and prevent others from editing it: let vue = Vue.createApp({ delimiters: ['[[', ']]'], data: function(){ return{ current_cm: cm_obj, intervall: null, } }, methods: { lockCmHeartbeat(){ console.log('locking'); console.log(`${BACKEND_PATH+LOCK_PATH+this.current_cm.id}/`); axios.post(`${BACKEND_PATH+LOCK_PATH+this.current_cm.id}/`, this.current_cm, { xsrfHeaderName: 'X-XSRF-TOKEN', }) .then((response) => { console.log('lock'); console.log(response); }); } }, mounted() { this.lockCmHeartbeat(); this.intervall = setInterval(function(){ this.lockCmHeartbeat(); }.bind(this), FIVE_SEC_IN_MILISEC); }, beforeDestroy() { clearInterval(this.interval); } }); vue.mount('#cm_vue_block'); After running my code I get a 403 response with the message "Request failed with status code 403". When I looked further into the response I got this "{"detail":"CSRF Failed: CSRF token missing or incorrect."}" in my responseText. My Question: Why does it tell me I sent an incorrect csrftoken since it's the same csrftoken in the cookie named csrftoken? Can someone clarify it for me? How can … -
Using Relationship Based Data in Model Definition - Django
I want to make the string representation of a field show data based on a JOIN, for instance: For Penciler - I want the string representation to resolve to John Doe (DC) - But the publisher value in that class is a Foreign Key - How do I reference the publisherName? from django.db import models class Series(models.Model): seriesId = models.AutoField(primary_key=True) series_name = models.CharField(max_length=300) publisher = models.ForeignKey('Publisher', on_delete = models.PROTECT) first_published = models.DateField() last_published = models.DateField() discontinued = models.BooleanField(default=False) def __str__(self): return f'{self.series_name} - {self.publisher} ({self.first_published - self.last_published})' class Meta: ordering = ['publication_year','title'] class Publisher(models.Model): publisherId = models.AutoField(primary_key=True) publisherName = models.CharField(max_length=250, null=False) def __self__(self): return self.publisherName class Penciler(models.Model): pencilerID = models.AutoField(primary_key=True) pencilerName = models.CharField(max_length=200) publisher = models.ForeignKey('Publisher', on_delete= models.PROTECT) def __str__(self): return self.pencilerName (self.publisher) -
How to create drill down operation for various chart in Plotly Dash using Django project?
I have some basic knowledge of python and I am using a Django. I am trying to create drill down operation for various chart in Plotly Dash. I have tried multiple demos from online but I am not able to find any proper tutorials which provides. I have uploaded post in Plotly support, but don't gives a proper links or tutorials. I was trying to this demo : Drill through bar chart Dash plotly , but this demo is in flask app but i need a code in Django. How do I put this code into Django?. Anyone please share useful demo links or some other tutorials with details which can I use. Thanks in advance. I need a code in Django project for drill down operation for various chart in Plotly Dash -
pgAdmin4 queries lead to BAD REQUEST when left idle for too long or when the docker service is restarted
I run pgAdmin4 (6.18 at the time of writing) as a dockerized application in my web browser, but sometime, somehow, e.g. when the docker service is restarted or when the computer is left idle for too long, whatever request I type ends on a BAD REQUEST in the messages panel. I have to close the tab and open a new one, losing my current work and queries. This is also showing in the logs: pgadmin4 | ::ffff:172.24.0.1 - - [12/Feb/2024:22:22:20 +0000] "GET /sqleditor/status/7821587 HTTP/1.1" 400 120 "http://localhost:8080/sqleditor/panel/7821587?is_query_tool=true&sgid=2&sid=31&did=5&database_name=postgres" "Mozilla/6.0 (X11; Ubuntu; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0" pgadmin4 | 2023-02-09 13:23:23,873: ERROR pgadmin: 400 Bad Request: The CSRF tokens do not match. pgadmin4 | Traceback (most recent call last): pgadmin4 | File "/venv/lib/python3.10/site-packages/flask_wtf/csrf.py", line 261, in protect pgadmin4 | validate_csrf(self._get_csrf_token()) pgadmin4 | File "/venv/lib/python3.10/site-packages/flask_wtf/csrf.py", line 115, in validate_csrf pgadmin4 | raise ValidationError("The CSRF tokens do not match.") pgadmin4 | wtforms.validators.ValidationError: The CSRF tokens do not match. pgadmin4 | pgadmin4 | During handling of the above exception, another exception occurred: pgadmin4 | pgadmin4 | Traceback (most recent call last): pgadmin4 | File "/venv/lib/python3.10/site-packages/flask/app.py", line 1515, in full_dispatch_request pgadmin4 | rv = self.preprocess_request() pgadmin4 | File "/venv/lib/python3.10/site-packages/flask/app.py", line 1857, in preprocess_request pgadmin4 | rv … -
ImportError: cannot import name '_imaging' from 'PIL' in my django project
I deployed my django site online on apache in mod_wsgi everything works so far I then installed: pip install --pre xhtml2pdf to generate pdf documents with the code that goes with it, after restarting the server and when I refresh my site I have an Internal Server Error error, And then after consulting the error.log file I have this: ImportError: cannot import name '_imaging' from 'PIL' (/home/ubuntu/myproject/env/lib/python3.10/site-packages/PIL/__init__.py) where is the problem ??? -
500:INTERNAL_SERVER ERROR when deploying in vercel
iam a student trying to build django project and deploy it to vercel since heroku is not free anymore i follow the tutorial step by step correctly, then when i deploy i got 500 internal server error when i check the log, it gave me [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django'Traceback (most recent call last): how can i fix this error since i'am pretty new to Vercel i have try to search online for the solution yet none satisfy the similiar problem i have -
how can I use django model method for ordering in meta class
class Post(models.Model): title = models.CharField(max_length=255, verbose_name="ady") text = RichTextField(verbose_name="text") tagList = models.ManyToManyField(Tag, verbose_name="taglar", related_query_name="tagList") image = models.ImageField(upload_to="postImage/", verbose_name="surat") seen = models.ManyToManyField(UserId,verbose_name="görülen sany", blank=True, related_name="gorulen") like = models.ManyToManyField(UserId,verbose_name="like sany", blank=True) share = models.PositiveIntegerField(verbose_name="paýlaşylan sany", null=True, blank=True, default="0") createdAt = models.DateTimeField(auto_now_add=True, verbose_name="goşulan güni") class Meta: verbose_name_plural="Makalalar" # ordering = ("-createdAt",) ordering = ["-hotness",] def __str__(self): return self.title def likes(self): return self.like.count() likes.short_description = "Like sany" likes.allow_tags = True def seens(self): return self.seen.count() seens.short_description = "Görülen sany" seens.allow_tags = True @property def hotness(self): return self.likes() + self.seens() + self.share how can I user hotness function value to ordering in meta class -
how to properly implement Django (Wagtail CMS) pagination in modal window using Select html tag?
I have a list view in a modal window, once the user chooses the option of the select element, the pagination changes the url queryset (?p=<page_number>), although, in a normal list view there is no issue,as it changes the url, in a modal, it changes the entire page's location (URL address), which of course causes the lost of changes in the main page (document form), I just need the modal list to be changed by the number of pagination-page. I have searched and read almost all documentations pages related to pagination of a list view using Django, however I was unable to find the solution. here is the modal pagination template code (see the comments that indicates not working parts): {% load wagtailadmin_tags %}{# Changed by HH #} {% if linkurl %}{% url linkurl as url_to_use %}{% endif %} {% if items.has_previous or items.has_next %} <div class='pagination center' aria-label="Pagination"> <!-- this is working --> {% if items.has_previous %}<div class="l_arrow previous"><a href="{{ url_to_use }}{% querystring p=items.previous_page_number %}" class="icon">Previous</a></div>{% endif %} <p>{% with pr=items.paginator.page_range page_num=items.number total_pages=items.paginator.num_pages %} Page {{ page_num }} of {{ total_pages }} <!-- this is NOT working --> <select onchange="gotopage(this)" name="pg_selector" title="pg_selector" id="pg_selector" disabled> {% for i in pr … -
I need to create documentation API for Django with MongoDB project
I need to create documentation API using swagger or anything I'm using drf-spectacular but do not support mongodb -
Nginx Gives 502 Error but config should be correct; Please I need advise on how to debug the issue?
I have a CentOS 8 (fedora) server running and I'm trying to run my Django Webapp on it through Nginx It runs on port 8000, and I want to access it on my browser through nginx (so port 80?) These commands on the server itself This shows my webapp HTML page fine curl http://127.0.0.1:8000 curl http://0.0.0.0:8000 but these show me the Nginx 502 Bad Gateway page curl http://0.0.0.0 curl http://127.0.0.1 No errors in the nginx log files This is my nginx.config: events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; server_tokens off; server { listen 80; server_name $hostname; # I tried this with an '_' also no help location / { proxy_pass http://0.0.0.0:8000; # also tried with 127.0.0.1 proxy_set_header Host $host; } } } Running nginx -T shows the config has been loaded Any advise on what to look for? (perhaps my firewall is blocking it somehow? idk) Kind regards I'm trying to get my webpage working through Nginx -
Django Admin inline-editable like Flask admin?
Flask Admin has this really nice inline-editable option. Is there something similar in Django-Admin? Yes, there is "list_editable". Unfortunately, this is poor usability and I much more prefere the flask-Admin approach: editable fields are underlined Click -> popup opens where you can edit Save -> save via Ajax -
Django ValueError: Cannot serialize: <User: username>
When I'm trying to make migrations of my models in Django, I keep getting the same error, even after I've commented out all the changes: (.venv) C:\Users\jezdo\venv\chat\chat_proj>python manage.py makemigrations chat Migrations for 'chat': chat\migrations\0002_alter_customusergroup_custom_group_name_and_more.py - Alter field custom_group_name on customusergroup - Alter field users on customusergroup Traceback (most recent call last): File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 22, in <module> main() File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 239, in handle self.write_migration_files(changes) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 278, in write_migration_files migration_string = writer.as_string() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize _write(arg_name, arg_value) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 63, in _write arg_string, arg_imports = MigrationWriter.serialize(_arg_value) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 282, in serialize return serializer_factory(value).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 221, in serialize return self.serialize_deconstructed(path, args, kwargs) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 99, in serialize_deconstructed arg_string, arg_imports = serializer_factory(arg).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize item_string, item_imports = serializer_factory(item).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize item_string, item_imports = serializer_factory(item).serialize() File … -
Django - images upload in wrong folder
Making some kind of blog website and can't make homepage to show article images... Images should be uploaded to media/profile_pics , but it just makes profile_pics folder in app folder and uploads images there. my models.py : class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") #author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = models.ImageField(upload_to="profile_pics", blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="blog_posts") def total_likes(self): return self.likes.count() def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") my views.py: class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' my forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'body', 'image') widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}), 'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}), 'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}), } my home.html <div class="row"> {% for post in object_list %} <div class="col-lg-4 my-4"> <div class="card shadow" style="width: 20rem; height: 33rem;"> <img src="/media/{{post.image}}" class="card-img-top" alt="..." height="250px"> <div class="card-body"> <h5 class="card-title">{{post.title}} <br><small>by {{ post.author.first_name }} {{ post.author.last_name }}</small></h5> <p class="card-text">{{post.body|slice:":100"|safe}}</p> <a href={% url 'article-details' post.pk %} class="btn btn-primary">Read More {% if user.is_superuser %}<a href="delete_blog_post/{{post.slug}}/" class="btn btn-danger mx-4">Delete Blog</a>{% … -
Django crispy forms language settings
I am a beginner at web application development using django framework. I am creating a crispy form to update the user information and upload an image. The html file contains two forms, one for updating the information and second for uploading the image. While the rest of the form language setting is us-en, only the button and text next to the upload button are seen in german language. The settings.py file has the chosen language code as 'en-us'. In the model.py file the forms are defined like below: The forms are then used in the html file: But the webpage shows the following: could anyone please help me understand, what is making only the upload button language change to german and how could I possibly fix it? Thank you :) already tried: checking the language code in the settings.py file -
I am trying to call "sqlite db.sqlite" in my django project but i found the error mentiod below
`sqlite : The term 'sqlite' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 sqlite db.sqlite3 + CategoryInfo : ObjectNotFound: (sqlite:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ~~~~~~` When I try to run this in the cmd it wrok fine the error is in visual studio terminal I have also installed sqlite viewer -
How to pass InMemoryUploadedFile as a file?
User records audio, audio gets saved into audio Blob and sent to backend. I want to get the audio file and send it to openai whisper API. files = request.FILES.get('audio') audio = whisper.load_audio(files) I've tried different ways to send the audio file but none of it seemed to work and I don't understand how it should be sent. I would prefer not to save the file. I want user recorded audio sent to whisper API from backend.