Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relative and Absolute Path in Python Django
I have succesfully, seperated my settings file to Development and Production settings. While trying to import from base (common to the two) I always get path error. When I try to do this in prod.py file from src.psm_website.settings.base import * and try to compile with the IDE, it works well ( I used a print statement to print from a variable from the base file) But when I try to deploy to Heroku, I get the error from src.psm_website.settings.base import * remote: ModuleNotFoundError: No module named 'src' remote: Then when I change the import statement to this from .base import * I get this error when trying to deploy in heroku raise KeyError(key) from None remote: KeyError: 'SECRET_KEY' Secret key is a variable in base file, meaning base was not imported and I get this error when I try to run from the IDE. from .base import * ImportError: attempted relative import with no known parent package I have init.py in all parent directory, making them pakages from what I have read. How can I solve this Python Version: 3.7.7 -
How to remove default delete confirmation message from django admin on overriding delete queryset method?
I want to override the default delete_queryset method in admin to prevent deleting last object. def delete_queryset(self, request, queryset): warehouses = self.model.objects.all() if warehouses.count() == 1: messages.error(request, "Can't delete last object") return False return super(WarehouseModelAdmin, self).delete_queryset(request, queryset) The deletiion is working fine but along with the error message, "Successfully deleted 1 Warehouse.", this message is also being displayed. How can I remove this success message? -
How can I shortcuts request session in Django Python?
Here's my views.py code: def checkout(request): request.session["quantity"] = int(request.POST["quantity"]) request.session["price"] = float(request.POST["price"]) quantity_from_form = request.session["quantity"] price_from_form = request.session["price"] total_charge = quantity_from_form * price_from_form context = { 'quantity_from_form': quantity_from_form, 'price_from_form': price_from_form, 'total_charge': total_charge } print("Charging credit card...") Order.objects.create(quantity_ordered=quantity_from_form, total_price=total_charge) return render(request, "store/checkout.html", context) I want to shortcuts naming request.session[" "] = request.POST[" "]. Is there any way i can shortcut this? -
Setting a Django ForeignKey to multiple models
I have a simple model called WebProfile that stores a webpage URL and its title. This model has a ForeignKey to a Student model, which allows me to store the student's bookmarks. I would like to reuse this model to also store bookmarks saved by teachers. What is the best way to have the owner ForeignKey point to either a Student or Teacher? Note: in my actual use case, the target model classes are conceptually very different and do not share any common fields other than the WebProfile links. class Student(models.Model): ... class Teacher(models.Model): ... class WebProfile(models.Model): title = models.CharField(max_length=50) link = models.URLField() owner = models.ForeignKey('Student', on_delete=models.CASCADE, related_name="bookmarks") -
NoReverseMatch with generic DeleteView
I cannot figure out why I'm getting NoReverseMatch when trying to use this view. I'd like to get generic views to work because it seems like alot less code to do the same task. views.py from django.views.generic import DetailView, ListView, UpdateView, CreateView, DeleteView from django.urls import reverse_lazy from .models import * class ProductDeleteView(DeleteView): model = Product success_url = reverse_lazy('homepage_view') models.py from django.db import models from django.urls import reverse from autoslug import AutoSlugField class Product(models.Model): name = models.CharField(max_length=50) slug = AutoSlugField(null=True, default=None, unique=True, populate_from='name') def get_delete_url(self): return reverse('product_delete_view', args=(self.slug,)) class Meta: verbose_name_plural = "Products" def __str__(self): return self.name urls.py from . import views from django.urls import path, include from django.views.generic import TemplateView app_name = "main" urlpatterns = [ path('product/delete/<slug:slug>/', views.ProductDeleteView.as_view(), name='product_delete_view'), ] template <p> <a class="btn btn-primary" href="{{product.get_delete_url}}">Delete Product</a> </p> -
Apply a condition to a uniqueconstraint to only run on create not update
With a UniqueConstraint on a model it is possible to add a condition. E.g.: class MyModel(models.Model): class Meta: UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user') ensures that each user only has one draft. Is it possible to use condition to apply the UniqueConstraint only on model create not on update? Do CheckConstraints have the same condition value? It is not in the docs. -
Django Documentation part 4 <Forms and generic views> return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) Not working
This is Working Working But when I use return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) .. Not Working Not Working It shows NoReverseMatch at /polls/3/vote/ Reverse for 'results' not found. 'results' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/polls/3/vote/ Django Version: 3.0.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'results' not found. 'results' is not a valid view function or pattern name. Exception Location: C:\Users\shaff\Anaconda3\envs\First_Django_App\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\shaff\Anaconda3\envs\First_Django_App\python.exe Python Version: 3.7.7 Python Path: ['G:\Django_Project\First_Django_App', 'C:\Users\shaff\Anaconda3\envs\First_Django_App\python37.zip', 'C:\Users\shaff\Anaconda3\envs\First_Django_App\DLLs', 'C:\Users\shaff\Anaconda3\envs\First_Django_App\lib', 'C:\Users\shaff\Anaconda3\envs\First_Django_App', 'C:\Users\shaff\Anaconda3\envs\First_Django_App\lib\site-packages'] Server time: Wed, 22 Apr 2020 07:54:46 +0000`` -
Build a one-page website that show results from InfluxDB query (Python? Node js? React?)
I have a InfluxDB database sat on an Ubuntu VM. I've written some basic Python code to run through some dates and pull out summary results from the influx database based on hard-coded (for now) calculations. What i'd like to do is to create a basic one page website (on a new VM) to go out on there on the web, where I can feed variables from pre-canned dropdown boxes (to create the calculations), fire off the script, then display the results on the page. Then ultimately show a graph, but i'd be happy with a table of results for starters. Apart from knowing a small amount of HTML from way back when, I no experience of creating websites. Wordpress doesn't count does it? :) I've seen Flask and Django mentioned from the Python side, but I can't see too much about an Influx client for those or whether they would be suitable? When I look at Node I see a fully fledged Influx API https://github.com/node-influx/node-influx So do I go down the React js route? Its all a bit daunting and unclear what is the best path to take. I'd be learning something from scratch whatever route I take. Any … -
How to change the response structure
I am facing one issue to change the following structure..... THis is the structure I am getting { "labels": [ "List A", "List B", "List C", "List D" ], "data": [ 19, 25, 30, 32 ], "colors": [ "#e15759", "#f28e2b", "#76b7b2", "#4e79a7" ], } But I want to change the following data in to the following method { "category": "List D", "value": 32, "colors": "#e15759" }, { "category": "List C", "value": 25 "colors": "#f28e2b" }, { "category": "List B", "value": 30, "colors": "#76b7b2" }, { "category": "List A", "value": 19, "colors" : "#4e79a7" } Here is my code class AbcListAPI(APIView): def get(self, request, format=None): a = data_fuction() return Response(a) In this code I am getting this response from a function data_fuction that is used in another part of my code.... So I am unable to edit that response from there ..... But in this function I need to format this code .... -
How do I get a url using "requests" in host adapter only? I keep getting HTTPSConnectionPool NewConnectionError
The error I keep getting when I try to run url The code I'm using -
Django Outer Join
I'm creating a small web application to track my orders, i have two models: Order(models.Model) " This model to record the new orders" class Order(models.Model): customer= models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product= models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=CATEGOTRIES) note = models.CharField(max_length=200, null=True) OrderHistory(models.Model) " This model to record the changes for each order in any field" version_num = models.AutoField(primary_key=True) Order = models.ForeignKey(Order, null=True, on_delete= models.SET_NULL) customer= models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product= models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True) note = models.CharField(max_length=200, null=True) View: def update_orders(request,pk): theOrder = Order.objects.get(id=pk) theHistory = createOrderHistory({ 'Order': theOrder.id, 'customer': theOrder.customer, 'product': theOrder.product, 'date_created': theOrder.date_created, 'status': theOrder.status, 'note': theOrder.note }) print('The History of the order ',theHistory) UpdateForm = createOrder(instance=theOrder) theid = pk if request.method == 'POST': UpdateForm = createOrder(request.POST,instance=theOrder) if theHistory.is_valid(): if UpdateForm.is_valid(): theHistory.save() UpdateForm.save() return redirect('home') else: UpdateForm = createOrder(instance=theOrder) context = {'UpdateForm':UpdateForm} return render(request,'accounts/updateOrder.html',context) In the View update_orders function am taking the current order and save it into OrderHistory and then i save the new changes into Order Model it's working fine but the OrderHistory Model is not including the new change. orderHistory to get the history of the order def orderHistory(request,pk): theHistoryOfTheOrder … -
Mocking django tests - why is this patched function still being called?
I'm trying to test a function in one of my models, and am trying to to mock out the filesytem using mock.patch. No matter what I try, it doesn't seem to intercept the method. Model to test: app/models.py from django.db import models from .utils.storageutils import get_file from .utils.datautils import derive_data Class DataThing(models.Model): #defined here def set_data_from_file(self): data = derive_data(get_file('filepath')) setattr(self, 'derived_data', data) self.save() app/utils/datautils.py import pandas as pd def derive_data(data_from_file): df = pd.DataFrame('...') #do stuff with dataframe return df app/tests/unit_tests/tests_models.py from django.test import TestCase import mock from app.models import DataThing class DataThingModelTest(TestCase): @classmethod def setUpTestData(cls): cls.datathing = DataThing @mock.patch('app.models.derive_data') def test_set_data_from_file(self, mocked_derive_data): mocked_derive_data.return_value=('pretend_dataframe') self.datathing.set_data_from_file() self.assertEquals(self.datathing.derived_data, 'pretend_dataframe') I would expect this to pass. However, I get an error, because datathing.set_data_from_file() is still ultimately calling utils.storageutils.get_file. I've tried patching in app.utils.datautils.derive_data but have the same issue. -
Call View Function and send FCM Without Refresh Page Using AJAX In Django
When i click on a href they go on Script code but form Script not call the views.py function! Link code:: <a class="likebutton" href="#"> <span id="unlock"> <i class="fas fa-lock"></i>&nbsp;Send Message </span> </a> Script code:: <script type="text/javascript"> $('.likebutton').click(function(){ $.ajax( { type:"GET", url: "sendnotification", success: function(){ alert('Done') } }) }); </script> urls.py:: url(r"^sendnotification",views.sendnotification,name='sendnotification'), views.py:: @csrf_exempt def sendnotification(request): if request.method == 'GET': push_service = FCMNotification(api_key="*********") registration_id = "****************" data_message = { "Nick" : "Mario", "body" : "great match!", "Room" : "PortugalVSDenmark"} result = push_service.single_device_data_message(registration_id=registration_id, data_message=data_message) return HttpResponse('success') -
Django Rest Frame in oTree
Does anyone have experience with the Django Rest Framework being applied into a oTree project. I want to serialize a query of saved chat messages saved from a chat application and send them as JSON to websocket so they can be shown in the frontend. When I serialize with the from django.core.serializers import serialize function and parse it in the frontend i don't get a desirable JSON object but just a JSON in a string. models.py class Message(models.Model): content = models.TextField() timestamp = django_models.DateTimeField(auto_now=True) player = models.ForeignKey('Player', on_delete=models.CASCADE, null=True) def last_15_messages(self): return Message.objects.order_by('-timestamp').all()[:15] consumers.py async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] messages_from_db = serialize('json', Message.last_15_messages(self)) messages_from_db_json = json.dumps({ 'messages_from_db': messages_from_db }) # Send message to room group await self.channel_layer.group_send( self.room_name, { 'type': 'chat_message', "message": { "chat_message": message, "db": messages_from_db_json } } ) play.html socket.onmessage = event => { let data = JSON.parse(event.data).message; let db = JSON.stringify(event.data).message.db; console.log(db); }; I have added two images one displaying the json of the query in the backend and the received string in the javascript console in the frontend. Backend Image Frontend Image -
I am not able to open admin page
Once i go into localhost:8000/admin the browser says: Firefox can’t establish a connection to the server at 127.0.0.1:8000. I am using PyCharm: This is the error that comes up in the terminal: Not Found: / [21/Apr/2020 15:18:20] "GET / HTTP/1.1" 404 2031 Following which the server cuts off my app/urls: from django.urls import path from . import views urlpatterns = [ path('', views.index), ] And my project/urls: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('KMIO_page/', include('KMIO_app1.urls')), ] -
Storing Access Token in httponly Cookie but user can still see it in Network tab of Chrome Dev Tools?
I am using django to create a python backend and am storing the user's access token and refresh token in httponly cookies so I can authenticate requests to my backend. 1) Is this the right way to do this? 2) I know that httponly prevents seeing the cookie using 'document.cookie', but you can still see the cookie by analyzing the network tab in Chrome Dev Tools. Is this fine because only the user can see it (not other people)? Or is this still bad? -
I want to apply flex to django template would you see this?
I have a question current code is this {% if object_list.exists %} {% for p in object_list %} <div class="d-flex flex-wrap"> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{p.title}}</h5> <p class="card-text">{{p.description}}</p> <a href="{% url 'challenge:lecinfo_list_for_challenge' p.title %}" class="btn btn-primary">go</a> </div> </div> </div> </div> {% endfor %} {% else %} <tr> <td colspan="6"> <h4>no subject!</h4> </td> </tr> {% endif %} and current result is this I want to change like this is this possible? Is it possible to use bootstap or flex? Thanks for the specific way I did a search, but I'm not sure what to do. https://codepen.io/trufa/pen/rmwLzJ -
Specific Time interval by user
While using a start_time and end_time in an HTML file for django application. I have used the time tag as follows: <div>Start Time <input type="time" min="" max="" id="" name="start_time"></div> <div>End Time <input type="time" min="" max="" id="" name="end_time"></div> But the constraint here is - the user will give the timings varying from 5:00 AM to 4:59 AM. So, can anyone suggest what values should we need to have as min and max for start_time and end_time in the tags. Any other workaround is also welcomed. -
Not able to apply migrations to Django application. Facing this issue from a long time
the error is something like this - raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ ) These are my database settings # Database Settings export DB_NAME='qbo' export DB_USER='' export DB_PASSWORD='' export DB_HOST='localhost' export DB_PORT='' And I also have given all privileges to the user - Can someone explain way this issue is actually happening? -
How To Create A Socail Media App With Python?
I Want To Create An Social Media App Purely With Python. I Just Listed Out What And All To Learn. So Please Check The List And Tell I Am Correct Or Wrong. To Create A Social Media App With Python I Must Know : Python Kivy Postgreql Sockets The Manin Question Is Below : Is There Anything Else I Need To Study Or These Things Are More Than Enough. By The Way In What Order I Am Supposed To Complete This. I Know Python. Next I Must Go With What ? Kivy Or Postgreql Or Sockets . Thank You In Advance -
How to stage forms in Django?
I have form data that I gather in the views. What the user inputs will determine what the next form will be like. Should I create another view? If so, how do I pass on variables from one view to another? And should the separate view render a different html page? Or is there a way to work in the same view that I gathered the data initially? The view looks like this: def admission(request): if request.method == 'POST': form = DeterminingForm(request.POST) if form.is_valid(): selected_season = form.cleaned_data['season'] selected_batch = form.cleaned_data['batch'] form = DeterminingForm() context = { 'form': form, } return render(request, 'admission.html', context) -
How to filter ManyToMany fields in django?
I have two classes: class A: name tags = manytomany(B) class B: name I need to get A-objects, which contain all elements of tag_list: tag_list = array of several B pk's A.objects.filter(tags__contains=tag_list) How can I write this ORM-queryset? -
Django, sum of values in form, then submit to database
Say for example I have this. Take the input fields, and add via the calculate button. I tried using django-mathfilters inside of my html file, but then I realized that the fields would always be empty beforehand, so nothing would ever be calculated. What is the right approach to this? Do I need to split Final_Result from my book table? Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) Final Result: (result of adding the fields above when user clicks the calculate button [calculate] [submit] submit button will finalize the results and sent the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() views.py for the form def final_price(request): if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('final_price') else: form = RequestForm() args = {'form': form} return render(request, 'final_price.html', args) Model for to allow me to edit the fields in my book module class RequestForm(forms.ModelForm): class Meta: model = book fields = ( 'book_price', 'delivery_charge', 'delivery_type', ) I tried adding them through the … -
TypeError: title() missing 1 required positional argument: 'request'
Traceback (most recent call last): File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\WILLIAMSWEBSITE\TJWEXOTICS\urls.py", line 21, in path('', include('TJW.urls')) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\danfi\AppData\Local\Programs\Python\Python38-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) … -
I want to serve static files with permissions logic in my django project
So I've been working on a django project. Its a marketplace platform (two kinds of users - buyer & seller) and when a seller uploads files for a buyer, only those two users should have access to the uploaded files. I'm trying to figure how static files can be served with these permissions. I'm not sure if this is relevant but I'm using nginx to serve the static files, so is there a way to add permissions logic in django to serve these static files?