Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query the database in Django forms?
I have a model: class Registration(models.Model): student_name = models.CharField(max_length=50) season = models.OneToOneField(Season) subject = models.OneToOneField(Subject) address = models.TextField() class Meta: unique_together = (('student_name', 'selected_season', 'selected_subject'),) I want to create a form for this model where the user will be given the option to select the subject based on the season that they selected. I have models for them as well: class Subject(models.Model): subject_name = models.CharField(max_length=50) ... class Season(models.Model): season = models.CharField(max_length=2, primary_key=True) subject = models.ManyToManyField(Subject) ... I dont know how to query the Form. Should It be a ModelForm or a regular Form? How to query the database in the form? -
Chart js in Django not showing when sent variable from views.py
I will plot horizontal bar chart in html but it's not showing. I send 2 variable from views.py are {{top5StockCode}} (code of item) and {{top5TotalSales}} (sale amount). The values of {{top5StockCode}} that views.py sent is ['23166', '21108', '85123A', '48185', '22470'] and {{top5TotalSales}} is [2671740, 227322, 171770, 158120, 143808]. This is my code in html <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockCode}}, datasets: [{ label: 'Top 5 selling products ', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5TotalSales}} }] }, options: { legend: { display: false }, responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </script> -
Django: adding items to cart automatically by scanning its barcode
I am building a salle application for store. The idea is the same an online shopping. Rather than selecting the product, choose the order quantity, and then add to cart, I would like to add items to the cart by scanning the item barcode. Now, now by clicking on the product name, I am able to add items to my cart. How can I do it please. Here is the view of adding items to the cart def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') This is the template {% extends "shop/base.html" %} {% load static %} {% block title %} {{ product.name }} {% endblock %} {% block content %} <div class="product-detail"> <h1>{{ product.name }}</h1> <h2><a href="{{ product.category.get_absolute_url }}">{{product.category }}</a></h2> <p class="price">{{ product.price }} MKF</p> <form action="{% url "cart:cart_add" product.id %}" method="post"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="Ajouter au panier"> </form> {{ product.description|linebreaks }} </div> {% endblock %} Please assist me -
Issue on Extend the Django Custom Admin Site
I have create a custom admin site and added the custom button to specific model page by extend 'change_list.html'. The following is my issue. Missed the link of "WELCOME, ADMIN. VIEW SITE / CHANGE PASSWORD / LOG OUT" on top right of the header. How to extend the custom admin site? the current setting is extend default admin site. Default Admin Site Custom Admin Site New Page that Extend Admin Site mysite\urls.py from django.contrib import admin from django.urls import include, path from polls.admin import polls_admin_site urlpatterns = [ path('polls-admin/', polls_admin_site.urls, name='polls'), path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('polls-admin/polls/question/show', views.show, name='show'), ... ] polls\admin.py from django.contrib import admin from django.contrib.admin import AdminSite from .models import Question class PollsAdminSite(AdminSite): change_list_template = 'polls/templates/admin/polls/change_list.html' site_header = "Polls Admin" site_title = "Polls Admin Portal" index_title = "Welcome to Polls Portal" polls_admin_site = PollsAdminSite(name='polls_admin') class QuestionAdmin(admin.ModelAdmin): list_display = ('question_text', 'pub_date') list_display_links = ('question_text', 'pub_date') polls_admin_site.register(Question, QuestionAdmin) polls\views.py from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.template import loader from .models import Question, Choice ... def show(request): template = loader.get_template('polls/show.html') context = { 'text': 'Hello!', … -
Django:Problems related creating custom user
I'm trying to creating a custom user in django with AbstractUser class. code of models.py where i defined my custom_user. from django.db import models from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): country=models.CharField(max_length=20) i want only country as a extra field with users.That's why i defined only country filed. i have already mention my custom user model in settings.py. AUTH_USER_MODEL = 'new_user.MyUser' when i run migration command it run successfully but when i run migrate it giving me error.like this. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 90, in handle executor.loader.check_consistent_history(connection) File "C:\Users\Futuresoft\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\loader.py", line 299, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency new_user.0001_initial on database 'default'. i have no idea what is this.Can anyone help with this. NOTE: I'm trying create custom user after creating my SuperUser and i have already migrate all migrations that comes when we first create our … -
Filenotfounderror while getting video length in django
Cannot get media file while calculating the video length in django after upload In my .views file ''' video_object = Video.objects.create( name = video_name, chapter = chapter, subject = subject, vfile = video_file, video_schedule = video_schedule, streaming_end_time = stream_end_time, quiz_count = quiz_count ) video_object.save() video_path = video_object.vfile.url video_length = get_length(video_path) video_object.video_duration = video_length return redirect('/admin_dashboard/') ''' get_length function ''' def get_length(filename): result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return float(result.stdout) ''' This is the video_path I'm getting at the error page, I have also added the media directory in the url file ''' video_path = '/media/media/video_zFnfdLY.mp4' ''' -
Django:Send email after redirect
Is there a way to send an email just after 'return redirect'? views.py Option 1: Placing 'send_mail' before 'redirect' if request.method == 'POST': formset = TestFormSet(request.POST,request.FILES,instance=project) if formset.is_valid(): subject = 'Notifications' html_message = "Testing notifications" recipient = ["testingemail@gmail.com"] send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False) formset.save() return redirect("home") With Option 1, the email is sent successfully but on the front-end the page has to wait until the email is sent before the redirection takes place. Option 2: Placing 'send_mail' after redirect if request.method == 'POST': formset = TestFormSet(request.POST,request.FILES,instance=project) if formset.is_valid(): formset.save() return redirect("home") subject = 'Notifications' html_message = "Testing notifications" recipient = ["testingemail@gmail.com"] send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False) With Option 2, formset is saved but email is not sent. Is there a way to send the email after the redirection so that the user doesn't wait for the email processing before the page is redirected? Thanks. -
How to display values in numbers instead of precentages in Plotly Pie chart?
Is there a way to display the actual values instead of percentage on the plotly pie chart? Below is the sample code which is a part of views.py file. The graph variable is then passed to HTML file to display the interactive image generated from plotly. import plotly.express as px import pandas as pd def my_view(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) a=os.path.join(BASE_DIR, 'db.sqlite3') con = sqlite3.connect(a) cur = con.cursor() df = pd.read_sql_query("SELECT * from POL", con) esd = df.groupby('ProjectStatus', as_index=False).agg({"ProjectID": "count"}) fig = px.pie(esd, values=Tasks, names=my_labels, color_discrete_sequence=px.colors.sequential.Blugrn) graph = fig.to_html(full_html=False, default_height=350, default_width=500) context = {'graph': graph} response = render(request, 'Home.html', context) The above would generate the attached pie chart. The values mentioned on hover should be displayed inside pie chart or on tooltip. Pie chart generated from above code -
join a image in mi view in django
Actually the original image is save on my downloads but I need the image to be stored in the database, not in my downloads, with the "nombre" of my model "programas" My model: class programas(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField('Nombres',max_length=50, blank= True) horas = models.CharField('Horas',max_length=50, blank= True) creditos = models.CharField('Creditos',max_length=50, blank= True) imagen = models.ImageField(blank=True, null=True) My view: def registroPrograma(request): if request.method == 'POST': form = ProgramaForms(request.POST, request.FILES) if form.is_valid(): programas = form.save(commit=False) programas.creditos= request.user imagen = qrcode.make('Hola Iver!') img = Image.open(programas.imagen) img = img.resize((2500, 2500), Image.ANTIALIAS) img = img.convert('JPG') img.paste(imagen, (0, 0)) x = img.save("/Downloads/hola.jpg") programas.imagen = img.paste(imagen, (0, 0)) form.save() return redirect('principio') else: form = ProgramaForms() return render(request,'registrar_programa.html', {'form':form}) -
How can i import my data frame from pandas in my template , i work with django, in order to display some éléments to user
I started a projet in django and i have some question. I have in my computer 100 files tab extension, and each one contains between 20,000 and 50,000 rows and 53 columns. That is an very big quantity of data. I implemented a template which will display to the user the name of the different columns, and so the user will check the name of the columns he wants to keep. After having selected these columns, on the server side, I have to recover these columns in each of the 100 files. Next, consider that each file corresponds to a vector, and that the elements of the vector correspond to different columns. Thus, When the user has selected the columns he wanted, this vector will correspond to an entry in a machine learning algorithm (for the moment, the choice of the algorithm does not interest me). What is the best way (in terms of complexity) to use my data (the 100 files), read it, merge columns, and more ..., in my django project? What I have done so far: _I have recovered my files in the form of dataframe using the pandas library. In this form and thanks to this … -
I want to run a new project in django and I get this error :ModuleNotFoundError: No module named 'C:\\Python39\\Lib\\site-packages\\django\\conf'
I created a project in virtualenv on windows and then tried to run it and this error occurred: Traceback (most recent call last): File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Windows\System32\django\.venv\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Windows\System32\django\.venv\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Windows\System32\django\.venv\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'C:\\Python39\\Lib\\site-packages\\django\\conf' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Windows\System32\django\django_project\manage.py", line 21, in <module> main() File "C:\Windows\System32\django\django_project\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Windows\System32\django\.venv\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Windows\System32\django\.venv\lib\site-packages\django\db\utils.py", line 225, in close_all for alias in self: File "C:\Windows\System32\django\.venv\lib\site-packages\django\db\utils.py", line 219, in __iter__ return iter(self.databases) File "C:\Windows\System32\django\.venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
Is Django Make Indexes for ManyToMany field?
i ask if Django make database indexes for ManyToMany Field ... and if yes is it do this for the model i provide in through ? i just want to make sure that database will go fast when it have a lot of data -
how to paginate and sort multiple querysets in same page?
I am using two query sets in one page and I want to have different paginations for each one this is my class based view: class MainListView(ListView): queryset = Post.objects.all() template_name = 'main.html' context_object_name = 'posts' def get_context_data(self, **kwargs): context = super(MainListView, self).get_context_data(**kwargs) context['news'] = EventsPost.objects.all() context['posts'] = self.queryset return context I want the Post model to be paginated by 3 and EventsPost by 6 Thanks for your responses -
Ideal way to check authentication token django x react
Im very new to React.js so i apologize if im asking a bad question. Right now i have just finished doing the authentication , however there are some issues that im facing and would like to know the best way of authenticating a get request / post request. I am using redux to store the authentication states . Logging in Upon completion of the form , i will enter the onFinish method which will call the dispatcher for logging the user in . Once the task of loggin in is successful , i will recieve a token of which i will check for this token within my render method (Im not sure if this is also the best way of doing things? seems highly likely to break): class Demo extends React.Component { formRef = React.createRef(); onFinish = values => { this.props.onAuth(values.username, values.password) } onFinishFailed = errorInfo => { console.log('Failed:', errorInfo); }; render() { let errorMessage = null; if (this.props.error) { errorMessage = ( <p>{this.props.error.message}</p> ); } if (this.props.token) { #<------- where i do the redirection , i will check for a token first. return <Redirect to="/" />; } return ( <div> {errorMessage} { this.props.loading ? <Spin size="large" /> : <Form … -
How to fix not updating problem with static files in Django port 8000
So when you make changes to your CSS or JS static file and run the server, sometimes what happens is that the browser skips the static file you updated and loads the page using its cache memory, how to avoid this problem? -
i was trying to add comment form in my post_detail: comment form
i was trying to add comment form in my post_detail its showing error(django.db.utils.OperationalError: no such column: userpost_comments.posts_id )can anyone help me with that i'm using class views for my detailsview models.py class Comments(models.Model): posts = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') author= models.ForeignKey(User,on_delete=models.CASCADE) comment = models.TextField() commented = models.DateTimeField(default=timezone.now) def __str__(self): return '{}-{}'.format(self.Post.title, str(self.User.username)) forms.py class Commentform(forms.ModelForm): class Meta: model = Comments fields = ('comment',) views.py class PostDetailViews(DetailView): model = Post @login_required() def Commentviews(request, slug): post = get_object_or_404(Post, slug=slug) template_name ='userpost/post_detail.html' if request.method == 'POST': form = Commentform(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return render(request,'userpost/post_detail.com',slug=post.slug) else: form = Commentform template = 'userpost/post_detail.html' context = {'form':form} return render(request, template, context) post_details.html <div class="comment"> <form method="POST"> {% csrf_token %} <fieldset class="form-group" id="login1"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" id="loginbtn" type="submit">Comment</button> </div> </form> <h1>Comments {{ post.comments.count }}</h1> {% for comment in post.comments.all %} <p>{{ comment.author }}</p> <p>{{ comment.comment }}</p> {% empty %} <p> There is no comment</p> {% endfor %} </div> can anyone please help i tried to google its only showing function based views -
Djnago, is it possible to create status choice with a model?
I have my model.py: class Example(models.Model): STATUS_CHOICE = ( ('status1', 'status1'), ('status2', 'status2'), ) field= models.CharField(max_length=10, choices=STATUS_CHOICE) . But I want to know if it's possible to have the possibility to create my STATUS_CHOICE with a model, in this manner the client can create the status as you want. Thanks -
Jquery How to change text of certain class inside $(this) selector
My problem is quite obvious but I don't know why its solution is taking so much time. Look at my html: {% for d in data %} <div class="chat_list" data-id={{d.id}}> <div class="chat_people" > <div class="chat_ib" > <h5><span class="chat_date"> </span></h5> </div> </div> </div> {% endfor %} I want to append text on click of certain div.Things I tried out in jquery: $('.chat_list').on('click', function(event){ event.preventDefault(); $( '.chat_date', this).text('hhh') $(this).find('.chat_date' ).text('hhh') $(this).find( 'chat_people').find('chat_ib').find('.chat_date' ).text('hhh') }); Nothing worked out. When only do $( '.chat_date').text('hhh') text get appears on every div. Any good solution to this? -
How to increment attribute "for" in my dynamic form?
I am new to programming so I really really appreciate if any of you would be able to help me with my code. I managed to solve my problem before this by referring to this link : previous row is not computing/updating from appended rows using jquery But then I have to combine that code with this : function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); total++; $('#id_' + prefix + '-TOTAL_FORMS').val(total); $(selector).after(newElement); fullrowname = selector.substring(0,selector.length - 4) + 'not(:last)' var conditionRow = $(fullrowname); conditionRow.find('.btn.add-form-row') .removeClass('btn-success').addClass('btn-danger') .removeClass('add-form-row').addClass('remove-form-row') .html('<span class="fas fa-minus" aria-hidden="true"></span>'); return false; } $("input.quantity,input.price").on('change', function() { Total($(this).attr("for")); }); The id is increment perfectly everytime I click the add button but the for="0" attribute is not increment. Hence my calculation for the dynamic input is not working :( Can you guys show me the way of how to increment the "for" attribute in the code above ? -
How to use a specific QuerySet for retrieval of related fields in Django?
I have subclassed QuerySet to provide it with an additional method, that annotates the QuerySet of MyModel with a custom field (containing the last related Person, for the purposes of optimization): class MyModelQuerySet(models.QuerySet): def with_last_person(self): people = Person.objects.filter(user_id=OuterRef('id')) people = people.annotate(person=RowToJson(F('id'), output_field=JSONField())) return self.annotate(person=Subquery(people.values('person')[:1])) This works just fine (e.g. [model.person for model in MyModel.objects.with_last_person()]) However, I am now retrieving another model, which has a foreign key relationship to MyModel: other_model = OtherModel.objects.get(foo=bar) #... Understandably, the other_model.my_model field contains the unannotated instance of MyModel. Is there a way to use this specific QuerySet for the retrieval of related MyModels of OtherModel? Something like: OtherModel.objects.filter(foo=bar).select_related('my_model', use_queryset=MyModelQuerySet) I suppose I could just copy and paste the code from MyModelQuerySet.with_last_person into the OtherModel query, but that duplicates the code unnecessarily. Is there another solution I'm missing? -
Shifting of filter section from right sidebar to left side bar in change list page in Django admin
I'm working on Django.And in Django admin I want to change the direction of filter section in the change list from right sidebar to left side bar as shown in the pic : Is there any way so that the filter section can be shifted as I mention?? Thanks in advance!! -
django orm how to get the sum of the first element of an array field?
I have the following django model for postgres. Assume metric_vals are non-empty arrays. Is there a way of getting the sum of all first values of metric_vals? from django.db import models import uuid from django.contrib.postgres.fields import ArrayField class SampleModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) metric_vals = ArrayField(models.FloatField(null=False), null=False, default=list) I tried the following but resulted in error: from django.db.models import F from django.db.models import Sum SampleModel.objects.aggregate(Sum('metric_vals__0')) django.db.utils.ProgrammingError: function sum(double precision[]) does not exist -
Issue regarding download Qgis 3.12 on Windows
I have tried multiple attempts and having 51 Gb in my hard drive, already deleted all the files regarding Qgis. -
i want to get the predicted result while adding the protein in sequence
here is my pickle class code feature engineering perform in jupyter and i put my model in pickle file whCih i'm calling in django here is my pickle class code.. import pandas as pd import pickle #Feature Engineering class protein: def __init__(self): self.features = self._makeFeature() def _makeFeature(self): test_list = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'Y', 'Z'] test_comb2 = [] test_comb1 = [] test_comb3 = [] for i in test_list: test_comb1.append(i) for j in test_list: test_comb2.append(i + j) for k in test_list: test_comb3.append(i + j + k) test_comb = [] test_comb.extend(test_comb1) test_comb.extend(test_comb2) test_comb.extend(test_comb3) print(len(test_comb)) return test_comb def countInputSeq(self, proteinSeq): d = {} for k in self.features: if k not in d: d[k] = 0 if k in proteinSeq: d[k] += 1 print(d) df = pd.DataFrame(d, index=range(len(d))) #df = pd.DataFrame(d) df=df.iloc[:,:420] return df def predict(self, feature): file = open("C:\\Users\\DELL\\Desktop\\Protein project\\model.obj",'rb') model = pickle.load(file) return model.predict(feature) def getSavedModel(self): file = open("C:\\Users\\DELL\\Desktop\\Protein project\\model.obj",'rb') model = pickle.load(file) return model here is my view file method which i call in form method, when i add some protein in text file i got the same output but i want the predicted result def test(request): … -
How to know if a model was modified by another user
I am writing a Django application where users manipulate a Model. A typical session for users is this : they get the model ; they do some actions (vizualise the model's datas, change these datas..); then, they save the model if they modified something. But, if two users are manipulating the same instance of the model, and one save his modification after the second loaded it, I want to be able to "notify" the second that the model has changed, so he can reload it. I could perform a get to check if there was a modification in the database every time a view is called, but it doesn't seems optimal. I have looked at Django's signals too, but I don't know how to send a signal to users manipulating a specific instance of the model. Do you have any ideas on how I can do it ?