Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
Python DJANGO TESTS test case with mocks not behaving as expected
I have to test an API for 404, so here is my test case @patch('api.services.requests.get') def test_whitelisted_response_failure(self, mock_get): response_body = utils.test_file('get_data.json')["HTTP_ERROR"] mock_get_data = Mock() mock_get_data.status_code = status.HTTP_404_NOT_FOUND mock_get_data.json.return_value = response_body mock_get.return_value = mock_get_data response = self.client.get(self.url, content_type='application/json') And this is my API which I am supposed to test. def get(self, request, id): try: response = Service.get_detail(id) response.raise_for_status() # response.status_code = 404 here except HTTPError as e: print("INSIDE HTTP ERRORS") The code in API never raises an exception for non 200 status codes when I test it through my testcase but works just fine when tested through Postman(not mocked) Am I missing something here? -
override django oscar search app to return specific only merchant specific products?
I am using Django oscar(2.0.2), where I have made foreign key relation of merchant ids with product table so that I can fetch merchant-specific products from the database AbstractProduct with data, (https://prnt.sc/s1ssxx). By default oscar returns all the products in the search results, I want to only return the products specific to a merchant's site. I am using haystack simple search as suggested in oscar documentation, I have tried overriding the search app like all other apps, I have overridden the search_indexes.py file, but it seems that it never gets called from the FacetedSearchView. where will I have to override the query like that Product.objects.filter(user_id=1), to return only merchant-specific products while searching for a product? if my question is not clear, let me know in the comments so I can improve it. -
How to stop a timer from reseting using Django and AJAX?
I am trying to stop a timer from resetting when the user refreshes the page. I don’t want to use cookies or local storage, I want to store how much left in the database. I am using Django and Ajax. I don’t fully understand how to do that, I have tried to send how much left to the view using AJAX POST request but I keep getting that its None hence it does not get stored in the database. I don’t fully understand where to place the AJAX call in my JS and how to use a GET AJAX request. How can I get the value from the database and use it in my timer when the user refresh the page? template.html const TIME_LIMIT = 30; let timePassed = 0; let timeLeft = TIME_LIMIT; let timerInterval = null; startTimer() function startTimer() { timerInterval = setInterval(() => { timePassed = timePassed += 1; timeLeft = TIME_LIMIT - timePassed; seconds_left = timeLeft/100 document.getElementById("base-timer-label").innerHTML = formatTime( timeLeft); $.ajax({ type: "POST", url: server_url+ '/study/attention_view', data: {'seconds_left' : seconds_left}, success: function () { console.log('seconds_left:', seconds_left); } }); setCircleDasharray(); setRemainingPathColor(timeLeft); if (timeLeft === 0) { onTimesUp(); } }, 1000); } function formatTime(time) { let seconds = … -
django rest framework HyperlinkedIdentityField
i've try to hyperlinked serializer in django-rest-framework , django version:2.2 main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/trip/',include('app.api.urls')), ] app urls.py app_name='my_app_api' urlpatterns = [ path('posts/',MyView.as_view(),name='posts'), path('details/<int:id>/',MyView.as_view(),name='post_id'), ] my serializers.py post_deteail_url = HyperlinkedIdentityField( view_name = 'my_app_api:post_id', lookup_field='id' ) but still i get this error django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "my_app_api:post_id". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. i found some solution with the same problem not worked for me , and still keeping getting the error -
How do i insert one table and update another table in django
I have two tables, purchase with four fields (id,supplier,items,and quantity), and i have items table with four fields(id,items_name,quantity). When ever i insert data in purchase table, i want to update the quantity of that item in items table. For example if i purchase one item, the quantity will be updated in items table. -
Django i18n: Django translation file with optional arguments
Is it possible to mark an argument as optional within my .po files? msgid "searchpage_seo_title_%(location)s_%(price)s" msgstr "My special title %(location)s - without using the price argument" If I build my string like that I got this error while compiling my translation files. python3 manage.py compilemessages processing file django.po in /locale/en/LC_MESSAGES CommandError: Execution of msgfmt failed: /locale/en/LC_MESSAGES/django.po:1294: a format specification for argument 'price' doesn't exist in 'msgstr' msgfmt: found 1 fatal error -
how to give condition on displaying value in Django admin
Hi i have user model consist of several fields, in that payment_type is one field which return integer value , so based on that value i need to show some string sentence. class Users(models.Model): payment_type=models.IntegerField() in my admin i need to make condition to display. I am new to django so support