Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save batton doesn't save review changes to the server
Learning Django and have some problem. I created a function to change user review, but when I click on the save button, nothing happens. "Submit" doesn't submit data to the database. views.py def my_reviews(request): reviews = ProductReview.objects.filter(user=request.user).order_by('-id') return render(request, 'user/reviews.html', {'reviews':reviews}) def save_review(request, pid): product = Product.objects.get(pk=pid) user = request.user review = ProductReview.objects.create( user=user, product=product, review_text=request.POST['review_text'], review_rating=request.POST['review_rating'], ) data = { 'user': user.username, 'review_text': request.POST['review_text'], 'review_rating': request.POST['review_rating'], } avg_reviews = ProductReview.objects.filter(product=product).aggregate(avg_rating=Avg('review_rating')) return JsonResponse({'bool': True, 'data': data, 'avg_reviews': avg_reviews}) def update_review(request, id): review = ProductReview.objects.get(pk=id) msg=None if request.method=='POST': form = ReviewAdd(request.POST,instance=review) if form.is_valid(): saveForm = form.save(commit=False) saveForm.user=request.user saveForm.save() msg = 'Отзыв изменен' return redirect('user/reviews') form=ReviewAdd(instance=review) return render(request, 'user/update-review.html', {'form':form, 'msg':msg}) review.html {% extends 'base.html' %} {% load static %} {% block content %} <main class="container my-4"> <h3 class="my-4 border-bottom pb-1">Reviews</h3> <div class="row"> <div class="col-md-3"> {% include 'user/user-sidebar.html' %} </div> <div class="col-md-9"> <div class="table-responsive"> <table class="table-bordered table"> <thead> <tr> <th>Title</th> <th>Image</th> <th>Price</th> <th>Review text</th> <th>Review rating</th> </tr> </thead> <tbody> {% for review in reviews %} <tr> <td><a href="/product/{{review.product.id}}">{{review.product.title}}</a></td> <td> <img width="100" src="/media/{{review.product.image}}" alt="{{review.product.title}}"> </td> <td>{{review.product.price}}</td> <td> <a href="{% url 'update-review' review.id %}" class="float-right"><i class="fa fa-edit"></i></a> {{review.review_text}} </td> <td>{{review.review_rating}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </main> {% endblock %} update-review.html … -
Geodjango: Annotate count points within polygons
I have two models: class State(models.Model): geom = models.MultiPolygonField() name = models.CharField() class Disease(models.Model): geom = models.PointField() date = models.DateField() How can I annotate the count of Disease points within the State model. -
How to check if two polygons have internal points in common, with geodjango and postgis
I am am using geodjango with postgis backend. Giving two polygons I want to check if they overlap. I mean, they have interior points in common. If we check A.function(B) In the following picture "Example 1" would be False, "Example 2", would be False (cause they only have edges in common) and "Example 3" Would be True, cause they have interior points in common. If both polygons are equal, the the function would return True as well. -
Django and AJAX: stop setTimeout after a value is updated
I want to use AJAX to "watch" a webpage while some data processing is ongoing in the background using celery AJAX file, worklist_download_ajax.js (function worker() { console.log('worker'); var ids = $('#Ids').val(); var timer = setTimeout(worker, 5000); data = { 'ids': ids } $.ajax({ url: "/update_worklist_download_status", type: 'get', data: data, dataType: "json", success: function(data) { var div = $('#download-status-info'); div.replaceWith(data.html_worklist_sample_container); // get done boolean value from data and if done, then all // data processing is done and want to stop setTimeout if (data.done === true) { console.log('done = true'); clearTimeout(timer); // doesn't seem to work timer = 0; }; console.log('replaced') }, // complete: function(data) { // // Schedule the next request when the current one's complete // setTimeout(worker, 5000); // } }); })(); django view ajax request, views.py def update_worklist_download_status(request, **kwargs): logger.info('update_worklist_download_status()') data = dict() if request.is_ajax(): logger.info('AJAX') ids = request.GET.get('ids', None) if ids: object_list = MyModel.objects.filter( id__in=ids.split('&')) # check is still need downloading downloading = object_list.filter(download_technical_report=False) logger.info(downloading) if downloading.count() >= 1: data['done'] = False else: data['done'] = True data['html_worklist_sample_container'] = render_to_string( 'results/worklist_templates/worklist_sample_container.html', {'object_list': object_list}) return JsonResponse(data) else: print('NO Ids') The view passes the done=True value correctly to AJAX function worker(), however I can't get it to stop "watching" the … -
connect Oracle 19c database schema/tablespace with Django application
The client provided the single oracle( version 19c ) database in which 2 custom schemas are created and each has a separate tablespace. I need to connect those schemas/tablespaces with 2 separate Django projects, One schema for each Django project. I am unable to connect those schemas/tablespaces with the Django projects. When I run migration all the tables are created under the USERS tablespace of the oracle database. I tried with few possible solutions that are available on the internet, such as, Add DEFAULT_TABLESPACE in the settings.py file of each Django project. add class Meta and configure db_tablespace in each class in the models.py file. kindly help me with this and provide any possible solution. Let me know If anyone requires more details. Thank you. -
Django application, logout link
Why link of logout doesn't work? Here is code of navbar: {% if user.is_authenticated %} <li {% if 'dashboard' in request.path %} class="nav-item active mr-3" {% else %} class="nav-item mr-3" {% endif %} > <a class="nav-link" href="{% url 'dashboard' %}"> Welcome {{ user.username }} (Dashboard)</a> </li> <li class="nav-item mr-3"> <a href="javascript:{document.getElementByid('logout').submit()}" class="nav-link"> <i class="fas fa-sign-out-alt"></i> Logout </a> <form action="{% url 'logout' %}" method="POST" id="logout"> {% csrf_token %} <input type="hidden"> </form> </li> {% else %} Here is view.py: def logout(request): if request.method == 'POST': auth.logout(request) messages.success(request, 'You are now logged out') return redirect('index') logout link will be directed to 'index' and logged out -
Gunicorn freezes intermittently
I have a Django project served via gunicorn. Unfortunately gunicorn freezes intermittently, sometimes after a few days of running, sometimes within hours of restarting. The weird thing is that I use the same configuration on 4 of my servers, all running different code, and they all experience the outage at the same time. The following are my config files: [Unit] Description=Gunicorn Socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target [Unit] Description=Gunicorn Daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/opt/app_repo Restart=always ExecStart=/opt/app_repo/venv/bin/gunicorn \ --access-logfile /opt/app_repo/gunicorn.access.log \ --error-logfile /opt/app_repo/gunicorn.error.log \ --timeout 1000 \ --workers 9 \ --bind unix:/run/gunicorn.sock \ --log-level DEBUG \ --capture-output \ app_repo.wsgi:application [Install] WantedBy=multi-user.target ... I was able to confirm the Gunicorn freezing by running the following commands: $ systemctl status caddy # -> up and running, curl-ing to the website's URL without a slash will return a Caddy redirect to its slashed version $ systemctl status gunicorn # -> up and running as well $ curl --unix-socket /run/gunicorn.sock http:// # this hangs between 2-45 minutes, in which at this point the server is responsive again Versions: gunicorn==19.9.0 Django==2.2.3 ... note that I also tried updating to the latest gunicorn version, but I had the same issue so I reverted back. Things that … -
my django server runs twice for the same process
when I runserver or reload the server it runs twice for the same process?enter image description here I tried os.getpid() and I know that I'm running two process but why the single process run twice enter image description here -
Nested Filters in 3 models in Django ORM
I have 3 models Purchase, Order, Sub as follows class Purchase(PostgresModel): order = models.ForeignKey(Order, on_delete=models.CASCADE) class Order(PostgresModel): name = models.CharField(max_length=200) total_price = models.FloatField() class Sub(PostgresModel): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='sub_orders') price = models.PositiveIntegerField() each Purchase is related to one Order, each Order has multiple subs i need to fetch purchases that his Order__sub__price is greater than X my query is:- Purchase.objects.filter(order__sub_orders__price_gt=X) but it's not returning valid objects -
Why an empty test make another test bug in Django because of his name?
This is the weirdest thing I saw in my programer life (not very long but still). I am trying to test a Django app with pytest and I realised that one of my test is ok when run alone, but fail when I run the whole file. So I decided to test some things. First of all, I use a Postgre database, but when I switch to sqlite3, the test of the whole file work. But i wan't to use Postgre because I consider using research only available on Postgre so that doesn't fix the problem. Next I tried to remove some tests to understand wich test is interfering. I found that this is the case for a few of my tests. So I decide to erase everything there is in my file excepted the setup of tests, the test that work (I will call it main test from now on) alone and one of the tests interfering. Then, I delete line by line of the interfering test to understand where the problem is exactly. That where it become very weird. I deleted every line of the interferring test and put pass in it, so there is only : class … -
How to specify another value instead of id in the Model class
How can I take the room number itself instead of going to room_num? But so that at the same time the choice of the room remains as below How can I implement this? serializers.py class RegistrationSer(serializers.ModelSerializer): class Meta: model = Registrations fields = ('id', 'room_num', 'first_name', 'last_name', 'tel_num', 'img', 'visit_date', 'guest_count', 'room_relevant') [ { "id": 1, "room_num": 1, "first_name": "Tangribergenov", "last_name": "Zafarovich", "tel_num": 8930005378, "img": null, "visit_date": "2023-02-16", "guest_count": 1, "room_relevant": true } ] And I need [ { "id": 1, "room_num": 101, "first_name": "Tangribergenov", "last_name": "Zafarovich", "tel_num": 8930005378, "img": null, "visit_date": "2023-02-16", "guest_count": 1, "room_relevant": true } ] changed room_num 1 After 101 -
Python django todo list with comments
I have a todo list app created with django and I need to add a comment model. In the app, user can add response/comment to todo lists and items, admin can assign user to comment a list/item (to deal with the to do item), and user can update to do list status by adding comment. How could I accomplish this? models.py from django.db import models from django.utils import timezone from django.urls import reverse def one week hence(): return timezone.now() + timezone.timedelta(days=7) class ToDoList(models.Model): title = models. CharField (max_length=160, unique=True) def get _absolute url(self): return reverse("list", args=[self.id]) def str (self): return self.title class ToDoItem (models.Model) : title = models. CharField(max_length=180) description = models.TextField(null=True, blank=True) created_date = models.DateTimeField (auto_ now_add=True) due date = models.DateTimeField(default=one week hence) todo_list = models.ForeignKey(ToDoList, on delete=-models.CASCADE) def get_absolute url(self): return reverse("item-update", args-[str(self.issue _list.id), str(self.id)]) def _str_(self): return f"{self.title}: due [self.due date}" class Meta: ordering = ["due date"] class Comments(models.Model): comment= models.Foreignkey (ToDoList, on_delete=models.CASCADE) user = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] def _str_(self): return 'Comment {} by {}'.format(self.body,self.user) views.py from django.urls import reverse, reverse_lazy from django.views.generic import (ListView,CreateView,UpdateView,DeleteView,) from .models import ToDoItem, ToDoList class ListListView(ListView): model = ToDoList template_name = "todo_app/index.html" … -
Timezones problems related to Elastic Beanstalk, RDS - why files dissapearing when I change a timezone?
Just like in the title, what's the logic behind this kind of behaviour? In addition, I would like to know if setting a different time zone for a project deployed with Elastic Beanstalk and a different one for the database (using RDS) can lead - later - to aborted deployment of a new version of my uploaded project. If so, is it possible to somehow fix it without changing time zones? I.e. Can I somehow set my project with Elastic Beanstalk with one timezone, RDS with different, and still be able to deploy my project/site with Elastic Beanstalk? -
How to store some default values in Django models?
I am kind of beginner in using Django. Let's say I have this code: Models.py: list_of_authors = ["Lily","David"] class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=500) author = models.ManyToManyField(Author) I want to save the name of authors to the model "Author" automatically by running the server to be able select them with ManyToManyField under "Book". It is important that the data are saved just one time in database, otherwise I am going to save them every single time by running the server. P.s: I know I can define choices or use MultiSelectField instead of ManyToMaynField, but due to the complexity of the project I can not do it. This example was simplified. -
For loop with big json data start to create same objects of model
I have big json file with like 18k lines and after some iterations it startы to create same objects of model PresenceDetailInfo and return error MultipleObjectsReturned Im not sure how am i suppose to fix that or change my for loop I`ve tried small json with 1k lines and my function works great Problems with creating same objects of model happens only with big json file task.py for item in response.json(): info_list_json = json.dumps(item) info_parsed = PresenceInfoListSerializer.parse_raw(info_list_json) list_counter = info_parsed.ListOfCounterparty object_model = ObjectList.objects.get(GUID=info_parsed.ObjectGUID) for counter in list_counter: for info in counter.Information: try: info_model = PresenceListInfo.objects.get( object_presence=ObjectList.objects.get(GUID=info_parsed.ObjectGUID), counter_presence__GUID=info.CounterpartyGUID) create_info(info_model, info, counter, SectionList, PresenceDetailInfo, PresenceListInfo) continue except PresenceListInfo.DoesNotExist as e: print(e) counter_model = CounterParty.objects.get(GUID=info.CounterpartyGUID) info_model = PresenceListInfo.objects.create(object_presence=object_model, counter_presence=counter_model) create_info(info_model, info, counter, SectionList, PresenceDetailInfo, PresenceListInfo) create_info.py def create_info(info_model, info, counter, SectionList, PresenceDetailInfo, PresenceListInfo): section_list = [] info_list = [] for section in info.SectionsGUID: try: section_list.append(SectionList.objects.get(GUID=section)) continue except SectionList.DoesNotExist as error: print(error) for sect in info.SectionsGUID: try: info_list.append(PresenceDetailInfo.objects.get(presence_info__counter_presence=info_model.counter_presence, work_date=counter.Date, sections_info__GUID=sect)) continue except PresenceDetailInfo.DoesNotExist as error: print(error) single_presence_model = PresenceListInfo.objects.get(counter_presence__GUID=info.CounterpartyGUID) presence_model = PresenceDetailInfo.objects.create(presence_info=single_presence_model, work_date=counter.Date, amount_of_workers=info.Number) presence_model.sections_info.set(section_list) -
I have this error that has been difficult for mse to solve.Can someone explain the problem as they would explain it to a beginner [closed]
LoginView() received an invalid keyword 'templates_name'. as_view only accepts arguments that are already attributes of the class. I haven't tried anything really -
certain django template never tracked by google analytics
I want to track via simple google analytics funnel user registrations on a django site. To this end I have the def sign_up(request) view return redirect to this "bucket" page: <!-- register_success.html --> {% extends 'tracker/base.html' %} {% block title %}Sign Up{% endblock %} {% block content %} <h1>Successful registration!</h1> <p>You are about to be redirected ...</p> <script> setTimeout(function() { window.location.href = '/home'; }, 5000); </script> {% endblock %} The JS does what is says on the tin and redirects after 5 secs. Problem is, this page never shows up in the GA reports, even though, just like the rest, it extends the base template where the tracking code resides. I'm confused. -
Multi-word django model naming convention
I have a django model called ProfilePicture, i've renamed it from Profile_Picture to ProfilePicture so that it will fit python naming conventions. Right now, i am accessing it something like this request.user.profilepicture. I would like to know if it's possible to change it so that i can access it like this: request.user.profile_picture or if there is a better way of doing things because request.user.profilepicture looks weird i've seen the answer that is suggested here: Referencing multiword model object in Django however, i've tried request.user.profilepicture_set.all() and it just says that the attribute does not exist. Even if it does, it still feels a bit wrong. -
so my question is related to subprocess in django
def Summary(request): # Call the generate_question_and_choices function output = generate_question_and_choices(1, key_distractor_list, keyword_sentence_mapping) # Create a new text file and write the output to it file_path = os.path.join(os.getcwd(), 'questions.txt') with open(file_path, 'w') as f: f.write(output) # Open the file for reading and return it as an HTTP response with open(file_path, 'r') as f: file_data = f.read() response = HttpResponse(file_data, content_type='text/plain') response['Content-Disposition'] = 'inline; filename="questions.txt"' return response so this function i use it for taking the output from a mcq generate and i want to add the output to a new file question.txt and just to display it whenever is start the program for the first time this works well but i have a function def open_new(request): python_executable = sys.executable subprocess.call([python_executable, "CustomerHome/generate_MCQ.py"]) Summary(request) def restart(request): open_new(request) return render(request, 'Home.html') where using a button i reexecute my program so that i can get input for the corresponding input. in the above case the problem is that when i upload a text file and generates its output its clear that the mcq generator is producing the output by looking at the terminal the problem is that the Summary() function is not getting executed after the subprocess of the program so that the text file … -
Django: How can I change my code to access ForeignKey fields through 3 tables?
I tried to get values with using three tables. cart_c = Cart.objects.select_related('item').filter(user=2) context = {'cart_c': cart_c} I got QuerySet, 'cart_c', but I could not refer ItemPhoto.photo from 'cart_c'. So, I made three tables joined with prefetch_related(). items = Item.objects.prefetch_related('item_photo', 'cart_item').filter(cart__user=2) context = {'items': items} But, I do not have any good idea to access ItemPhoto.photo and Cart.quantity except this. items[0].cart_item.values()[0].get('quantity') # Or [i.quantity for item in items for i in item.cart_item.all()] I think this way is not proper and sophisticated to use in Django Template System. It's complicated I think. I found a relative question in StackOverFlow, and one of the answers is same like code I wrote. items[0].cart_item.all()[0] Could anyone teach me how I should change and write code to send QuerySet or dictionary to Django Template to access Item.name, Item.price, ItemPhoto.photo and Cart.quantity with using three tables, Item, ItemPhoto and Cart? Thanks. models.py(omitted) class Item(models.Model): # Product name = models.CharField("item_name", max_length=255, blank=False, default="") price = models.DecimalField("price", max_digits=12, decimal_places=2, default=0.00, blank=False, ) class ItemPhoto(models.Model): # Photo item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item_photo", verbose_name="item_id",) photo = models.ImageField("item_photo", blank=True, upload_to=get_itemimage_path) class Cart(models.Model): # Order user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="user", on_delete=models.CASCADE, null=False, related_name="cart_user",) item = models.ForeignKey(Item, verbose_name="item_id", on_delete=models.CASCADE, related_name="cart_item", null=False,) quantity = models.PositiveSmallIntegerField("quantity", default=0) … -
total number of hires (django)
models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True) full_name = models.CharField(max_length=50,blank=True, null=True) bio = models.TextField() is_hired = models.BooleanField(default=False) hires = models.ManyToManyField(User, related_name="profile_hires",blank=True, default=None) template: <div> <div class="title">Likes</div> <i class="fa fa-group"></i> <div class="value">{{profile.likes.count}}</div> </div> I want it so that it number of hires doesn't decrease, so if i hire someone and then later fire them it should show 1 hire instead of decreasing the count to 0 -
Django Jet Theme Installation + Bookmark collission with Admin_Tools
I keep getting this error when Installing Jet Theme in an environment which uses currently admin_tools. Any idea how to solve it? What do I need to add in Models? All I try with ForeignKeys and related_name ends up in another error. python manage.py makemigrations apfm SystemCheckError: System check identified some issues: ERRORS: apfm.Bookmark: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'added'. jet.Bookmark.user: (fields.E304) Reverse accessor 'User.bookmark_set' for 'jet.Bookmark.user' clashes with reverse accessor for 'menu.Bookmark.user'. HINT: Add or change a related_name argument to the definition for 'jet.Bookmark.user' or 'menu.Bookmark.user'. menu.Bookmark.user: (fields.E304) Reverse accessor 'User.bookmark_set' for 'menu.Bookmark.user' clashes with reverse accessor for 'jet.Bookmark.user'. HINT: Add or change a related_name argument to the definition for 'menu.Bookmark.user' or 'jet.Bookmark.user'. I have tried to give the 'jet.Bookmark.user' and 'menu.Bookmark.user' a related_name using ForeignKeys in models.py but I cannot make it work. -
How to get folium map to full screen width despite being in a bootstrap container?
I am playing around with Folium. The map is contained within a bootstrap container.(tab) As a result, the map is taking the size of the child div instead of the whole screen width. Is there a way to change the map to full screen width despite it being in a child div? (I did try to remove all the divs (except the tab one) but the result is the same) <div class ="container mt-2"> <ul class="nav nav-tabs"> <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#all">All</a></li> <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#other">Other</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="all"> <div class="row"> <div class="col"> {{map|safe}} <div class="col-auto"></div> </div> </div> </div> <div class="tab-content"> <div class="tab-pane" id="other"> <div class="row"> <div class="col"> {{map_access|safe}} <div class="col-auto"></div> </div> </div> </div> </div> </div> -
I am getting data which was fetched for earlier request instead of current request in DJango Restframework + Pandas
I am currently using SOLR as database and Django Restframework as my back-end. here is scenario request 1: fetched 100 records from SOLR and used pandas for manipulating data for response and sent response: Completed successfully no issue request 2: fetched 50 records from SOLR and used pandas for manipulating data for response and sent response but some how previous 100 record get added and now df is 150. Can some one help me in under standing why is this happening Surplus this is only happening on only one server and rest is working fine I tried to log data at each step and it was correct apart from one set of place in for loop. -
Uncaught TypeError: Failed to resolve module specifier "cytoscape". Relative references must start with either "/", "./", or "../"
This is my directory path I'm running cytoscape module on Django server.But terminal throws ERROR Uncaught TypeError: Failed to resolve module specifier "cytoscape". Relative references must start with either "/", "./", or "../". settings.py import os.path STATIC_URL = "/static/" STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ STATIC_DIR, ] print(STATIC_DIR) index.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="UTF-8"> <title>0!</title> </head> <body> <div id="cy"></div> <script type="module" src="{% static '/src/index.js' %}"></script> </body> </html> webpack.config.js const path = require("path"); const HtmlWebPackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: "./src/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname + "/build") }, devServer: { static: { directory: path.join(__dirname, 'public'), }, compress: true, port: 9000, }, mode: "none", module: { rules: [ { test: /\.(js|jsx)$/, exclude: "/node_modules", use: ['babel-loader'], }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true } } ] }, { test: /\.css$/, use: [MiniCssExtractPlugin.loader,'css-loader'] }, { test: /\.json$/, type: "javascript/auto", use:[ { loader: "file-loader", options: { name: "model/[name].[ext]" }, } ], include: [ path.resolve(__dirname, "./model") ] }, { test:/\.ico$/, use:[{loader:"file-loader?name=[name].[ext]",}], } ] }, plugins: [ new HtmlWebPackPlugin({ template: '../Map/templates/Map/index.html', filename: 'index.html' }), new MiniCssExtractPlugin({ filename: …