Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any need of closing a database connection in django?
Is there any need of clossing a database connection in django . Or will the django automatically do it for us -
Ignore django_migrations table after migrate in postgresql
In django, the database engine default is sqlite. I change the engine from sqlite to postgresql. when I run python manage.py makemigrations and python manage.py migrate, I get my table a_atable in postgresql database successfully. But in my case, I find the django_migrations table in my database but I didn't create it in my models.py. The django_migrations save the migration log information. How do ignore the django_migrations table when I run python manage.py migrate? I want the a_atable in the postgresql only when I migrate. -
Add and Submit Product Django Model
Hello. I'm new to Django and want to do a project. I have some models that need to be fix. It's Online Shop and I have already done them but I'm not sure how many of them are correct. 1- Order.total price. I'm not sure about it. 2-The rest parts, need to be done with staticmode. A: def initiate(customer) This function check if the customer has an order before or not, if he has, we must return his order and if he doesn't have, we should create a new order for him. B: def add_product here, we should add a specific product and amount to OrderRow list. I need to check if the product has the enough amount and others stuff. if the product has been in'OrderRow',need to be update, if not need to be add. C: def submit check if status == BUYING and total_price <= Customer.balance and It should be checked that there are enough of all the goods ordered by the customer in the store: status need to change to submit and decrease the total price of the order from the customer's inventory The number of inventories of goods must be updated, If they are reduced or … -
Static files causing docker-compose to not work
I wrote a Dockerfile to run an application I'm writing for a non-profit organisation, which I hope to publish very soon (probably on DigitalOcean). I had issues with the Dockerfile due to random files like 'chunk' in the static folder, I resolved this with a fresh clone of my repository as the chunk files disappeared, see here. So it works perfectly fine when I just run using the image alone using docker run --rm -d mellon:latest. Here is the Dockerfile: FROM (MY FRIENDS ACCOUNT)/django-npm:latest RUN mkdir usr/src/mprova WORKDIR /usr/src/mprova COPY frontend ./frontend COPY backend ./backend WORKDIR /usr/src/mprova/frontend RUN npm install RUN npm run build WORKDIR /usr/src/mprova/backend ENV DJANGO_PRODUCTION=True RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python3 manage.py collectstatic && \ python3 manage.py makemigrations && \ python3 manage.py migrate && \ gunicorn mellon.wsgi --bind 0.0.0.0:8000 Now (as per advised by people online) I am trying to separate the app from the database so I have written a docker-compose.yml file. version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=(adminname) - POSTGRES_PASSWORD=(adminpassword) - CLOUDINARY_URL=(cloudinarykey) web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - ./backend:/usr/src/mprova/backend ports: - "8000:8000" depends_on: - db (Also annoyingly - I have to go into bash … -
Access to XMLHttpRequest at 'url' from 'origin' has been blocked by CORS policy
The complete error is Access to XMLHttpRequest at 'url' from 'origin' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. I am trying to develop a simple login application with Django backend and React frontend where a new user can register and will get added to my MySQL database. I am unable to send a POST request because of the above error. My settings.py has this cors policy: CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True ''' CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True` ''' CORS_ORIGIN_REGEX_WHITELIST = [ 'http://localhost:3000', ] My React code to send a post request looks like this: handleClick(event){ var apiBaseUrl = "http://localhost:8000"; console.log("values",this.state.name,this.state.email,this.state.secretword); //To be done:check for empty values before hitting submit var self = this; var payload={ "last_name":this.state.name, "email":this.state.email, "secretword":this.state.secretword } axios.post(apiBaseUrl+'/signup', {method:'post'}, payload) .then(function (response) { console.log(response); if(response.data.code === 200){ // console.log("registration successfull"); var loginscreen=[]; loginscreen.push(<Login parentContext={this}/>); var loginmessage = "Not Registered yet. Go to registration"; self.props.parentContext.setState({loginscreen:loginscreen, loginmessage:loginmessage, buttonLabel:"Register", isLogin:true } ); } I am unable to understand why this is being caused, or how I can resolve this. Any help … -
Why my code is only increamenting this value 1 time in javascript
HTML code : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Counter app</title> </head> <body> <p id="counter" value="0">0</p> <br> <button id = "increase" onclick="increase1()">increase</button><br><br> <button id = "decrease">decrease</button> </body> <script src="app.js"></script> </html> /*this is the code of JS please guide me*/`enter code here` JS code : function increase1() { var a = document.getElementById('increase').value; ++a document.getElementById('counter').innerHTML = a } this is the code I have pre incremented please check and please check what should I change in this code man please -
Djongo arrayfileld 'Item' is not subscriptable
I have 2 models in my django project. DB is mongoDB and I use Djongo. Here are the models: class Item(models.Model): item_id = models.IntegerField(primary_key=True) item_name = models.CharField(max_length=30) def __str__(self): return f'<{self.item_name}>' class Items(models.Model): items_id = models.IntegerField(primary_key=True) inventory = models.ArrayField(model_container=Item,) neutral_item = models.EmbeddedField(model_container=Item,) buffs = models.ArrayField(model_container=Item,) def __str__(self): return f'<{self.inventory}, {self.neutral_item}>' When I do: item = Item(item_name='Helmet') items = Items(inventory=[item]) I am getting this TypeError: 'Item' object is not subscriptable What is wrong? -
(Auto_now_add = True) result different between 2 fields
I have two models also including the datetimeField but the format and result is different. Did I miss somethings? models.py: class Order(models.Model): start_date = models.DateTimeField(auto_now_add=True) class Payment(models.Model): timestamp = models.DateTimeField(auto_now_add=True) setting.py: LANGUAGE_CODE = 'zh-TW' TIME_ZONE = 'Asia/Taipei' USE_I18N = True USE_L10N = True USE_TZ = True When I check the value in django admin: For Order: Aug. 1, 2020, 9:49 p.m. For Payment: 2020-08-01 13:50:01.368611+00:00 -
Video Seeking not working in Django WebPage?
I have a page where I play videos using the /media directory. I am using Django WebFramework for this. The problem is that using default controls of Chrome video player, the seek is not working in using Django Server, but the same video's Seek bar works when I try to run in normally. For Example - <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <video src="A.mp4" controls autoplay></video> </body> </html> While using normal notepad++ when I run this code the seekbar works,forward backwards everything. But when I render the same page using Django on localhost, the video plays but the when I click on the seekbar on some particular time, it does not jump to that point Instead it keeps playing where it was. Also..The seekbar works normaly for some videos using Django but not for all... Any idea to fix the seek bar while using Django. -
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I am getting this error for the third time.The first two times it was a missing comma and spelling mistake but this time I have checked everything and couldnt find what was the error. This is the code in my html in script tags document.getElementById('payment-info').addEventListener('click',function(e){ submitFormData() }) function submitFormData(){ console.log('Payment Button Clicked') var userFormData={ 'name':null, 'email':null, 'total':total, } var shippingInfo={ 'address':null, 'city':null, 'state':null, 'zipcode':null, } shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value var url="/process_order/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData,'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:',data); alert('Transaction Completed') window.location.href="{% url 'index' %}" }) } And this is my views.py def processOrder(request): transaction_id=datetime.datetime.now().timestamp() data = json.loads(request.body) customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer,complete=False) total=float(data['form']['total']) order.transaction_id=transaction_id if total == float(order.get_cart_total): order.complete = True order.save() ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) I have the respective fields in my models. I am not able to find the error. This is the complete error that I am getting: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Any help would be appriciated. -
Infinite ask self-retry with countdown if conditions are not met
I need to run the task and do some actions, retry it if some conditions are not met. The task should be retried infinitely and retries stops only if conditions are met. class MyCustomException(Exception): pass class MyCustomTask(Task): def run(self, *args, **kwargs): try: if not is_in_condition(): raise MyCustomException except MyCustomCondition: do_actions() # execution time about 3 secs. MyCustomTask.apply_async(countdown=60) In this case I have an immediate next execution of the task without countdown. I've tried this, too: # the same code except MyCustomCondition as exc: do_actions() raise self.retry(exc=exc, countdown=60, max_retries=-1) In this case I have only one do_actions execution and then it falls with MyCustomException Also I've tried eta parameter as here, the same result. Eager setting is fine. -
The current path,didn't match any of these
I have this in urls.py urlpatterns = [ path("product/<str:title>/<slug:pname>/<uuid:puid>",views.viewProduct), ] But when I try to click on the url. I got this error. The current path, product/amazon/home-secure-snake-shield-natural-snake-r/B0882NKXW7, didn't match any of these. Here I just want the puid but to match the pattern of URL I added str:title and str:pname I don't want the title and pname. But my URL patern is like this- product/store_name/product_name_slug/product_id -
Comment model only for user django (1048, “Column 'user_id' cannot be null” or no user filled)
I hope you are well. I'm trying to create comment for user with one form field (content). I'd like to have the user field automatically filled in user value. I. I started with this model but I got an error (1048, “Column 'user_id' cannot be null”): models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name="comments") user = models.ForeignKey(User,on_delete=models.CASCADE) content = models.TextField(max_length=160) publishing_date = models.DateField(auto_now_add=True) def __str__(self): return self.post.title views.py class PostDetail(generic.DetailView,FormMixin): model = Post context_object_name = 'post' template_name = 'post_detail.html' form_class = CreateCommentForm def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.post = self.object form.save() return super(PostDetail, self).form_valid(form) else: return super(PostDetail, self).form_invalid(form) def post(self,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_valid(form) def get_success_url(self): return reverse('post_detail',kwargs={"slug":self.object.slug}) forms.py class CreateCommentForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreateCommentForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("content",css_class="form-control",style="margin-bottom:10px",rows="1"), ) self.helper.add_input(Submit('submit','Comment',css_class="btn btn-sm",style="background-color: #0d6ec5;border-color: #0d6ec5;")) class Meta: model = Comment fields = [ 'content' ] II. It worked from my admin panel but not from my website (I got this error: (1048, “Column 'user_id' cannot be null”)). So I've decided to change my models with: class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name="comments") user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) content = … -
What are good comments when writing testing Django
I am working with Django, and I am new to it. I do not know lots of staff, especially when it comes to testing my views.py, models.py etc. I have written some tests in other coding languages, but Django just seems (at least to me) to have different kinds of test. I have only been experimented with other kind of tests (like arithmetic operations, file-parsing...). Those in Django, are mostly related with Web (HttpResponses & Requests, Templates etc.) and I am not sure at all, what comments should I write, and how to write them. Thank you in advance. I have searched on internet, but I've found only, general good practices for commenting on tests. I want specifically for Django test. -
Json to django models. Python data-type error
I have got when I want convert json data in django models. How can I solve it. class Persons(models.Model): rank = models.IntegerField() employer = models.CharField(max_length=100) employeesCount = models.IntegerField() medianSalary = models.IntegerField() object creater: for json in json_string: Persons.objects.create(id=json['rank'], employer=json['employer'], employeesCount=json['employeesCount'], medianSalary=json['medianSalary']) json reader f = open('data.json') json_string = f.read() f.close() json file: [ { "rank": 1, "employer": "Walmart", "employeesCount": 2300000, "medianSalary": 19177 }, { "rank": 2, "employer": "Amazon", "employeesCount": 566000, "medianSalary": 38466 } ] -
Cannot connect network server
I got a Django project and I m trying to connect to my linode online server . I type cd \\\folder location.... in cmd console then python manage.py runserver 0.0.0.0:8070 got the result python: can't open file 'manage.py': [Errno 2] No such file or directory Is anything missing here? -
Correct way to override django admin's add_view()
I need to override the view add_view() in django admin that gets called whenever I try to add a new model instance. What I've tried: class BaseMarketModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.creator = request.user return super().save_model(request, obj, form, change) def add_view(self, request, form_url='', extra_context=None): try: super(BaseMarketModelAdmin, self).add_view( request, form_url, extra_context ) except ValidationError as e: return handle_exception(self, request, e) def change_view(self, request, object_id, form_url='', extra_context=None): try: return super(BaseMarketModelAdmin, self).change_view( request, object_id, form_url, extra_context ) except ValidationError as e: return handle_exception(self, request, e) The change_view() works without any problems, but when I try to add a new model instance using "Add ModelName" button in django admin I always get this exception: AttributeError at /admin/market/exchange/add/ 'NoneType' object has no attribute 'has_header' Request Method: GET Request URL: http://127.0.0.1:8000/admin/market/exchange/add/ Django Version: 3.0.3 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'has_header' Exception Location: /usr/local/lib/python3.7/site-packages/django/utils/cache.py in patch_response_headers, line 243 Python Executable: /usr/local/bin/python Python Version: 3.7.7 I tried checking the source code of django's add_view() which is placed in: django/contrib/admin/options.py and it seems that it only calls change_view() with no object_id. Then I tried this: def add_view(self, request, form_url='', extra_context=None): return self.changeform_view(request, None, form_url, extra_context) And it loads the new instance page … -
django rest framework not showing response data
i have a problem with django rest framework and mySql the response data not showing: i define serializer: from rest_framework import serializers from ..models import H010002 class H010002Serializer(serializers.Serializer): class Meta: model = H010002 # Note: any fild passed her will send to xhr request fields = [ 'id', 'module_name', 'module_description', 'module_type', ] 2- view.py from .serializers import H010002Serializer from ..models import H010002 from rest_framework.generics import ( ListAPIView, RetrieveAPIView, ) # Create your views here. class H010002ListAPIView(ListAPIView): queryset = H010002.objects.all() serializer_class = H010002Serializer 3- data base included 1 record 4- django rest framework disply empty data with status 200 OK Note: if i use normal class ListView the data come correctly -
Image broken HTML even with correct path
So in my navigation bar I have tried to add an icon. However, even with the correct path given (shown with fuji.png) the image gives a 404 (NOT FOUND). The error message in inspect element is: GET http://127.0.0.1:8000/icons/fuji.png 404 (Not Found) Does this mean that instead of a relative path it looks for a URL path? navbar.html <div class="topnav"> <nav> <div class="logo-image"> <img src="/icons/fuji.png" alt="Mt. Fuji"/> </div> {% with url_name=request.resolver_match.url_name %} <a class="{% if url_name == 'index' %}wob{% endif %}" href="{% url 'polls:index' %}">Homepage</a> <a class="{% if url_name == 'create' %}wob{% endif %}" href="{% url 'polls:create' %}">Create a Poll</a> {% endwith %} </nav> </div> *BY THE WAY:: I get the same response with /icons/fuji.pg and icons/fuji.png. This is my directory (not everything, only showing what is necessary): Does anyone have an idea of why this is happening and how to fix this? The image doesn't even load in -- it is just a broken image file. -
I am having issues with retrieving data from a model in Django using ajax to and display it in a Datatable table
What I am trying to do is I have a model which already has got about 5000 records. Retrieving it as a context from a view is very slow. So i thought lets use ajax which would do server side processing. So I tried building a view which would handle ajax requests, retrieve all data from the model and return a JsonResponse. Now which I run the server I get the following issue : DataTables warning: table id=hospital_table - Requested unknown parameter 'id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4 I have gone through the link but well I'm am not able to fathom what's wrong. I'm fairly new to django. This is my Django Model : class Hospital_Data(models.Model): hospital_name = models.TextField(max_length=100) hospital_id = models.CharField(max_length=50, unique=True) category = models.TextField(max_length=50, null=True) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zone = models.CharField(max_length=100) address = models.TextField(max_length=300) pincode = models.IntegerField(max_length=10) phone_number = models.CharField(null=True,max_length=100) def __str__(self): return self.hospital_id This is the view that the ajax communicates with : def view_hospital_data(request): hospitalObjs = Hospital_Data.objects.all()[:10] context = { "data": list(hospitalObjs.values()) } print(context) return JsonResponse(context) This is the context variable that is printed : {'data': [ {'id': 3054, 'hospital_name': 'NAVJEEVAN HOSPITAL', 'hospital_id': … -
Accessing IP camera feed
I'm using the Django framework for developing an API and want to access the feed from an IP camera over the network. I'm stuck at the point. Any help will be appreciated. -
Django integrity error NOT NULL constraint
i'm creating a blog site which requires a login to write a post.As of now, ive just created the create post and update post views, but when i try to submit a created post, this integrity error is raised. I dont know how to get through this. Help is appreciated :) the error(idk as this is my first question stack wont allow me to embed images) models views blog/urls create_post.html mysite/urls -
How do I get the number of active users on my django website?
I want to display the number of active visitors on my website, I tried using django-tracking, django-active-users but none of them worked because they are outdated. I am using django 3.0.8 and all of those modules aren't supported with django3. I also tried doing this with Google analytics but their real-time reporting API is in limited beta and not open to everyone. Is there any way I can get this to work using django active sessions or something? -
How to get ajax post data in views.py?
I try to submit a form using ajax, the issue is the request.POST is always empty, the server reply successfully to the request but no data are coming. jquery : $(document).ready(function() { $("#step1").click(function(e) { console.log($('#form-one').serialize()) var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); e.preventDefault(); $.ajax({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, data: $('#form-one').serialize(), type: 'POST', url: '/commande/test', success: function(response) { console.log("success !") } }); return false; }); }); views.py def test(request): nadjib = modelformset_factory(Commande_Designation, form=Commande_D_Form, extra=1, can_delete=True) formset = nadjib(queryset=Commande.objects.none()) if request.method == 'POST' and request.is_ajax: print('post test 1') print(request.POST)// empty !! ............. -
Django Error: zip argument #4 must support iteration
My Django Dynamic url link got a problem: once the page was opened, every link are fine, but after used the link inside the page and refresh the page, an error shows as:zip argument #4 must support iteration the #4 is the id list, which used for dynamic url to link an file name and file context. View.py def coop(request, *args, **kwargs): my_context = {"coop_list": zip(Get_coop_list.number,Get_coop_list.course_name,Get_coop_list.method,Get_coop_list.id) } return render(request,'home_coop.html',my_context) def coop_gradefile(request,id): Get_coop_list.id = id grade_file = Get_coop_list.f_list[id-1] file_path = './Grades/Co-op/' + grade_file open = xlrd.open_workbook(file_path) grade_file = open.sheet_by_index(0) rowNum = grade_file.nrows colNum = grade_file.ncols grade_array = [] for i in range(rowNum): rowlist = [] for j in range(colNum): rowlist.append(grade_file.cell_value(i, j)) grade_array.append(rowlist) context = { "grade_file": grade_array } return render(request,'Grades.html',context) models.py class Get_coop_list(models.Model): number = list() course_name = list() method = list() f_list = os.listdir('./Grades/Co-op') id = list() for i in f_list: if os.path.splitext(i)[1] == '.xlsx': name = str(i) for n in range(len(f_list)): id.append(n) file_path = './Grades/Co-op/' + name open = xlrd.open_workbook(file_path) grade_file = open.sheet_by_index(0) page.html {% for number,course_name,method,id in coop_list %} <tr> <td>{{id}} - {{number}}</td> <td>{{course_name}}</td> <td>{{method}}</td> <td><a href='/grades/coop/{{id}}'>{{ 'view' }}</a></td>