Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Messed up trying to install backports, ending killing dnf and yum
so everything is in the title, im working on fedora30 os, on a django project, and for no reason i couldnt start another one with django-admin startproject. 1 - i got a message telling me backports need to be installed, 2- i did the command to instal it, got a error telling me its not possible for whatever reason. 3 (where the fun begins) - got tired of it, proceded to do a rm-rf on python2.7 and 3.4 folder in order to keep only python 3.9 4 - reinstalling python 5 - dnf and yum missing, and now im starting to think i really messed up all of this i dont mind if someone can help me fixing this problem what i got in the command prompt right after using any dnf or yum command : Traceback (most recent call last): File "/usr/bin/yum-config-manager", line 75, in <module> from dnf.cli import main ModuleNotFoundError: No module named 'dnf' -
how to use a models and create a form to save in the data_base
so, i created this models, like person and the text, i want to create a form in html and call these models and save then in the data base. Note: every text must have the person ID, the person ID is like the author, you know? from django.db import models from django.utils import timezone #onde é trabalhado a parte de dados # Create your models here. from django.utils import timezone # class Text(models.Model): title = models.CharField(max_length=255) description = models.TextField() datesss = models.DateTimeField(default=timezone.now) Person = models.ForeignKey(Person, on_delete=models.DO_NOTHING) def __str__(self): return self.description class Person(models.Model): name = models.CharField(max_length=255)# charfiel é STR surname = models.CharField(max_lenght=255) user = models.CharField(max_lenght=255) #telefone = models.CharField(max_length=255, blank=True)#blank se torna opcional email = models.CharField(max_length=255) password = models.CharField(max_length=255) #description = models.TextField(blank=True) photo = models.ImageField(blank=True, upload_to='pictures/%Y/%m/%d') #criar pasta pelo dia mês ano def __str__(self): return self.name -
how to find a way for a continuous cycle? using django?
new price is the price taken from the marketcapapi. I would like that every time the user buys coins, the coins are transferred to the ALGO_wallet leaving n_ALGO_coin at zero (= 0). The first time the user buys, everything is ok, the transfer is done, while the second time the data remains both in n_ALGO_coin and also in ALGO_wallet. I tried with a for loop but it tells me that the object is no interable def buyalgomkt(request): new_price = algoValue() if request.method == "POST": form = PurchaseForm(request.POST) if form.is_valid(): form.save(commit=False) profile = Profile.objects.get(user=request.user) if profile.USD_wallet > 0 and form.instance.max_spend_usd < profile.USD_wallet: form.instance.purchased_coin = form.instance.max_spend_usd / form.instance.price_mkt profile.n_ALGO_coin += form.instance.purchased_coin profile.USD_wallet -= form.instance.max_spend_usd profile.ALGO_Wallet += profile.n_ALGO_coin profile.n_ALGO_coin = profile.ALGO_Wallet - profile.n_ALGO_coin form.save() profile.save() name = request.user name.save() messages.success(request, 'Your order has been placed and processed') else: messages.warning(request, 'You do not have enough money') return redirect('purchase') else: return HttpResponseBadRequest() else: form = PurchaseForm() return render(request, 'coinmarketalgo/purchase.html', {'form': form, 'new_price': new_price}) .. how can I do? class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) ips = models.Field(default=[]) subprofiles = models.Field(default={}) n = random.randint(1, 10) n_ALGO_coin = models.FloatField(default=algoValue() * n) ALGO_Wallet = models.FloatField(default=0) purchased_coin = models.FloatField(default=0) USD_wallet = models.FloatField(default=10000) profit = models.FloatField(default=0) class … -
Attribute Error 'list' object has no attribute 'get' in Django
I'm facing a issue while getting the data from the 'POST' method I'm getting an error as Attribute Error at api/Data/SaveUserResponse/ 'list' object has no attribute 'get' Django . The response which I get in the payload [{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}] Views.py: @api_view(['POST',]) def SaveUserResponse(request): if request.method == 'POST': auditorid = request.data.get('AuditorId') print('auditorid---', auditorid) ticketid = request.data.get('TicketId') qid = request.data.get('QId') answer = request.data.get('Answer') sid = '0' TicketType = request.data.get('TicketType') TypeSelected = request.data.get('TypeSelected') agents = request.data.get('Agents') supervisor = request.data.get('Supervisor') Comments = request.data.get('Comments') action = request.data.get('Action') subfunction = request.data.get('AuditSubFunction') region = request.data.get('AuditRegion') print('Region---', region) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s,@agents=%s, @supervisor =%s, @Comments=%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region)) return Response(True) urls.py: path('Data/SaveUserResponse/', SaveUserResponse, name='SaveUserResponse'), -
Apply django migration if constraint doesn't exist yet
I want to add a constraint to my django model. I want this migration to do nothing if the constraint has already been added (manually in sql, not by django). I know how to check if constraint is already applied thanks to this question. However, how could I skip the "add constraint" operation in my migration file based on this condition? Do I need to create a RunPython operation or can I rely on django migration objects? I am using postgres. -
how to apply constraints on Django field within the instances associated with the user
I am a django beginner and making a todo app for practice, the functionality I want to achieve is that, when a user create a task,Only the time field should be unique about all of his tasks, I have done (unique=True) In the time field in model but that make it unique all over the database, but I want it to be unique only with the tasks associated with the user. the view is below: @login_required(login_url='login') def home(request): tasks = Task.objects.filter(name__username=request.user.username) form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.name = request.user obj.save() return redirect('home') else: print(request.POST) print(request.user.username) messages.warning(request, 'Invalid Data!') return redirect('home') context = {'tasks' : tasks} return render(request, 'task/home.html', context) task model: class Task(models.Model): choices = ( ('Completed', 'Completed'), ('In Complete', 'In Complete'), ) name = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) task = models.CharField(max_length=200, null=False, blank=False) time = models.TimeField(auto_now_add=False, blank=True) status = models.CharField(max_length=200, choices=choices, null=True, blank=False) def __str__(self): return self.task def get_task_author_profile(self): return reverse('profile') as you can see, I want to show the task that the logged in user has added. the form is: class TaskForm(ModelForm): class Meta: model = Task fields = '__all__' exclude = ['name'] the functionality I talked about … -
Bootstrap CDN overrides custom CSS in Django
I have tried everything mentioned on the internet but yet bootstrap CDN overrides the custom CSS file. The HTML file: {%extends 'movies/base.html'%} {%block content%} {% load static %} <!DOCTYPE HTML> <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <div class="section"> <h1>Recommend Me:</h1> <form action="recommendation" method="post"> {% csrf_token %} <input type="text" name="emotion" /> <button type="submit" name="button">Find</button> </form> <div class="video-container"> <div class="color-overlay"></div> <video autoplay loop muted > <source src="{% static 'movies/intro.mp4' %}" type="video/mp4"> </video> </div> </div> <div class="shows"> <h2 class="mt-5">Shows you might like:</h2> <br> <div class="row"> {%for tvshow in tvshows%} <div class="col-lg-5 col-md-6"> <a href="{{ tvshow.url }}"> <img src="{{ tvshow.image.url }}" class="img-fluid mb-2"> </a> <h3>{{ tvshow.title }}</h3> </div> {% endfor %} </div> </div> </body> </html> {%endblock%} I tried adding the attribute !important in CSS but yet it didn't work. CSS file: *{ box-sizing: border-box; margin: 0; padding: 0; font-family: 'Poppins'; } .video-container video{ position: absolute; top: 0; left: 0; width: 100%; height: 570px; object-fit: cover; z-index: 1; opacity: 0.8; } .section h1{ position: relative; text-align: center; font-size: 4rem; padding: 20px; margin: 15px; top: 100px; z-index: 2; opacity: 0.6; } .section form{ position: relative; … -
Django admin count numbers of rows before adding a new data in StackedInline mode
In my django project i have a model related to a main model like this one: class Device_Docs(models.Model): id = models.AutoField(primary_key=True) master_id = models.ForeignKey(Device, on_delete=models.CASCADE) device_file = models.FileField(upload_to='uploads/', validators=[FileExtensionValidator(['pdf', 'jpg', 'txt', 'png', 'jpeg']), validate_fsize], verbose_name="Select File", help_text='Allowed formats are PDF, JPG, JPEG, TXT, PNG, max size 3Mb') title = models.CharField(max_length=250, help_text='Document title') description = models.TextField(default='', verbose_name="Descrizione", null=True, blank=True) load_data = models.DateField(default=datetime.now(roma).strftime("%Y-%m-%d %H:%M:%S.%f"), verbose_name="Load data") owner = models.ForeignKey('accounts.CustomUser', related_name='odevdocs', on_delete=models.CASCADE) ... Now i would to show in my admin, for the Device model (main model) using StackedInline option both models data: class DocsInline(admin.StackedInline): model = Device_Docs extra = 1 @admin.register(Device) class DeviceModelAdmin(admin.ModelAdmin): list_display = ('mac_id', 'short_name', 'proj_type', 'polling_interval', 'active', 'autoupdate', 'save_date') list_filter = ('polling_interval','proj_type', 'active', 'autoupdate') search_fields = ('short_name', 'save_date' ) ordering = ('-save_date', 'mac_id') readonly_fields = ('mac_id', ) inlines = [PortinInline, DocsInline] def has_delete_permission(self, request, obj=None): return False def get_form(self, request, obj=None, **kwargs): self.exclude = ("owner", "save_date") form = super(DeviceModelAdmin, self).get_form(request, obj, **kwargs) return form Ok all works good, now my question is, how can i control the numbers ofrows already entered about Device_Docs data before save? For exmple i would block the possibility about insert data if in model there are more then 5 records with the same master_id … -
Django run a command once the server starts [duplicate]
I have a setup function which can only be run once the app has started and is answering requests, but which I would like to run only once when the server starts. Is there a hook or other way to run a setup function after Django has completed the "peforming system checks..." and gotten to the point where it has emitted "Quit the server with CONTROL-C."? -
Django model tab-complete in ipython
I wish to use ipython to create a custom command-line interface to query Django model objects. So for example I'd like to type: my_models.MyModelClass.h <TAB> And have all of the elements of the MyModelClass table that start with "h" be used as the tab complete. I could achieve this by creating a startup script and creating an object heirachy which matches the table structure, however that will be slow, and I'd prefer to only create the request on demand. Is there a more direct way to use ipython's tab complete, for example a function which is called to get the tab complete list when tab is invoked? -
docker-compose can't find django-admin in $PATH, but I can run django-admin commands separately
I'm trying to test a django app in a docker image. I have followed the tutorial until the it starts the django project. When I run, docker-compose run web django-admin startproject composeexample . I get Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "django-admin": executable file not found in $PATH: unknown ERROR: 1 It's weird because I can run django-admin createproject ... seperately. Any thoughts? I have added the ..\python39\scripts in the path. Also I have python 3.9.10 from the windows store. -
Django-CMS slug in if statement in HTML
I am trying to write an if statement to change what the link links to, based on the slug URL. I get an error in the if_statement. Shouldn't this work? <div> {% if page_attribute "slug" == 'hjem' or page_attribute "slug" == 'home' %} <a href="/no/">NO</a> / <a href="/en/">EN</a> {% else %} <a href="/no/{% page_attribute 'slug' %}">NO</a> / <a href="/en/{% page_attribute 'slug' %}">EN</a> {% endif %} </div> -
Django admin login wont respect custom next param
I want to redirect to a custom page (next='reports/fooreport') after Django admin login. I have a page in Django to be accessed by authenticated users. If I hit the URL let's say /reports/fooreport and I am redirecting the user to admin login with next='/reports/fooreport' using HttpResponseRedirect('%s?next=%s' % (reverse('admin:index'), '/reports/fooreport')) After successful login, Django is not redirecting to the next URL. However, it works pretty well for its internal apps like if I hit any admin page without login it appends in URL with next param and post login it redirects to this URL. Is there anything we can do to make it work? -
How do I filter wagtail images by a queryset?
I have following page structure: blog_ |_contributor 1 |_Post 1 |_Post 2 |_contributor 2 |_Post 3 |_Post 4 |_Post 5 Editors take the content provided by contributors and upload that content on their behalf. Editors can therefore create posts as children of each contributor. To avoid accidental copyright infringements in the use of image materials, I would like the ImageChooserPanel to only display images uploaded to the pages of a given contributor, i.e. when a post is created as a child of a given contributor, the ImageChooserPanel should only display images uploaded to the pages of that contributor (or allow additional image upload). A manual solution would be to manually create a collection for each contributor and upload and select from that section. However, that would create too much overhead, given a high number of contributors. I've tried to figure out a solution with the use of a custom image model that contains a foreignkey to the contributor in combination with a construct_image_chooser_queryset hook, but have so far fallen short. -
Summation of fields in SQL Query or getting results and then looping in code?
I have more than 100K rows in my table. I want to get the sum of data with id='x' (Filtered data would be 50-100 rows). What should I prefer? SQL Sum or get the filtered data and sum the data using loop. Option 1 query = 'SELECT SUM('field_1) as qunatity_1, SUM(field_2) as quantity_2....SUM(field_15) as quantity_3 from BOOKS where id=10' Should I just hit this query and get the required data Option 2 query = 'SELECT field_1, field_2...field_15 from BOOKS where id=10' loop on the received rows and sum the fields to get required data -
How to perform left join in django?
i like to join two tables using left join operation. this is what i like to do: SELECT * FROM orders LEFT JOIN products ON (orders.product_id = products.id); my model classes: class Orders(models.Model): name = models.CharField(max_length=100, null=False, blank=False) qty = models.IntegerField(null=False, blank=False) product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customers, on_delete=models.CASCADE) class Meta: db_table = 'orders' class Products(models.Model): name = models.CharField(max_length=100, null=False) qty = models.IntegerField(default=0, null=True) price = models.FloatField(null=True, default=0) description = models.CharField(max_length=500, null=True, default=None) class Meta: db_table = "products" -
How can increment a variable value in jinja
How can increment a variable value in jinja (django template language).. {% with a=0 %} {% with b=4 %} {% endwith %} {% endwith %} i used above code to assign value to a variable. i want to increment it with 4. -
how to pass SQL output parameter in rest framework
I'm trying to pass the Output parameter @response in Django views but I couldn't able to achieve it. I have tried two approaches here, what I have tried views.py: approach1: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method == 'POST': agents = request.data.get('Agents') Output = request.data.get('Answer') AuditorId = request.data.get('AuditorId') TicketId = request.data.get('TicketId') QId = request.data.get('QId') Answer = request.data.get('Answer') print('Agents--', agents) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_FetchSuggestionAuditAgent] @agents=%s, @response=%s', (agents, '')) return Response({ 'Agents':agents }) approach2: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method == 'POST': agents = request.data.get('Agents') sql = """\ DECLARE @response nvarchar(max), @agents nvarchar(max); EXEC [dbo].[sp_FetchSuggestionAuditAgent] @agents = ?, @response = @out OUTPUT; SELECT @response AS the_output; """ params = (agents, ) cursor = connection.cursor() cursor.execute(sql, params) rows = cursor.fetchall() while rows: print(rows) if cursor.nextset(): rows = cursor.fetchall() else: rows = None return Response(True) SQL: CREATE [dbo].[sp_FetchSuggestionAuditAgent] @agents nvarchar(max),@response nvarchar(1000) OUTPUT AS BEGIN set @agents = replace(@agents,' ', '%') select @response = FullName from ( select FullName from tblusers where IsActive=1 union all select FullName from tblusers where IsActive=0 and UserRole='Snowuser' )as a where FullName like @agents--('%'+@agents+'%') order by FullName desc END -
use of mixins class defined in Django rest framework
What is the actual use of Mixins class? I don't really get it. All the mixins classes like CreateModelmixin, Listmixin, etc features are already available in class-based view like ListCreateApiView. For eg: class ExampleView(ListCreateAPIView DestroyAPIView, RetrieveUpdateAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer pagination_class = CustomPageNumberPagination Using mixins we can do it by following: class ExampleView(ListAPIView, mixins.CreateModelMixin): queryset = Example.objects.all() serializer_class = ExampleSerializer pagination_class = CustomPageNumberPagination When I check https://www.cdrf.co/ I see the methods that are available in CreateModelMixing are the following: def create(self, request, *args, **kwargs): def get_success_headers(self, data): def perform_create(self, serializer): These methods are already available in ListCreateApiView, then why Django went to create this useless class?? -
Downloaded file is stored in 2 directories
problem occurs with the code below def creation_download(request, campaign_id, downloaded_file): bucket_file = downloaded_file gcs = GCPStorage() gcs.download_file(GCP_STORAGE_BUCKET_NAME, bucket_file) response = HttpResponse(bucket_file, content_type='application') response['Content-Disposition'] = 'attachment' return response I just want my file to be downloaded only to user/download directory, but it also being downloaded to my repository directory (where manage.py is stored and where is base_dir pointed). How do i manage only to store it in download directory? -
How can open and read GML file with OGR
I'm trying to open a gml file to read it but i can't access to content. models.py: class Plot(ChangesMixin, TimeEntity): gml = models.FileField(verbose_name=_('GML'), upload_to='gml/plot/', blank=True, null=True) parser_gml.py: from osgeo import ogr ... self.element.gml.file.open() file_content = self.element.gml.file.read() reader = ogr.Open(file_content, False) for layer_i in range(reader.GetLayerCount()): ... Anybody could help me please ? Thanks in advance. -
Django form not showing up in template using {{ form }} tag
I have made a basic todo app for my practice in which i want to create a profile page for every user. I have made a profile model, and connect it to a User signal, profile has been created but when I render it in a template, its not showing the profile form. the form for the profile model is form.py: class ProfileForm(ModelForm): class Meta: model = Profile fields = '__all__' exclude = ['user'] model.py --profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True, blank=False) email = models.EmailField(max_length=200, null=True) phone = models.CharField(max_length=40, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='pfp.png', upload_to='images') date_created = models.DateField(auto_now_add=True) def __str__(self): return self.user.username the view to render the profile(note: I am not creating a edit profile form, which i'll do later, that is why i used get in method): def user_profile(request): profile = request.user.profile form = ProfileForm(instance=profile) context = {'form': form} return render(request, 'task/profile.html') profile page template: {% extends 'main.html' %} {% load crispy_forms_tags %} {% block content %} <h3>Profile Page</h3> <style> .profile-pic{ max-width: 200px; max-height: 200px; margin: 0 auto; border-radius: 50%; } body{ background-color: rgba(211, 211, 211, 0.527); } </style> <br> <div class="row"> <div class="col-md-3"> <div class="card card-body"> <a class="btn … -
How to change the default Django Admin Site
I have added a new admin site to my Django Project and I only want some staff members to have access to it: class OtherAdminSite(DjangoAdminSite): site_header = "Some Other Header" site_title = "Some Other Title" index_title = "Some Other Title" def has_permission(self, request): user_in_other_admin_group = request.user.groups.filter( name="OtherAdminGroup" ).exists() return super().has_permission(request) and user_in_core_admin_group I can associate specific ModelAdmins w/ that site as follows: @admin.register(MyModel, site=other_admin_site) class MyModelAdmin(admin.ModelAdmin): pass That works fine. However, I don't want the members of "OtherAdminGroup" to be able to access the default admin site. I do not have the ability to update all of the admins in my project, b/c many of them come from 3rd party libraries. Is there a way to retroactively change the permission of all the default admins? -
Access a serializer via a variable in drf
In the create method in my serializer I'm trying to send a portion of validated data to another serializer as below: new_serializer = NewSerializer(validated_data.get('customer')) new_serializer.save() But in the place of NewSerializer I want to be able to use a variable.This will allow me to choose serializers dynamically. Something like this: the_serializer = "NewSerializer" new_serializer = the_serializer(validated_data.get('customer')) Is there a way to achieve this? -
Using custom manager in M2M serializer in Django Rest Framework
I have three models. I've simplified the case for easier understanding: class Physician(model.Models): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) class Hospital(model.Models): name = models.CharField(max_length=512) physicians = models.ManyToManyField(Physician, through=Membership, related_name='hospitals') class MembershipManager(models.Manager): def get_queryset(self): is_verified = # A very complex annotate case. return super(MembershipManager, self).get_queryset().annotate(is_verified=is_verified) class Membership(model.Models): hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE) physician = models.ForeignKey(Physician, on_delete=models.CASCADE) object = MembershipManager() I use Django Rest Framework to create a read-only API. In this case, a Pyhisician can have many Memberships in different Hospitals. I want to add the is_verified attribute to the Hospital serializer. Of course I could create a function is_verified_for_physician(self, physician) inside the Hospital class, but this field is expensive to calculate (that's why I made the annotate in the manager). The question is, how can I achieve this using Serializers? The natural thing for me, it would be to ask for physician.hospitals.all() and somehow pass the is_verified field from the Membership model to the Hospital. Is this possible?