Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make single CharField display as textarea inside a fieldset
I have a user model: class User(AbstractBaseUser): username = models.CharField(max_length=64, unique=True) email = models.EmailField(unique=True) about_me = models.CharField(max_length=140, blank=True) last_login = models.DateTimeField(auto_now_add=True) last_message_read_time = models.DateTimeField(auto_now_add=True) following = models.ManyToManyField("self",symmetrical=False) def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) def clean(self): obj = self parents = set() while obj is not None: if obj in parents: raise ValidationError('Cannot follow self', code='self_follow') parents.add(obj) obj = obj.parent and this admin form: class BlogUserAdmin(admin.ModelAdmin): fieldsets = [ (None, { 'fields': ['username', 'email', 'password'] }), ('Biography', { 'classes': ['collapse'], 'fields': ['about_me'] }), ('Follows', { 'classes': ['collapse'], 'fields': ['following'] }), ] admin.site.register(User, BlogUserAdmin) and it displays like this: imgur I want to make the "about me" a text area. I have viewed methods where you define the text area in forms.py but it seems that fieldsets do not support forms from that. I'm assuming this is not possible and that I will have to define my own form from scratch but perhaps there is some setting or method or class I have overlooked? -
Elasticsearch dsl
I need an multi match and suggestions in elasticsearch-dsl search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=categoryField.code) ) I tried multi_phrase and multi_phrase_prefix but not working ! -
update api not working in django rest framework
I have a simple update api which is not working properly. I tested the API in postman by sending only the key and data that needs to be updated but my frontend is sending whole formdata along with the data that are updated. It is working in my postman when I send only the key and the data that needs to be updated but when I send all the data with certain fields as empty string (""), it does not get updated. My models: class Lead(models.Model): title = models.CharField(max_length=5, choices=TITLES, blank=True) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30) address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50, blank=True) state = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=30, default="nepal") phone = models.CharField(max_length=50, ) /........other fields................................/ My views: class LeadsView(APIView): permission_classes = [AllowAny] def put(self, request, pk=None, *args, **kwargs): print("iam put") id = pk abc = Lead.objects.get(id=id) serializer = LeadSerializer(abc,data=request.data) if serializer.is_valid(): serializer.save() return Response({ "message": " Leads has been updated", "data": serializer.data }, status=status.HTTP_200_OK) return Response(serializer.data) My serializers: class LeadSerializer(serializers.ModelSerializer): email= serializers.EmailField(required=False) phone = serializers.CharField(required=False) first_name = serializers.CharField(required=False) last_name = serializers.CharField(required=False) title = serializers.CharField(required=False) address = serializers.CharField(required=False) company_name = serializers.CharField(required=False) /.................same in other fields............../ class Meta: model = Lead fields = ['id','title','first_name','last_name','address','company_name', … -
How to upload images with AJAX in DJANGO
I have been using AJAX recently with DJANGO to send text data. It has been working smoothly and feels an easy method. But I cant understand and there no proper resource to learn to send images with AJAX and save to Django Database. HTML: <input type="file" id="fileInput-single" class="drop-zoon__file-input" accept="image/*"> JS: $(".add-prop").click(function() { var data = new FormData(); data.append("image", $("#fileInput-single")[0].files[0]) data.append("csrfmiddlewaretoken", $("input[name=csrfmiddlewaretoken]").val()) $.ajax({ method: "POST", url: "{% url 'upload-prop-images' %}", processData: false, contentType: false, mimeType: "multipart/form-data", data: data, success: function(data) { if (data.status == "Upload Done") { console.log("Uploading Done successfully") } } }) }); models.py class Property(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='property_user') prop_images = models.ImageField(upload_to="prop_images") views.py def uploadPropImages(request): image = request.POST['image'] property_new = Property(user_id=request.user.id, prop_images=image) property_new.save() return JsonResponse({'status': 'Upload Done'}) urls.py urlpatterns = [ path('upload-prop-images/', views.uploadPropImages, name='upload-prop-images') ] There is one tutorial using the forms.py file but I don't want to create a forms.py file. -
How to backend filter exact field of model
I have model named Tittle and I wanted to filter its GET respond by the "genres->slug". I tried to use backend filter with filterset_fields = ("genres__slug",). But it is not doing what I thought. How can I filter it by the model Slug of the Genres? views.py class TitleViewSet(viewsets.ModelViewSet): queryset = Title.objects.all() permission_classes = (AdminModifyOrReadOnlyPermission,) pagination_class = LimitOffsetPagination filter_backends = (DjangoFilterBackend, ) filterset_fields = ('genres',) def get_serializer_class(self): if self.action == 'list' or self.action == 'retrieve': return ReadTitleSerializer return WriteTitleSerializer models.py class Title(models.Model): ... genres = models.ManyToManyField( Genre, through='GenreTitle', ) class Genre(models.Model): name = models.CharField( max_length=255, verbose_name='Название жанра' ) slug = models.SlugField( unique=True, verbose_name='Слаг жанра' ) def __str__(self) -> str: return self.slug class GenreTitle(models.Model): title_id = models.ForeignKey( Title, on_delete=models.CASCADE, related_name='genres_titles' ) genre_id = models.ForeignKey( Genre, on_delete=models.CASCADE, related_name='genres_title' ) -
how to use many to many field in django serializers and How o use related_name for that
class PamphletLocation(models.Model): pin_code = models.CharField(max_length=6) def __str__(self): return self.pin_code class PamphletCampaign(Campaign): PAMPHLET_SIZE_CHOICES = ( ('A4', 'A4'), ('A5', 'A5'), ) pamphlet_id = models.ForeignKey(ClientPamphletDesign, on_delete=models.CASCADE) size = models.CharField(max_length=3, choices=PAMPHLET_SIZE_CHOICES) pin_codes = models.ManyToManyField(PamphletLocation, related_name="pin_codes_str") class Meta: verbose_name = 'Campaign' class CreatePamphletCampaignSerializer(serializers.ModelSerializer): pin_codes_str = PamphletDistributionLocationListSerializer(read_only=True, many=True) class Meta: model = PamphletCampaign fields = ('id', 'name', 'quantity', 'file', 'sub_industry', 'amount', 'pamphlet_id', 'pin_codes_str') -
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Address not available)")
I have built a Django app along with Mariadb by referring to this https://www.javatpoint.com/django-crud-application And I'm trying to make a docker image for this app. I am completely new to Docker and I'm not able to figure out what I am doing wrong. This is my Dockerfile FROM python:3.9.10-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app RUN pip install -r requirements.txt # copy project COPY . /usr/src/app EXPOSE 8000 CMD python3 manage.py runserver This is my requirements.txt file asgiref==3.5.0 Django==4.0.2 protobuf==3.19.4 PyMySQL==1.0.2 six==1.16.0 sqlparse==0.4.2 The docker build is successful, but if I try to run the docker image, I get this error and I have no idea on what I'm supposed to do. Should I make a Docker compose file ? I don't know why that is used, as I said I'm completely new to Docker. Can someone please help me out ? -
How to pass some data from html to django view? Should I just try with javascript?
I'm rendering some questions about math from a Postgres database. Exercises have a field with correct answers; I'm passing it to view. I want to compare the answers the user sends through a form with correct answers. How could I pass the correct answers (as a list, for example) to a view to check how many are correct? Is there a way in Django ou I should use JavaScript? This is the views.py from django.shortcuts import render from questoes.models import Questao from .forms import CHOICES from django.forms import formset_factory # Create your views here. #I'd like to use this function to compare the answers. In this part I'm getting the responses from the form def get_respostas(request): form = CHOICES(request.POST) if request.method=='POST': form0 = request.POST['form-0-NUMS'] form1 = request.POST['form-1-NUMS'] form2 = request.POST['form-2-NUMS'] form3 = request.POST['form-3-NUMS'] form4 = request.POST['form-4-NUMS'] # Id like to test here. return render(request,"provas/teste.html") def prova(request): questoes = Questao.objects.order_by('?')[:5] gabarito = [] for q in questoes: gabarito.append(q.gabarito) form = CHOICES respostaFormSet = formset_factory(CHOICES, extra=5) if request.method=='POST': dados = { 'formset': formset, 'questoes': questoes, 'form':form(request.POST), 'gabarito':gabarito } return render(request,'provas/prova.html', dados) else: dados = { 'formset': formset, 'questoes': questoes, 'form':form, 'gabarito':gabarito } return render(request,'provas/prova.html', dados) this is the prova.html {% if questoes … -
How to sort related objects based on the timestamp of when we are associating the two objects?
i'm trying to sort objects based on the time when i associate the two objects. For example, i have these two models: class Album(models.Model): title = models.CharField(max_length=255) release_date = models.DateField() order = models.IntegerField(blank=True, null=True, help_text="The order of albums to be displayed.") class Artist(models.Model): name = models.CharField(max_length=255) stage_name = models.CharField(max_length=125) is_active = models.BooleanField(default=True) albums = models.ManyToManyField(Album, blank=True) I have an Album model, that have an order field to sort the priority of the album when we display it on the API. Now, of course it is working when i sort the albums based on the order field: artist = Artist.objects.get(id=76) album1 = Album.objects.create(title="Untitled Album", order=2) album2 = Album.objects.create(title="Magical Nights", order=1) artist.albums.add(album1, album2) albums = Album.objects.filter(artist=artist).order_by('order') print(albums) >> <QuerySet [<Album: Magical Nights>, <Album: Untitled Album>]> But when i have some albums with the same priority, i want to also sort the objects based on the timestamp of when i associate the item. Something like this: artist2 = Artist.objects.get(id=77) new_album1 = Album.objects.create(title="Sapphire Blue", order=1) new_album2 = Album.objects.create(title="Now We're Strangers", order=2) new_album3 = Album.objects.create(title="Fight For You", order=1) artist2.albums.add(new_album3) artist2.albums.add(new_album2) artist2.albums.add(new_album1) albums = Album.objects.filter(artist=artist2).order_by('order') print(albums) >> <QuerySet [<Album: Sapphire Blue>, <Album: Fight For You>, <Album: Now We're Strangers>]> My expected result is that when we … -
Django - NoReverseMatch Error even with correct parameters (no namespacing)
I'm trying to create an app that stores problems (specifically math problems), and displays them to the user. I haven't add much of the functionality that I want to yet, and as I'm fairly new to Django, I have been following along with the Django Tutorial project, and changing it according to my needs. However, I'm encountering a NoReverseMatch error even though I seem to be passing in the correct parameters. My code is below. models.py import imp from django.db import models from django.urls import reverse import uuid # Create your models here. class Source(models.Model): '''Model that represents the source of a problem (e.g. AMC, AIME, etc.)''' problem_source = models.CharField(max_length=20) problem_number = models.PositiveSmallIntegerField() def __str__(self): '''toString() method''' return f'{self.problem_source} #{self.problem_number}' class Topic(models.Model): '''Model that represents the topic of a problem (e.g. Intermediate Combo)''' problem_topic = models.CharField(max_length=50) problem_level = models.CharField(max_length=15) def __str__(self): return f'{self.problem_level} {self.problem_topic}' class Problem(models.Model): '''Model that represents each problem (e.g. AIME #1, AMC #11, etc.)''' id = models.UUIDField(primary_key=True, default=uuid.uuid4) source = models.OneToOneField(Source, on_delete=models.RESTRICT, null=True, unique=True) problem_text = models.TextField() topic = models.ManyToManyField(Topic) def __str__(self): """String for representing the Model object.""" return f'{self.source}' def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('problem-detail', args=[str(self.id)]) urls.py … -
Django running timer
I'm trying to implement a running timer on a django app/website. Essentially I would like for someway to input let's say 5 min and then start and then a timer will start that will countdown to 0:00. Any help with where I can start? I've found some tutorials that have running timers but this is part of a project where I would like after the timer for a signal to be sent to a microcontroller (that's not important for this part). -
How to link HTML and CSS file using Django?
I am novice person to Django learning. I have tried with simple linking HTML and CSS files in Django by referring some sites and videos but it seems CSS file is not included. Though I tried multiple times I am not getting the background color which I put in CSS file. CSS file saved in static/css/style.css body{ background-color: violet; } HTML file saved in templates/bg.html {%load static%} <!<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title> BG </title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <h2 class="bg_class">BG Colour</h2> <p> Background Color is to be changed.<br> </p> <script src="" async defer></script> </body> </html> Also, I have configured the static file in settings.py file too. STATIC_URL = '/static/' STATIC_DIRS=[ os.path.join(BASE_DIR,'static') ] Instead of ‘violet’ background, I am still getting ‘white’ background. Kindly help me to fix this. -
How to upload an image to DriveHq using django?
Can any one give me the code for uploading an image through html file and using django for uploading that image to DriveHq. Thankyou so much... -
Django print statements/debug on hosted app pythonanywhere
I have a Django app working fine on the local server but when I host it on the pythonanywhere (It is a cloud-based python site), there are some issues with the rendering on the template. While I was coding on the local server, I used to use print statements to debug the functions in views.py, but how to use print statements for debugging if the site is deployed on the web because after hosting it on the pythonanywhere, I am unable to find where the output of the print statements goes to? Please suggest ay other way, if this is not feasible, to get the backend output after deploying the django web app. Thanks for the help. -
Use django, filter and get to the same id, but result data not same, why?
enter image description here just like this, I guess its beacause of caches, but i don't ensure, how should i do? thanks -
Is there any function to filter the field values based on another field value in django
model1 class Client(models.Model): client_name=models.CharField(max_length=20) company=models.CharField(max_length=200) finance_contact_email=models.EmailField(max_length=25,default=None) business_purpose=models.CharField(max_length=50,null=True,default=None) location=models.CharField(max_length=200) emergency_contact=models.CharField(max_length=200,null=True,default=None) website=models.URLField(max_length=200,null=True) comments=models.TextField(max_length=300,null=True, blank=True) start_Date = models.DateTimeField(max_length=10,null=True) end_Date=models.DateField(max_length=10,null=True) Model2 class Project(models.Model): project_name = models.CharField(max_length=20) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) description=models.TextField() type=models.TextField() start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) model3 class Job(models.Model): job_name=models.CharField(max_length=50) client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client',default=None) project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project',default=None) user=models.ForeignKey(User,on_delete=CASCADE,related_name='user',default=None) hours=models.TimeField(null=True) start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) Actually I need to filter the values based on the clients in the Job model. For example we will be giving the project_name on the Project model based on selecting the specific clients. So we need a filter in the Job model like if we select the specific client in the field, it needs to display only the projects available for that client in the project field of Job model. Now it is displaying all the projects which are inputted. Please help me get this solved as I am new to django. -
How to add optional parameters in a django view keeping the same url
Let's say I have the following URL: http://127.0.0.1:8000/en/project_page/1/ and my urls.py: path( 'project_page/<int:pid>/', views.project_page, kwargs={'approvalid': None}, name='project_page' ), Generally speaking, the users will always access via http://127.0.0.1:8000/en/project_page/1/ , but in some cases I want to pass an optional parameter so that the page renders optional content. For example, if the user access: http://127.0.0.1:8000/en/project_page/1/somevalue I would like to see the content of somevalue in my view, like: def project_page(request, pid, somevalue): if somevalue: #do something here with the optional parameter else: #run the view normally Once we get the optional parameter, I want the url structure to be the original: http://127.0.0.1:8000/en/project_page/1/somevalue -> get the value of the optional parameter and get back to the original url -> http://127.0.0.1:8000/en/project_page/1/ What I've tried: I thought kwargs would do the trick, but I did something wrong. I found this from the official docs (Passing extra options to view functions) but it seems that I'm doing something wrong. -
How to get user object based on username and not the (id, pk) in Django
I am having struggles viewing other profiles with the users username in the URL, I am able to see there pages with the users ID, but not with there usernames, this is the url now http://127.0.0.1:8000/user/30/, but I want to have this http://127.0.0.1:8000/user/reedlyons/. I know I could do it with the get_object_or_404, but I was wondering if there is another way around that. Here is my views.py def profile_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") try: profile = Profile.objects.get(user=user_id) except: return HttpResponse("Something went wrong.") if profile: context['id'] = profile.id context['user'] = profile.user context['email'] = profile.email context['profile_picture'] = profile.profile_picture.url return render(request, "main/profile_visit.html", context) urls.py urlpatterns = [ path("user/<user_id>/", views.profile_view, name = "get_profile"), ... -
Mathjax with Vue.js
I am rather stumped as to how I can render Tex equations in my html. I have a vue project with django in the backend as the CMS. I am using Ckeditor as a rich text field which uploads the equation within markdown from an api. In my vue page I can render all the text with no issues using v-html but my mathematical equations are rendering like this: \(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\) I have tried many ways to no avail and I can currently get a test equation to render by adding this to index.html <script> MathJax = { tex: {inlineMath: [['$', '$'], ['\\(', '\\)']]} }; </script> <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">. </script> and this to my vue page: <span class='math-tex'>( \(\frac{2}{7},\frac{2}{18}\) )</span> However I cant seem to get it to work with inline math and text. Here is my vue div: <template v-if="$store.state.user.isAuthenticated"> <template v-if="activeLesson"> <span v-html="activeLesson.long_description"></span> </template> </template> Whats strange as well is when I add the test equation <span class='math-tex'>( \(\frac{2}{7},\frac{2}{18}\) )</span> in the template v-f section it doesnt render? What am i doing wrong? Please halp. -
how to round a MoneyField in Django
Use django-money to reprent a product rate. The Model is defined as follows. class ItemPrice(models.Model): """ Item price """ rate = MoneyField(_('Unit rate'), max_digits=10, decimal_places=2, default_currency='USD') If I want to have the rounded rate in template, such as USD200 but not USD200.23, how to write the code? -
How to import swagger/?format=openapi to postman from django-rest-swagger without error of format not recognized?
Our project use django-rest-swagger to manage API, and we would like to export all api and import Postman, I can get JSON by below url localhost:5000/swagger/?format=openapi, but when I import the file, postman says Error while importing: format not recognized, How to import swagger/?format=openapi to postman from django-rest-swagger without error of format not recognized? Is there anyone who knows some easy way to solve it? Thanks so much for any advice. { swagger: "2.0", info: { title: "TestProjectAPI", description: "", version: "" }, host: "localhost:5000", schemes: [ "http" ], paths: { /api-token/: { post: { operationId: "api-token_post", responses: { 201: { description: "" } }, parameters: [ { name: "data", in: "body", schema: { type: "object", properties: { pic_id: { description: "", type: "string" }, phonenumber: { description: "", type: "string" }, checkcode: { description: "", type: "string" }, user_phone: { description: "", type: "string" }, phone_code: { description: "", type: "string" }, username: { description: "", type: "string" }, password: { description: "", type: "string" } } } } ], description: "User Login", summary: "User Login", consumes: [ "application/json" ], tags: [ "api-token" ] } }, /porject_management/: { get: { operationId: "porject_management_list", responses: { 200: { description: "" } … -
Using metamask to authenticate a SSO flow
Is it possible to do something like a social signup/login using crypto wallets like Metamask? Analogous to signup/login with Google/Facebook/Apple... Does the concept even make sense? I'm thinking that the user could prove he owns the wallet, but there is no profile data like email/name/avatar so basically every usual datapoint of signup must be provided manually anyway, so what would be the point in some sense. If it is possible, are there any libraries that support this in Django/Python? -
How to pass multiple arguments from one template to another template?
I'm creating a to do list, and on the detail page I have a list of tasks. And when I click on the delete button on the side of the task, it will bring me to a delete confirmation page. Question I've been stuck for a long while trying to figure a way to pass in 2 different pks(dailies.pk & task.pk) from the detail page to the delete confirmation page, so that I can click the delete button to delete task(associated with task.pk) or click "back" to return to the previous page(with dailies.pk as a reference). Currently i'm only able to pass in one argument dailies_detail.html: <h3> <p> {{dailies.date}} Dailies pk({{dailies.pk}}) <a href="{% url 'task-create' dailies.pk %}">Add task</a> </p> {% for todo in dailies.dailytask_set.all %} <br> {{todo.task}} {{todo.pk}} <a href="{% url 'task-delete' todo.pk %}"> Delete</a> {% endfor %} </h3> I tried to do {% url 'task-delete' todo.pk dailies.pk %}, that didn't work URLS: urlpatterns = [ path('', DailiesListView.as_view(), name='home'), path('dailies/<int:pk>/', DailiesDetailView.as_view(), name='todo-detail'), path('dailies/<int:pk>/task-create/', TaskCreate.as_view(), name='task-create'), path('dailies/<int:pk>/task-delete/', TaskDelete.as_view(), name='task-delete'), # I kind of wanted to do something like 'dailies/<int:dailies_pk>/task-delete/<task_pk>/' ] I know that I need to do something with the URL in order to take in both arguments, not quite sure … -
Django no static files after deploying to AWS Elasticbeanstalk?
I have successfully deployed django application to single instance elasticbeanstalk. But the issue is that, css and js are not loading up. As by default Elastic Beanstalk uses Nginx, i think i am missing something. Note: I have used certbot for ssl and ngnix configs are updated by certbot. My django settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ BASE_DIR / 'project/static' // All static files at this directory only ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'project/static/files') In the above, I have a directory inside project called static. And all my static files are presented over there only. And my elastic beanstalk config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static container_commands: 01_collectstatic: command: "source $PYTHONPATH/activate && python manage.py collectstatic --noinput" Note: I have moved my django settings to separate folder named config. And by adding this aws:elasticbeanstalk:environment:proxy:staticfiles elastic beanstalk added a new section named Static files and it also has /static and static Am not sure where am doing wrong. As i have already mentioned aws:elasticbeanstalk:environment:proxy:staticfiles am not sure if i need to add alias to ngnix config for static files. Please advice. -
The problem with django in the server must be closed and opened every time
I am facing a problem with django. The server must be closed every time something changes, even if it is in the link, for example, localhost:8888/admin and I run the server and visit the site, the control panel appears, but when I change the link in the urls file. py to localhost:8888/any, the browser says that the link does not exist and shows me the option localhost:8888/admin, note that the problem appeared recently and appeared only when using template html and linking it to the project