Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cant join two models on Django rest api and get a specific output
Hello guys I am new in Django REST API. I want your help. I am trying to join my two models : User and blogs to get specific api output like this: { "blog_id": 1, "title": "first blog", "description": "hola", "image": "/images/phone.jpg", "create_at": "2021-04-08T14:24:51.122272Z", "update_at": "2021-04-08T14:37:00.287746Z", "user": 1, "user_name": "superuser", "first_name": "Dannis", "email": "superuser@test.com" } Here is the models.py class Blog(models.Model): blog_id = models.AutoField(primary_key=True, editable=False) title = models.CharField(max_length=128,null=False,blank=False) description = models.TextField(null=True,blank=True) image=models.ImageField(null=True,blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True, editable=False) update_at = models.DateTimeField(auto_now=True,editable=False) def __str__(self): return f'{self.user.username} {self.title} {self.create_at} {self.update_at}' class UserActive(models.Model): user_active_id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False) last_active = models.DateTimeField(auto_now_add=True, editable=False) Here is the views.py @api_view(['GET']) def get_blogs(request): blogs = Blog.objects.all() serializer = BlogSerializers(blogs, many=True) return Response(serializer.data) @api_view(['GET']) def get_users(request): user = User.objects.all() serializer = UserSerializer(user, many=True) return Response(serializer.data) here is the serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'first_name', 'is_staff', ] class BlogSerializers(serializers.ModelSerializer): class Meta: model = Blog fields = '__all__' Please Help me out. I will be so grateful -
Django m2m field on signals getting overridden
I am adding a m2m field on signals, but it gets overridden after the signal call. But when using django admin it does not get overridden. Here's the signal.py snippet @receiver(post_save, sender=Category) @on_transaction_commit def update_properties(sender, instance: Category, created, *args, **kwargs): print("Adding tag 5: Asdf") instance.tags.add(5) on_transation_commit decorator def on_transaction_commit(func): def wrapper(*args, **kwargs): transaction.on_commit(lambda: func(*args, **kwargs)) return wrapper views.py class CategoryUpdateView(PermissionRequiredMixin, TagFormMixin, UpdateView): model = Category form_class = CategoryForm template_name = '.....' tag_class = Tag permission_classes = [...] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) .... return context TagFormMixin class TagFormMixin: tag_class = None def get_tag_class(self): return self.tag_class def get_form_kwargs(self): ... creates tags if does not exist ... As much I can understand, after the post_signal is done executing, somewhere in View/Form tags are overriden -
Place image on page that users can refer too using "src" in an "img" tag (Django)
How do I place an image that people can refer to i.e via a link just like this ? If I just place a normal <img src="{% static 'media/my_img.png' %}"> in my template and inspect the site, the source is static/media/my_image.png. I want to be able to refer to specific images from my webpage in an email using html like<img src="my_page.com/logos/my_image.png> -
Django admin dependent drop down (no models)
models.py class Document(models.Model): word_type = models.CharField(max_length=255, choices=[('noun', 'noun'), ('verb', 'verb'), ('adjektive', 'adjektive')], default='noun') word = models.CharField(max_length=255) article = models.CharField(max_length=255, choices=[('the','the), ('-','-')], default='') forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['word_type', 'word', 'article'] def __init__(self, *args, **kwargs): super(DocumentForm, self).__init__(*args, **kwargs) if self.instance.word_type == "noun": self.fields['article'].choices = [('the', 'the')] else: self.fields['article'].choices = [('-', '-')] I have a model 'document'. When creating a document object in django admin, I want the article dropdown (actual language has several articles) only to show up when 'noun' is selected as word type. Currently I got it working to update the choices to '-' if it's not a noun, but the dropdown only updates with init. So I'm looking for a way to update the article dropdown automatically when word type changes. Maybe there is another (better) way of doing it, would be great if there was a solution to make article dropdown completely disappear when 'verb' or 'adjective' is selected as word type. I'm fairly new to django, couldn't find a solution for this since most tutorials assume article and word_type are dependent models, which is not the case for me. -
Django Oscar, how to make product price dynamic, by allowing users to enter their own value
Im using django-oscar as my e-commerce library, What I want to do is to give users an input field they can use to enter the amount they want to pay for a product When a user presses the add to cart, button they are presented with a Price Input Field How can I archieve this? -
Uploading Django website to Godaddy using Cpanel
I build a website using django(+html,css,js,bootstrap). I check my site on wampserver and its complete. Now i want to upload it to my domain on godaddy using cpanel but i have no idea how to do it. Can anyone explain it to step by step. -
django form dropdown return key instead of value
I have populated dropdown list by values as pk and key as names in my django form. <select name='user_name_fk' id='id_user_name_fk'> <option value='1'>name1</option> <option value='2'>name2</option> <option value='3'>name2</option>.... </select> When i post a form, i get keys(names) asa output instead of values(pk). when i print(form.cleaned_data['user_name_fk']) output is 'name'. As i get text as a output as "text", i cant able to update foriegn key field(error : Cannot assign "'1'": "TABLENAME.user_name_fk" must be a "TABLENAME" instance). i do not know where i do the errors. i would like to get oupt as form.cleaned_data['user_name_fk']=pk. Can anybody help me to find a solution pls? Thanx in advance forms.py class MyTable2Form(forms.ModelForm): user_name_fk= forms.ChoiceField( label='Names', required=True, choices=MyTable1.objects.all().values_list('pk','user_name'), widget=forms.Select( attrs={'class':'form-select'} ) ) class Meta: model = MyTable2 fields = ['user_name_fk'] class MyTable3Form(forms.ModelForm): user_name_fk= forms.ModelChoiceField( label='Names', required=True, empty_label='-- Names --', queryset=MyTable1.objects.only('pk','user_name'), widget=forms.Select( attrs={'class':'form-select'} ) ) class Meta: model = MyTable2 fields = ['user_name_fk'] models.py class MyTable1(models.Model): table1_id=models.AutoField(primary_key = True) user_name= models.CharField(max_length=100) def __str__(self): return (self.user_name) class MyTable2(models.Model): table2_id=models.AutoField(primary_key = True) user_name_fk= models.ForeignKey(MyTable1, blank=True, null=True, on_delete=models.CASCADE, default=None) def __str__(self): return (self.user_name_fk) views.py class Page2view(TemplateView): template_name='logout.html' def get_context_data(self, *args, **kwargs): context=super().get_context_data(**kwargs) context={'form':MyTable2Form()} return context def post(self,request): form=MyTable2Form(request.POST) if form.is_valid(): reg=form.save(commit=False) #print(form.cleaned_data['user_name_fk']) reg.user_name_fk=MyTable1.objects.get(table1_id=form.cleaned_data['user_name_fk']) reg.save() messages.success(request,'Form is saved successfully') return HttpResponseRedirect('/page2/') class Page3view(TemplateView): … -
how to change email for user and confirm it using usercreationform - django
how to change email for user and confirm it using usercreationform , i want allow user to change email in his profile and when he enter new email he must activate email to save it in his profile forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), name='emailchange'), path('activate/<uidb64>/<token>/', ActivateAccount.as_view(), name='activate'), ] change email html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="fadeIn fourth" style="background-color:#7952b3" value=" change "> </form> -
When does the save method in a DJango model not run?
I have a Django model that overrides the save method and looks like this: class Log(models.Model): agent = models.ForeignKey(Agent, on_delete=models.CASCADE) calls_logged = models.IntegerField(default=0) texts_logged = models.IntegerField(default=0) completed_logs = models.BooleanField(default=False, db_index=True) def save(self, *args, **kwargs): if self.calls_logged >= 30 and self.texts_logged >= 50: self.completed_logs = True super().save(*args, **kwargs) What's supposed to happen is when the Agent reaches 30 calls and 50 texts, the save() method is supposed to change the completed_logs field to True. But when I recently checked my DB, an agent had reached over 30 calls and over 50 texts but completed_logs wasn't marked as completed. So, my question is: is there ever a time that Django will not call the save() method on a model? Is there a better way to do this? -
Django [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'MYSCHEMA.MyUnmanagedModel'
I'm running into this issue: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'MYSCHEMA.MyUnmanagedModel'. It's an unmanaged model, so I understand that I have to create the table manually ahead of time. Here is the model: class MyUnmanagedModel(CampusModel): id = models.IntegerField(db_column="ID", primary_key=True) end_year = models.IntegerField(db_column="endyear") grade = models.CharField(db_column="grade", max_length=2) enrollments = models.IntegerField(db_column="enrollments") class Meta(object): managed = False db_table = "[MYSCHEMA].[MyModelTable]" I have ensured that my docker database contains the appropriate 'MYSCHEMA' with the table 'MyModelTable' and that it's built out appropriately with respect to the model (all the appropriate columns). I'm using factory-boy to create the object: here is my Factory: class MyUnmanagedModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyUnmanagedModel database = "secondary_database" id = factory.Sequence(lambda n: n) end_year = 2021 grade = 1 enrollments = 1200 I use multiple databases in my project, the 'secondary_database' is the one that holds the database with the appropriate schema. DATABASES = { "default": { "ENGINE": "mssql", "NAME": os.environ.get("default_NAME"), "HOST": os.environ.get("default_HOST"), "USER": os.environ.get("default_USER"), "PASSWORD": os.environ.get("default_PASSWORD"), "PORT": os.environ.get("default_PORT"), "OPTIONS": { "host_is_server": True, "driver": os.environ.get("ODBC_DRIVER"), }, }, "secondary_database": { "ENGINE": "mssql", "NAME": os.environ.get("secondary_NAME"), "HOST": os.environ.get("secondary_HOST"), "USER": os.environ.get("secondary_USER"), "PASSWORD": os.environ.get("secondary_PASSWORD"), "PORT": os.environ.get("secondary_PORT"), "OPTIONS": { "host_is_server": True, "driver": os.environ.get("ODBC_DRIVER"), }, }, Using DataGrip or Azure … -
Django fetch manytomany values as list
class Groups: name = models.CharField(max_length=100) class User: firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) group = models.ManyToManyField(Groups) i need user details with groupname as list not as separate records. User.objects.values('firstname','lastname', 'group__name') While i'm querying like above, i'm getting like this <QuerySet [{'firstname': 'Market', 'lastname': 'Cloud', 'group__name': 'Group 5'}, {'firstname': 'Market', 'lastname': 'Cloud', 'group__name': 'Group 4'}]> but i want like this <QuerySet [{'firstname': 'Market', 'lastname': 'Cloud', 'group__name': ['Group 5', 'Group 4']}]> -
How to query data from real Database created by django-pytest db fixture
I write db-related tests for my django project using pytest. I use db fixture for creation of records in the database. Test works fine but how to select these records from real Postgres db. When I try to select these records via PgAdmin I get empty list. Can you please clarify how db fixture works and where does it store records? -
How to export all models in the same file with django-import-export?
I want to use django-import-export to manage export in my project. But, I can figure out how to export all models in the same file with django-import-export Can find in the doc a way to do that. I am only able to export model by model... -
Why Role Rights Are Not Assigned to a User?
Why when I create a user and assign a role to him the role rights are not assigned? self.request.user.get_user_permissions() returns empty tuple -
Cannot scroll through video using scrollmagic in django
I'm building a web app where video plays along the scroll, it works completely fine but when I incorporated it in django the video dosen't play while scrolling anyore. I have used scrollmagic plugin and jquery in javascript. And i have included static_root in setting.py and I have also tried accessing the video from media file from django but still it didn't work. HTML file : <main class="content"> <div class="container"> <video src="{% static 'images/My Video.mp4' %}"></video> </div> </main> I'm still new to javascript I tried this by watching youtube tutorials Javascript file : var controller = new ScrollMagic.Controller(); const video = document.querySelector('video'); var scene2 = new ScrollMagic.Scene({ duration: 9000, triggerElement: "main", triggerHook: 0 }) .addIndicators() .setPin('main') .addTo(controller); let scrollpos = 0; let accelamount = 0.1; let delay = 0; scene.on("update", e => { scrollpos = e.scrollPos / 700; }); setInterval( () => { delay += (scrollpos - delay) * accelamount; // console.log(scrollpos, delay); video.currentTime = delay; }, 20); settings.py # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] I know it's not right to access video file from static, but even when I fetch video by creating 'media_root' and use 'media_url' it didn't work. … -
Filterset field not working for multiple object
filterset field not working for multiple leave of a single employee leave details, how may i solve this? class LeaveApplicationGetUpdateView(RetrieveUpdateAPIView): serializer_class = LeaveApplicationSerializers queryset = LeaveApplication.objects.filter() permission_classes = (IsAuthenticated, IsSuperUser) filter_backends = [filters.OrderingFilter, DjangoFilterBackend] filterset_fields = ['type', 'from_date', 'to_date'] def get(self, request, *args, **kwargs): contact_inf = LeaveApplication.objects.filter(employee__code=self.kwargs.get('code')) # will be refactor if contact_inf: return Response({ 'success': True, 'message': 'Successfully', 'data': LeaveApplicationSerializers(contact_inf, many=True).data }, status=200) else: return Response({ 'success': False, 'message': 'Not Found' }, status=200) -
django-filter-2.0 + django 2.2 + Strictness Behaviour
I have the django 1.11 code as below and we are using django-filter==1.0 library for filters. and below is the code according to django 1.11 Models: class BaseItem(models.Model): CHOICES = ( (STATUS_ACTIVE, 'Active'), (STATUS_INACTIVE, 'Inactive'), ) class Item(BaseItem): name = models.CharField(null=True) symbol = models.CharField(null=False) Filter class ItemFilterSet(django_filters.FilterSet): status = django_filters.MultipleChoiceFilter(choices=Item.CHOICES, widget=CSVWidget) class Meta: model = Item fields = ['symbol'] strict = STRICTNESS.RAISE_VALIDATION_ERROR Viewset class ItemViewSet(ModelViewSet): http_method_names = ['get', 'post'] serializer_class = ItemSerializer queryset = Item.objects.all() filterset_class = ItemFilterSet def filter_queryset(self, queryset): try: return super().filter_queryset(queryset) except ValidationError as e: if 'symbol' in e.error_dict: raise exceptions.ValidationError(detail=e.message_dict) raise e But in Django 2.2 version we have used django-filter==2.0 library, but in this library, this strictness has been moved to view as per below link. https://django-filter.readthedocs.io/en/master/guide/migration.html#filterset-strictness-handling-moved-to-view-788 django-filter other github link https://github.com/stephenfin/django-filter/commit/552c35ac45b965c2d68e97f9cfdeef940f17d6ea So my question is, according to django-filter 2.0 and django 2.2 , in the view, I dont need to handle strictness according to second link ? it will be by default will have strictness behaviour(STRICTNESS.RAISE_VALIDATION_ERROR) in view ? or should i write some code for this in view ? -
How to check_object_permissions on @api_view functions?
I defined a view function with the @api_view decorator. Now I would like to test object-level permissions in this object. I know there is a check_object_permissions that would let me check the permissions I defined on my view, but I don't know how to call it. The documentation gives examples for classes, not functions. @api_view(["GET"]) @permission_classes([IsAuthenticated & IsOwnerOfItem]) def query_something_related_to_items(request, item_id): item = get_object_or_404(Item, id=item_id) # I want to test IsOwnerOfItem here, # I guess I need to call something like: # "self".check_object_permissions(request, item) # custom code here return something class IsOwnerOfItem(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.owner == request.user the documentation says: If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object. But how do you call this in an view function? -
How to deploy Django apps independently using Docker?
We have a large Django project that is deployed weekly using Docker container, Nginx and Kubernetes cluster. This project has some smaller apps that often receive changes and fixes mid-week that would be nice to have in production immediately but they need to wait for the project deployment on the following week. Knowing that these apps in Django are not standalone and depend on other files/folder/settings, I would like to find a way to have a separate deployment cycle for these apps so the changes could be reflected more often than once a week but without affecting the whole project. I was thinking about using different Docker containers but I am not proficient in it yet to know if this is the best solution. I still find it a bit hard to visualize how to deploy just some "folders" of the project and have everything working together. What would be the best approach here? -
I want to upload multiple images for one product without creating another table for images
I want to store images path in single field "like store them in JSON field {'image1','image2'}" and then display the images in a slider. I'm using Angular 11 and Django. -
Ordering related model values in django-rest admin view
I want to see this view with the features list sorted alphabetically. The model from the view above comes from is AircraftModel. models.py: class AircraftModelFeature(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class AircraftModel(models.Model): features_list = models.ManyToManyField(AircraftModelFeature) # ... other stuff ... def __str__(self): return self.name serializers.py class AircraftModelFeatureSerializer(serializers.ModelSerializer): class Meta: model = AircraftModelFeature fields = "__all__" class AircraftModelSerializer(serializers.ModelSerializer): features_list = AircraftModelFeatureSerializer(many=True, read_only=True) # ...other stuff... class Meta: model = AircraftModel fields = ['id', 'features_list',] # there are more fields, omitted views.py class AircraftModelFeatureViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = [IsAdminOrReadOnly] queryset = AircraftModelFeature.objects.all().order_by('name') serializer_class = AircraftModelFeatureSerializer class AircraftModelViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = [IsAdminOrReadOnly] queryset = AircraftModel.objects.all().order_by('name') serializer_class = AircraftModelSerializer So, how can I make that list sorted? -
set env variable from a Makefile command and use in another Make command
I'm trying to connect to the Google Cloud SQL DB instance from my local machine inside a Django project. As you might know, we can create management commands in Django. So I created two management commands which basically does some ETL stuff. To make my life simple, I actually created commands in Makefile for these mgmt commands. mgmt_cmd_1: $(eval DB_HOST := $(gcloud sql instances describe <GCP_DB_INSTANCE> --project <GCP_PROJECT_ID> --format="value(ipAddresses.ipAddress)")) DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_1 mgmt_cmd_2: $(eval DB_HOST := $(gcloud sql instances describe <GCP_DB_INSTANCE> --project <GCP_PROJECT_ID> --format="value(ipAddresses.ipAddress)")) DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_2 Now as you can see some part(1st line) is duplicate. in both above commands. I want to get rid of that duplicacy. I want something like below so that I can reuse even if in future I have more than 2 mgmt commands. get_db_host_ip: $(eval DB_HOST := $(gcloud sql instances describe <GCP_DB_INSTANCE> --project <GCP_PROJECT_ID> --format="value(ipAddresses.ipAddress)")) mgmt_cmd_1: DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_1 mgmt_cmd_2: DB_HOST=$(DB_HOST) python manage.py mgmt_cmd_2 I guess probably I can wrap these two commands and create another Make command, like below. but not sure if that always works. mgmt_cmd: @$(MAKE) get_db_host_ip @$(MAKE) mgmt_cmd_1 So I'm wondering if there is even a better way to do this? maybe using some kind of … -
responsive img for site [closed]
I have a board that I want to stay together like this photo But when the page shrinks a bit, the two images are broken and placed at the bottom of each other like a yen. I want the photos to make themselves smaller when the screen gets smaller. Thank you for your help -
How to export and migrate OpenSlides database?
I encountered an error message while exporting my OpenSlides database. My goal is to switch from a SQLite database to PostgreSQL database in OpenSlides, but unfortunately, as I said, exporting doesn't quite work. Can someone help me please? Error Message: ModuleNotFoundError: No module named 'settings' -
How to create a chart of total number of analyzes made in months?
I created a customer management system with Django. Every user has several customers and every customer has several reports. Users make analyses of these reports and send them to a user. This process is ApprovalProcess. I have an ApprovalProcess model and I want to create a line chart that shows the total number of analyzes made in months during the year. (By using begin_date) How can I do that? models.py class ApprovalProcess(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter') doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True) begin_date = models.DateTimeField(null=True) ... views.py def approval_context_processor(request): all_approvals = ApprovalProcess.objects.filter(user_id__company=request.user.company) ... dashboard.html ... <div class="chart-container" style="min-height: 375px"> <canvas id="statisticsChart" ></canvas> </div> <script> var ctx = document.getElementById('statisticsChart').getContext('2d'); var statisticsChart = new Chart(ctx, { type: 'line', data: { labels: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], datasets: [ { label: "# of Approval", borderColor: '#54bbf3', pointBackgroundColor: 'rgb(84,187,243, 0.6)', pointRadius: 0, backgroundColor: 'rgba(84,187,243, 0.4)', legendColor: '#f3545d', fill: false, borderWidth: 1, data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], }, ] }, options : { responsive: true, maintainAspectRatio: false, legend: { display: true }, tooltips: { bodySpacing: 5, mode:"nearest", intersect: 0, position:"nearest", xPadding:20, yPadding:20, caretPadding:10 }, layout:{ padding:{left:5,right:5,top:15,bottom:15} }, scales: { yAxes: [{ ticks: { fontStyle: "500", beginAtZero: true, maxTicksLimit: 5, padding: 10 }, gridLines: { drawTicks: false, display: false …