Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models,There's a column in the table, but it cannot be referenced from this part of the query,
I've defined some models in django and I can successfully add data to them using objects in django but the problem is that when I try to do this directly from the database it gives me this "HINT" There's a column named origin_id in the table flight, but it cannot be referenced from this part of the query, I'm using postgresql for the database, So can anyone please help me with this? I know there are similar questions like this but I couldn't find the solution. class AirportManager(models.Manager): @classmethod def ret(cls): return 'This is a custom "Manager"' @classmethod def code(cls): obj = Airport.objects.all() return obj class Airport(models.Model): code = models.CharField(max_length = 3) city = models.CharField(max_length = 20) objects = AirportManager() class Meta: db_table = 'airport' def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport,on_delete=models.CASCADE) destination = models.ForeignKey(Airport,on_delete=models.CASCADE,related_name = "arrivals") duration = models.IntegerField() flights = models.Manager() class Meta: db_table = 'flight' def __str__(self): return f'from "{self.origin}" to "{self.destination}" in "{self.duration}" hrs' -
Is there a create() method in the Manager class of Django?
So, I recently started learning Django and found out about the two ways to create obejcts in database using their given API. Now, one of the methods is to use the create() methods that is provided by Manager class as follows : joe = Author.objects.create(name="joe") Now, objects is the default manager given by Django but I could not find create() method inside the source code. Please tell me what am I missing? -
Autofield attribute giving NOT NULL constraint failed: CART.CARTID
I am not able to insert a record in cart table. cartid = models.AutoField(primary_key=True) # Field name made lowercase. productid = models.IntegerField(db_column='PRODUCTID') # Field name made lowercase. prodctname = models.TextField(db_column='PRODCTNAME') # Field name made lowercase. This field type is a guess. price = models.TextField(db_column='PRICE') # Field name made lowercase. This field type is a guess. quantity = models.IntegerField(db_column='QUANTITY') # Field name made lowercase. dateadded = models.DateTimeField(db_column='DATEADDED') # Field name made lowercase. customerid = models.IntegerField(db_column='CUSTOMERID') # Field name made lowercase. sellerid = models.IntegerField(db_column='SELLERID') # Field name made lowercase. class Meta: managed = False db_table = 'CART' When I insert a record with this statement: cart = Cart.objects.create(productid = productId, sellerid = sellerId,prodctname= prodName,price = price,quantity=1, dateadded= datetime.datetime.now(),customerid = request.user.id) class Cart(models.Model): -
Can u deploy django in Apache with out creating a virtual environment , i waant to run django globally
I am having multiple django projects and want to switch projects multiply times in hosted ip . So i want to install django globally instead of in the virtual environment and serve. Is it possible to server without virtual envionment in apache -
Recurring instances of "[Errno 111] Connection refused" in syslog - Django app with gunicorn app server, gevent workers and nginx reverse proxy
I have a Django v1.8.19 app being served on a virtual machine procured from Digital Ocean (32 GB Memory / 25 GB Disk + 85 GB / SGP1 - Ubuntu 16.04.6 (LTS) x64). I've installed a gunicorn v19.9.0 application server, alongwith an nginx v1.17.7 reverse proxy. The DB is Postgresql v9.6.16. Note that I've used gevent workers in gunicorn. This setup sees moderate daily traffic daily. I see a recurring error cropping up in my syslog almost hourly. I don't know what to make of it, and need expert guidance. Note: things got compounded this morning - when I found the app to have totally crashed. Syslog was repeatedly flooding with the aforementioned error at that time. Here's the traceback: [ERROR] Socket error processing request. Traceback (most recent call last): May 15 09:23:17 main-app gunicorn[10779]: File "/home/ubuntu/.virtualenvs/app/local/lib/python2.7/site-packages/gunicorn/workers/base_async.py", line 66, in handle May 15 09:23:17 main-app gunicorn[10779]: six.reraise(*sys.exc_info()) May 15 09:23:17 main-app gunicorn[10779]: File "/home/ubuntu/.virtualenvs/app/local/lib/python2.7/site-packages/gunicorn/workers/base_async.py", line 56, in handle May 15 09:23:17 main-app gunicorn[10779]: self.handle_request(listener_name, req, client, addr) May 15 09:23:17 main-app gunicorn[10779]: File "/home/ubuntu/.virtualenvs/app/local/lib/python2.7/site-packages/gunicorn/workers/ggevent.py", line 160, in handle_request May 15 09:23:17 main-app gunicorn[10779]: addr) May 15 09:23:17 main-app gunicorn[10779]: File "/home/ubuntu/.virtualenvs/app/local/lib/python2.7/site-packages/gunicorn/workers/base_async.py", line 129, in handle_request May 15 09:23:17 main-app gunicorn[10779]: … -
Django multiple queryset combine into a pagination and be able to loop through the querysets differently
I have two query sets I have combined as one using chain method then used it on a template using pagination... I would like to loop through the results accessing the two query sets on there own on the category template. I want them to appear this way posts appearing side by side below is my view.py def post_category2(request, category=None): object_list = Post.published.all() results = object_list.filter(category=category) count = len(results) + 1 limit = math.ceil(count/2) left_posts = results[:limit] right_posts = results[limit: count] post = list(chain(left_posts, right_posts)) # paginator = Paginator(post, 5) paginator = Paginator(post, 6) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/category2.html', {'posts' : posts, 'category' : category, 'page' : page, }) my pagination file is here <div class="col-sm-12"> <ul class="pagination"> {% if page.has_previous %} <li> <a href="?page={{ page.previous_page_number }}" class="prev"> <i class="pe-7s-angle-left"></i> </a> </li> {% endif %} <li><a href="#" class="active">{{ page.number }}</a></li> {% if page.has_next %} <li> <a href="?page={{ page.next_page_number }}" class="next"> <i class="pe-7s-angle-right"></i></a> </li> {% endif %} </ul> </div> then here is the … -
Getting django error even after deleting mistake line
i've been trying djano project that include channels & redis. recently i recreated venv and i get following even after deleting mistaken line. is there a way to clear cache in django project and runserver again? ''' line 52, in message to = models.ForeignKey(to='user',on_delete='',related_name = 'to') File "/home//python-projects/DjangoChannels/.env/lib/python3.8/site-packages/django/db/models/fields/related.py", line 801, in init raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable.''' -
How to set a model with autofield and create a new record?
How can I create a model with auto increment field, primary key. How can I create a new record? -
Defning Django admin models inside subdirectories instead of admin.py
My goal is to define admin models in separate files. So the project structure looks like this: app admin_models __init__.py TestAdmin.py TestAdmin.py: from django.contrib import admin from cms.models import ( TestModel) class TestAdmin(admin.ModelAdmin): fields = (...) admin.site.register(TestModel, TestAdmin) The problem is that the model does not appear on the admin page. However, in standard structure (if I move TestAdmin.py file's content to admin.py on the top level inside the app) then everything works fine. Anyway to fix this? -
Django React: API HTML Response not rendering no the browser
As an exercise, I was trying to render and HTML Response trying to use Django Rest Framework Renderers. I have a React frontend that sends a post request to the API request in a react component axios.get('/api/upload_photo', config).then(res => res.render()) router router.register("api/upload_photo", UploadPhotoViewSet, "upload_photo") API class UploadPhotoViewSet(viewsets.ViewSet): parser_class = (FileUploadParser,) renderer_classes = [TemplateHTMLRenderer] def list(self, request, format=None): return Response({}, template_name='api/test.html') template.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>HEEEEEY it worked</h1> </body> </html> The problem is I get the response with the Html page but it's just as response and the Html doesn't render on the browser -
Language Selector not Switching to Chinese
I made a language selector its right from the docs, when I run the server I can switch to English, and Dutch. But, when I try and switch to Chinese it just goes back to english. Navbar.html: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select name="language" onclick="Bonjour"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code = LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go" /> </form> Settings.py MIDDLEWARE = [ ... "django.middleware.locale.LocaleMiddleware", ... ] ... # Translations USE_I18N = True USE_L10N = True LANGUAGES = ( ("en", u"English"), ("zh-cn", u"简体中文"), ('de', u"German"), ) ... Let me know if you need to see more code, and from where. -
Create message Error with UniqueConstraint Django
I try to create a message if the same Todo exists and return a message but I'm a bit lost ^^' what should I do ? models.py created = models.DateTimeField(auto_now_add=True) content = models.CharField(max_length=300, blank=False) status = models.BooleanField(default=False) def __str__(self): return self.content class Meta: constraints = (models.UniqueConstraint(fields=['content'], name='unique_todo'),) ordering = ['created'] views.py class NewTodoFormView(FormView): form_class = TodoForm success_url = reverse_lazy('todo_site:todo-list') def get(self, request, *args, **kwargs): form = TodoForm() return render(request, 'todolist/newTodo.html', {'form': form}) def post(self, request, *args, **kwargs): if request.method == 'POST': form = TodoForm(request.POST) if form.is_valid(): try: form.save() except IntegrityError: return redirect('todo_site:todo-new') return redirect('todo_site:todo-list') return render(request, 'todolist/newTodo.html', {'form': form}) thanks for your help :) -
Correct on_delete option
Say I have a Car model and a CarImage model and the CarImage model uses a foreign key to relate to a Car object. If I set on_delete=models.CASCADE when I delete an image will that also delete the Car object that CarImage is linked to? models.py class Car(models.Model): title = models.CharField(max_length=80) class CarImage(models.Model): image = models.ImageField(upload_to='images') model = models.ForeignKey(default=1, on_delete=models.CASCADE, to='main.Car') -
Django: safely deleting an unused table from database
In my django application, I used to authenticate users exploiting base django rest framework authentication token. Now I've switched to Json Web Token, but browsing my psql database, I've noticed the table authtoken_token, which was used to store the DRF authentication token, is still there. I'm wondering how to get rid of it. I've thought about 2 options: deleting it through migration: I think this is the correct and safer way to proceed, but in my migrations directory inside my project folder, I didn't find anything related to the tokens. Only stuff related to my models; deleting it directly from the database could be another option, but I'm afraid of messing with django migrations (although it shoudn't have links with other tables anymore) -
Creating manual tokens using django rest_framework_simplejwt
I am new to django and to rest_framework and I would like to create manual token using django rest_framework_simplejwt. A page on its documentation shows how to do this but it seems to me that it lacks further detail. code in the documentaion: from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } I was wondering where to put this piece of code exactly. I tried to put it in my views.py but im having an error saying "'WSGIRequest' object has no attribute 'id'" I have yet to read the documentation for the rest_framework library alone, hoping i could get a quick answer here. -
Context from views.py didn't show in template. How can I solve this problem?
I'm trying to reverse a function from views.py to my html file. I only got 1 key (count) that is showing in index.html. The rest are just blank, also it didn't return error like you see in the code below. Please check also my result preview in the bottom of this post. also it didn't return error like you see in the code below. models.py class Orders(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) total_order = models.DecimalField( max_digits=6, decimal_places=2, default=0.00) status = models.CharField(max_length=64, default="Initiated") date = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return f"{self.pk} - {self.user} | Status: {self.status} | Total: ${self.total_order} | Date: {self.date}" class All_Orders(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order_id = models.IntegerField() order_item = models.CharField(max_length=64) extras = models.CharField(max_length=512) item_price = models.DecimalField( max_digits=4, decimal_places=2, null=True, blank=True) def __str__(self): return f"{self.pk} - {self.user} | Order ID: {self.order_id} | Item: {self.order_item} | Extras: {self.extras} | Price = {self.item_price}" views.py def cart_item_view(request): order = Orders.objects.get(user=request.user, status="Initiated") cart = All_Orders.objects.filter(user=request.user, order_id=order.pk) count = 0 for item in cart: count += 1 context = { "cart": cart, "count": count, "total_order": order.total_order, "order_id": order.id, } return HttpResponseRedirect(reverse("index"), context) urls.py urlpatterns = [ path("", views.index, name="index"), path("cart_item", views.cart_item_view, name="cart_item"), ] index.html <div class="jumbotron item_list"> <h3>Item(s) in cart: {{ count }}</h3> <table … -
Django: apply filtering on model imported from external library
Is it possible to apply easy filtering to a list of object retrieved from an API, without having a model in my Django app? I can import the model of the retrieved objects from an external library, but I don't have a Django model in my apps for them. -
Django user creation with costume boostrap form
i know how to create and extend a usercreation form using the Django modelsform. but how can i create and authenticate a user without using the inbuilt Django form instead i will use a bootstrap form having my own tailored designs and additional fields -
Error when trying to add permissions to a group in django admin panel
I am trying to add a few existing permissions to the group inside the django admin panel. But its showing the below error and I haven't got a clue why its happening. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/auth/group/4/change/ Django Version: 3.0.6 Python Version: 3.8.2 Installed Applications: ['exams.apps.ExamsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception (syntax error at or near "ON" LINE 1: ...ons" ("group_id", "permission_id") VALUES (4, 20) ON CONFLIC... ^ ) was the direct cause of the following exception: File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 231, in inner return view(request, *args, **kwargs) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1641, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/defiant/Projects/Python3.8/lib/python3.8/site-packages/django/utils/decorators.py", … -
implement ajax with django
english is not my first language so i will try explain as good as i can . I am trying to achieve that my page does not relaod/refresh when someone publish comment and like dislike the article. if someone could do that for me and write an explanation how it works and what is going on. I do not know javascript. VIEWS.PY from django.shortcuts import render,redirect,HttpResponseRedirect from .models import The_Article ,Comment from .import forms from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import User from accounts.models import Profile def group_articles(request): return render(request,'articles/group_art.html') def the_articles(request,value): posts = The_Article.objects.filter(article_choice=value) return render(request,'articles/articless.html',{'posts':posts}) def one_article(request,slug): # here is passed user that is currently logged in posts = The_Article.objects.get(slug=slug) post = Comment.objects.filter(post=posts,replay=None).order_by('-id')# 1 comm=to article like_users = posts.like.all() if request.method == 'POST': new_comm = forms.New_Comment(request.POST) if new_comm.is_valid(): # remember new_comm is form of Comment object replay_id = (request.POST.get('comment_id')) parent = None if replay_id: parent = Comment.objects.get(id=replay_id)# this's executed last comm_save = new_comm.save(commit=False) comm_save.post = posts #this will be executed before/// post = Comment.objects.filter(post=posts,replay=None).order_by('-id') comm_save.replay = parent comm_save.user = request.user comm_save.save() # this is saved in my Comment object return HttpResponseRedirect('') else: new_comm = forms.New_Comment() return render(request,'articles/one_article_page.html',{'posts':posts,'new_comm':new_comm,'post':post,'like_users':like_users}) def create_article(request): if request.method == 'POST': form = forms.New_Article(request.POST) if form.is_valid(): … -
Model Placement
It is necessary to place posts on the site so that they can be created and edited, but in the site design the posts are separated by sliders and other elements, how is it possible to implement this in such a way that the other layout elements are, so to speak, ignored? I tried to solve this problem by creating additional models, that is, the posts before the separating elements (sliders in this case) should be taken in one class, and the subsequent ones in another and further edited in such a way. Of course this is a crutch, but I don’t know how to configure it, because together these models are not displayed for me, that is, either one or the other. I also created a separate class for the Main Post, because it has a different design and, as a matter of fact, always hangs in the top, but of course it’s ideal to implement such that the model has such an attribute that you can indicate to a specific post that it is the main and most located at the beginning of the site. Here is my code (let's say that we added Posts_one, Posts_two, if we … -
Django, how to set value in forms.ModelForm
I have a question for you. I have the following Model: class AltriCosti(models.Model): STATUS_CHOICES= [ ('VARIABILE', 'VARIABILE'), ('FISSO', 'FISSO'), ] centro_di_costo = models.ForeignKey(Centro_di_costo) sub_centro_di_costo = models.CharField('Categoria', max_length=30) status = models.CharField(choices=STATUS_CHOICES) I use it in a lot of view, but in one of them I wanna set the value without passing from the POST request. So I have tried to set the ModelForm in the following manner: class ModCollaboratori(forms.ModelForm): class Meta: model = AltriCosti fields = "__all__" def __init__(self, *args, **kwargs): super(ModCollaboratori, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields['centro_di_costo'].value= "Servizi di Produzione" self.fields['sub_centro_di_costo'].value = "Collaboratori esterni" self.fields['status'].value = "VARIABILE" But It does not work. How could I fix the code to work? -
class has no object error with django and python
I am using Django . Can anyone please check what's the error in here : I keep getting an error in my view.py "Class Rate has no objects member" This is views.py : from django.http import HttpResponse from django.shortcuts import render from .models import Rate def index(request): context = { "rates":Rate.objects.all() } return render(request,"rates/index.html", context) and this is my models.py: from django.db import models class Rate(models.Model): ratename=models.CharField(max_length=64) hourlyrate=models.IntegerField() def __str__(self): return f"{self.ratename} - {self.hourlyrate}" -
Does there any difference between return statement in backend language like django than in programming language like java,c++,python?
Here is my code from views.py from django.shortcuts import render from basicapp import forms def form_name_view(request): form = forms.FormName() if request.method == 'POST': form = forms.FormName(request.POST) if form.is_valid(): print("Validation sucess!!") print("Name: "+form.cleaned_data['name']) print("Email: "+form.cleaned_data['email']) print("Text: "+form.cleaned_data['text']) return render(request,'basicapp/form_page.html',{'form':form}) here according to me , if statement inside form_name_view should'nt work because it is taking data from form input to print name,email etc in console. but my doubt is that to fill data inside form there need to load basicapp/form_page.html and it is inside return statement.so after executing return statement how could if statement execute as return statement is end of the function -
Django view design - export CSV from user-generated content
On my Django app, users get a unique (partly random) output for each request. I would like to allow the user to download the exact same output (shown in an HTML table) as CSV. My difficulty is how to design this flow so the result generated from form.generate_cassettes() will be used for the csv export. Where should the export logic go? Where should the csv response be located in my view? What should the "export to csv" button in the HTML page be calling? This is the view in my django app: def generate_rna(request): if request.method == 'POST': form = RNAGeneratorForm(request.POST) if form.is_valid(): result = form.generate_cassettes() context = { "form": form, "cassettes": result } return render(request, 'rnagen/RNA.html', context) else: form = RNAGeneratorForm() context = { "form": form } return render(request, 'rnagen/RNA.html', context) The "cassettes": result and the input from the user form in the field name Sequence String is all the information I need to generate the csv.