Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get this error when running migrate command. invalid literal for int() with base 10: 'portraiture'. Below is my code. Django version=1.11
class Category(models.Model): TRAVEL = 'TR' WEDDING = 'WE' PORTRAITURE = 'PR' CATEGORIES = ( ('TRAVEL', 'travel'), ('WEDDING', 'wedding'), ('PORTRAITURE', 'portraiture'), ) category = models.CharField( max_length=32, choices=CATEGORIES, default='PORTRAITURE', ) class Image(models.Model): image = models.ImageField((""), upload_to='images/', height_field=None, width_field=None, max_length=None, blank=True) image_name = models.CharField(max_length=60) image_description = models.TextField() location = models.ForeignKey(Location, null=True) category = models.ForeignKey(Category, default='PORTRAITURE') pub_date = models.DateTimeField(default=datetime.now, blank=True) tags = models.ManyToManyField(tags) -
os.path.expanduser("~") + "/Downloads/" not working
In my django app i have specified download location as Path = os.path.expanduser("~") + "/Downloads/" and it is running in apache2 mod_wsgi server..When i try to download it downloads content inside /var/www/Downloadsinside a server folder but not users Download directory?What is wrong with my download path? -
Cannot post data to mysql from template of django using vue
When i post data, i got the bellow message. CSRF Failed: CSRF token missing or incorrect. However, i am adding CSRF to header of axios like bellow. postArticle: function() { this.loading = true; csrftoken = Cookies.get('csrftoken'); headers = {'X-CSRF-Token': csrftoken}; axios.post('/api/articles/',this.newArticle, {headers: headers}) .then((response) => { this.loading = false; console.log(this.articles) console.log("success") this.getArticles(); }) .catch((err) => { this.loading = false; console.log("failed") console.log(err); }) }, i am including csrf like bellow. <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> On the other hand, I have tried other way like bellow. In html <meta name="csrf-token" content="{{ csrf_token }}"> postArticle: function() { this.loading = true; axios.defaults.headers.common= { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content') }; axios.post('/api/articles/',this.newArticle) .then((response) => { this.loading = false; console.log(this.articles) console.log("success") this.getArticles(); }) .catch((err) => { this.loading = false; console.log("failed") console.log(err); }) }, However, i cannot as well. What is the problem? -
FormSet validation of data change
from django.forms import formset_factory from django.shortcuts import render from myapp.forms import ArticleForm def manage_articles(request): ArticleFormSet = formset_factory(ArticleForm) if request.method == 'POST': formset = ArticleFormSet(request.POST, request.FILES) if formset.is_valid(): # do something with the formset.cleaned_data pass else: formset = ArticleFormSet() return render(request, 'manage_articles.html', {'formset': formset}) How does the Formset remember the previous request.POST in order to determine whether the data has changed or not from calling formset.has_changed() Is there somehow a call to database or it uses the client storage? If the View function is called for every request, a new ArticleFormSet instance is created with some data How does it remember the previous data? -
Value is none when calling out a value of foreign key
I am trying to display a brand of a bike, but the value shows as None. Models.py: class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) brand = models.ManyToManyField(Brand, null=True) class Brand(models.Model): name = models.CharField(max_length=20) and here's my template: {% for item in items %} {{ item.bike.brand.name }} {{ item.title }} {% endfor %} I am calling the brand by {{ item.bike.brand.name }} and it displays as None for every Bike -
Django using AJAX or Angular
I am building a blog where users can post and comment using Django, now there is a scenario that I have posts being display on my user page. Using Django for adding a comment it will redirect user to another page. How can I write this using AJAX or AngularJs? I am new to Angular and Ajax and I only need this function specifically. I appreciate all your help in advance! -
How to use 'async def' in django views?
views.py async def test(request: ASGIRequest): return HttpResponse(b'hello') class Test(View): async def get(self, request: ASGIRequest): print(type(request)) print(dir(self)) return HttpResponse(b'hello') urls.py urlpatterns = [ path('admin/', admin.site.urls), path(r'testfunc/', test), path(r'testclass/', Test.as_view()), ] i got this: AttributeError at /testclass/ 'coroutine' object has no attribute 'get' # AttributeError at /testfunc/ 'coroutine' object has no attribute 'get' -
Django: Settings' object has no attribute 'LOGFILE'
Thats my code and that's what django showing wing i run the server. Any help? from datetime import datetime from django.conf import settings class Utils(object): def get_logs(self): try: with open(settings.LOGFILE, 'r') as fd: data_logs = fd.readlines() return data_logs except IOError: return [] def write_log(self, content): date = datetime.now() with open(settings.LOGFILE, 'a+') as fd: fd.write("%s : %s\n" % (date.strftime("%b %d %Y %H:%M:%S"), content)) -
Django Models - Unable to get readonly inlines and save data to different models
class Question(models.Model): name = models.ForeignKey(SomeModel, related_name="somemodel_fk", on_delete=models.PROTECT, default=None) question = models.TextField(max_length=200, unique=True) class Choice(models.Model): name = models.ForeignKey(Question, related_name="question_fk", on_delete=models.PROTECT, default=None) answer = models.TextField(max_length=200, unique=True) class FormList(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default=None) # question = models.Field("Is this needed? Want this in the list. Duplicate column") # Choice has the foreignkey to Question answer = models.ForeignKey(Choice, on_delete=models.PROTECT, default=None) selected_answer = models.TextField("selected",max_length=200, unique=True) correct_selection = models.BooleanField("correct answer",max_length=200, unique=True) First, I want the admin to show the Question and Choices Model in the form and when the submit is being done it should be saving to the data should be stored in the FormList. I can do inlines but I will have no option to make Question-Choices uneditable. Second, I in the admin can use just the FormList (due to foreign key) but am having issues getting the queryset for Answers(Many-1 with Question) and FormList(Many-1 with Question) Any idea how to get a view of Questions-Multiple Choices in the view and save to FormList. The FormList will be saving Question Answer into the Table. 1: Question: What is the answer? A: Choice 1 B: Choice 2 C: Choice D: Choice 4 Storage will be in FormList (Was not able to do this). Any help … -
make a join course feature with django
I have a "courses" model, and I want to make a join course feature, if the join will already be saved in my course, can anyone help? -
How do I increase the size of a Django form
this is my first project with using Django. I am creating a form as follows and as you can see on the screenshot below, the form is just to narrow. I'd like the input fields to go across the whole screen which is not possible when the form is that narrow. How can I increase the width of the form. from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Row, Field from ..models import EvilSnippet class AddSnippet(forms.Form): class Meta: model = EvilSnippet code_language = forms.ChoiceField( label = "Select Language", choices = (("Java", "Java"), ("Python", "Python"), ("C#", "C#")), required = True, ) severity = forms.ChoiceField( label = "Severity", choices = (("HIGH", "HIGH"), ("MEDIUM", "MEDIUM"), ("LOW", "LOW")), required = True, ) description = forms.CharField( label = "Description", required = False, #widget=forms.TextInput(attrs={'size': '20'}) ) code = forms.CharField( label = "Code", required = False, widget=forms.Textarea() ) def __init__(self, *args, **kwargs): super(AddSnippet, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-addSnippet' self.helper.form_class = 'uniForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_snippet' self.helper.layout = Layout( Row( Field('code_language', wrapper_class='col-md-6'), ), Row( Field('severity', wrapper_class='col-md-6'), ), Row( Field('description', wrapper_class='col-md-6'), ), Row( Field('code', wrapper_class='col-md-6'), ) ) self.helper.add_input(Submit('submit', 'Submit')) and {% extends 'base.html' %} {% load crispy_forms_tags %} {% … -
Django Rest_framework Apiview to show items
i'm creating a django api, to show the product count for each manufacturer as users add products real time. i've tried this and it's not work, and am getting a null constraint err when i wan add item to my cart using the api, can any one help me out pls class CartViewSet(viewsets.ModelViewSet): serializer_class = CartDetailSerializer queryset = CartList.objects.all() #@detail_route(methods=['post', 'put']) def add_item(request, self, pk=None): cart = self.get_object() try: product = Product.objects.get( pk = request.data['product_id'] ) quantity = int(request.data['quantity']) except Exception as e: print (e) return Response({'status': 'fail' }) if product.quantity < 0 or product.quantity - quantity < 0: print('sorry check back leta') return Response({'status': 'fail'}) existing_cart = CartList.objects.filter(product=product, cart=cart).first() if existing_cart: existing_cart.quantity +=quantity existing_cart.save() else: new_cart = CartList(cart=cart, product=product, quantity=quantity) new_cart.save() product_list = Product.Objects.filter(manufacturer=manufacturer).count() serializer = CartSerializer(cart) return Response(serializer.data) -
Filter function doesn't works as it supposed to
I am trying to filter results, that are inside a specific category. I click on a category and all items that are inside that category are showing. Then I have a content filter on the side that is supposed to filter that results further by title and price. The thing is that title query works, but for every Item inside Item table. Here's my models: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') class Accessory(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category_accessory = models.ManyToManyField(CategoryAccessory, blank=True) image = models.ImageField(upload_to='accessories') views.py: def SearchView(request, category_id=None): if category_id: category = Category.objects.get(pk=category_id) item_list = Item.objects.filter(category__id=category_id) else: item_list = Item.objects.all() title = request.GET.get('title') if title: item_list = item_list.filter(title__iexact=title) else: query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) context = { 'item_list': item_list, 'category': category, } return render(request, "search.html", context) and template: {% for bike in item_list %}{% for item in item_list %} <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view … -
AttributeError: 'CoreManager' object has no attribute 'place_from'
models.py class Segment(CoreModel, ): place_from = models.ForeignKey(Place, on_delete=models.CASCADE, related_name="segments_start", limit_choices_to=Q(place_type=CITY_OR_VILLAGE)) place_to = models.ForeignKey(Place, on_delete=models.CASCADE, related_name="segments_to", limit_choices_to=Q(place_type=CITY_OR_VILLAGE)) forms.py class PlaceForm(forms.Form): place_from = forms.ModelChoiceField(queryset=Segment.objects.place_from) How i can do this? -
Pass Django Data into Vue component
I am using Django as a backend and I am trying to pass some data into a Vue table component that I made. I set it up using this tutorial The component is showing up fine while using a webpack. I am trying to set the data to a javascript constant and then pass it into the component. The data does not appear to be passing through. Here is how my scripts are laid out. index.html {% block content %} <script> const gridData = {{json_data|safe}}; console.log(gridData) </script> <div id="app"> <table_component v-bind:tableData=this.gridData > </table_component> </div> {% end block %} myComponent.vue script seciton export default { name: 'table_component', props: { tableData: Array }, data() { return { } }, components: { Grid, ButtonModal }, created(){ console.log(this.tableData) }, } When I look at the console, it is not showing any data. It just says undefined. view.py class CurrentClassroomView(LoginRequiredMixin, CreateView): template_name = 'home/index.html' def get(self, request, *args, **kwargs): db_data = list(myData.objects.all().values()) my_json_data = json.dumps(db_data) return render(request, self.template_name, {'json_data':my_json_data}) I am getting this in the console that I am not sure what that means and why it is making everything lowercase even though I'm passing it with upper case letters. [Vue tip]: Prop "griddata" is … -
Page not found 404 on Django server?
I am doing a Django course and in my first tutorial only I am getting "Page on found 404 error" while mapping the URL will the view. I referred to this link and did same steps I am still getting same error. https://docs.djangoproject.com/en/3.0/intro/tutorial01/ polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), polls/view.py ` from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") mysite/urls.py ' from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ]' Directory of my code Help me with the error... I checked all sources and followed exactly the link... Still cannot run it properly -
how to alter references to wagtail's groups attribute?
I am using wagtail as part of a multi-tenant setup using django-tenant-schemas and django-tenant-users. Whenever I specify my custom user model that extends django-tenant-users's UserProfile, as required by django-tenant-users, wagtail breaks the application because it is trying to access the groups attribute, which UserProfile does not have. The groups attribute lives in a different model. How would I go about changing every reference to a user's groups attribute in wagtail? Output: File "/home/cirrus-admin/cirrus/cirrus_core/cirrus_core/urls.py", line 25, in <module> from wagtail.admin import urls as wagtailadmin_urls File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py", line 12, in <module> from wagtail.admin.urls import password_reset as wagtailadmin_password_reset_urls File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/admin/urls/password_reset.py", line 3, in <module> from wagtail.admin.views import account File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/admin/views/account.py", line 14, in <module> from wagtail.users.forms import ( File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/users/forms.py", line 178, in <module> class UserCreationForm(UserForm): File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/django/forms/models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (groups) specified for User -
Python, Django - Find a folder of an installed package
In my project, I use Django allauth to allow users to login using their google account. However I want to override the default templates for this package, therefore I need access to the actual allauth folder that was created when I did a pip install. I need this folder, as it contains two subfolders I need to add to add to my project. I have already checked a folder called site_packages which another answer on a question told me to go check through, however no allauth folder was found. Does anybody know where I can gain access to this folder, so I can use parts of it in my project? Also when I pip installed allauth package, it was not added to my Pipefile, whilst all my other packages were. Thank you. -
How to avoid using ON CONFLICT DO ' 'NOTHING' on Django?
I have an webapp running in a CentOS Server with Django 3.0 and PostgreSQL 9.4.25. Cant upgrade ph right now. On this wepapp there are many queries generated by django that look like this: INSERT INTO public.cad_uf (nome, sigla, regiao_id) VALUES('xxxxx', 'xxxxx', 0) ON CONFLICT DO NOTHING; The problem is that "ON CONFLICT DO NOTHING" is not available on this pg version (9.4.25). How can I make django dont generate this ending code in SQL, looking like this: INSERT INTO public.cad_uf (nome, sigla, regiao_id) VALUES('xxxxx', 'xxxxx', 0); -
Passing variables from HTML to Python app to execute using Django
I am trying to have a user input their information in the HTML form and then send it to my Python app that is located in the root of the directory and then run the python program. Below is my code for views.py and my html form. My program I want to execute is app.py and would take the variables and use them in the program. How do I pass a variable from the HTML to my Python app and then execute the program? I followed along with a youtube video to setup the externapApp function but I'm having problems executing app.py and making sure the variables are passed to the app. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1 class="display-4">Flatbush Zombies Shop Bot</h1> <p class="lead">This is a bot written in Python that will shop <a href="https://thegloriousdead.com/">this</a> website for you. This website sells out of its products right away when they are released so this bot can purchase your desired items in an instant!</p> </div> </div> <div class="form"> <form action="/externalApp/" method="POST"> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-default">First name</span> </div> … -
Can't import top level packages in django project
I'm working on a django project that requires me to import code from another package. For exmaple, in my "home" app, I'm import from the "users" app. In my index.py view in the home app, I'm using from project.users import services. Running this from a python shell works fine, however, if I try to run python3 manage.py runserver, I get the error ModuleNotFoundError: No module named 'project.users'. I tried adding my project directory and its parent to my sys.path, however, nothing changes. I also tried using a different machine and a venv with no success. How would I be able to fix this? -
'NoneType' object has no attribute 'username'
I am currently working on a project that would take in a users information and store it. So far as I can tell there are no issues with storing the data, but when I try and access the user section on my admin page it gives me this error: AttributeError at /admin/users/profile/ 'NoneType' object has no attribute 'username' Request Method: GET Request URL: http://127.0.0.1:8000/admin/users/profile/ Django Version: 2.2.10 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'username' Exception Location: /Users/ethanjay/Django Projects/opinions_app/users/models.py in __str__, line 28 Python Executable: /Users/ethanjay/Enviroments/py3/bin/python Python Version: 3.7.4 Python Path: ['/Users/ethanjay/Django Projects/opinions_app', '/Users/ethanjay/Enviroments/py3/lib/python37.zip', '/Users/ethanjay/Enviroments/py3/lib/python3.7', '/Users/ethanjay/Enviroments/py3/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages'] Server time: Fri, 28 Feb 2020 21:25:57 +0000 There are a few other people with the same error posted, but I can't seem to make sense of their solutions. Any help or advice that would point me in the right direction would be greatly appreciated! models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') gender = models.CharField(max_length = 1, choices = GENS, default = '') birthday = models.DateField(default = '1900-01-01') address = AddressField(on_delete=False, blank=True, null=True) race = models.CharField(max_length = 2, choices = RACES, default = 'x') ethnicity = models.CharField(max_length = 1, choices = ETHNICITIES, default … -
can I share a database between Django 1.11 and Django 2.x?
Can Django 1.x and 2.x share the same database, or does 2.x make changes to the database that would break 1.x? My app currently runs on on Python 3.6 + Django 1.11. I need to upgrade to Django 2.x. What I'd like to do is run two apps side-by-side: so "www.example.com" is my production site, running Django 1.11. I'd like to run a parallel site for trusted users at "beta.example.com" which would be the same site, but implemented with Django 2.x. I want these two sites to share the same (Postgres) database so that work done in the beta site is "real" and will persist if something can't be done in the beta site, i can tell a user to use the existing production site I can promote my beta site to production by changing DNS entries. (And my next question will be "Can Django 1.x and 3.x share the same Postgres database?") -
Django - Access ForigenKey object fields of chain in a template
Assuming the following cenario at a django app: views.py: def my_purchases(request): if request.method == 'GET': list_my_purchases = sorted( chain( Item_X_Licence.objects.filter(user=request.user, status=1), Item_Y_Licence.objects.filter(user=request.user, status=1) ), key=attrgetter('paid_date'), reverse=True ) paginator = Paginator(list_my_purchases, 20) # Show 20 per page page = request.GET.get('page') my_purchases = paginator.get_page(page) user = request.user args = {'user': user, 'my_purchases': my_purchases, } return render(request, 'App/my_purchases.html', args) and the following 2 models (Item_X and Item_Y are basically the same, so I will only show it for one of them here) models.py class Item_X_Licence(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Item_X, on_delete=models.CASCADE) status = models.IntegerField(choices=PAYMENT_STATUS, default=0) paid_date = models.DateTimeField(auto_now_add=True) ... class Item_X(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=25) .... My question now is the following: How can I access the title of Item_X in my_purchases.html template? currently I'm only able to get back the Item_X_Licence object (id) itself, but thats basically everything ... {% for my_purchases in my_purchases %} <tr class="font-size-small"> <td>{{ my_purchases }}</td> </tr> {% endfor %} Currently list_my_purchases acceses Item_X_Licence but I dont know how i can get up to Item_X and the fields like author and title as i want to display them at my template. thanks :) -
django put some objects in last of queryset
I have a queryset of objects with fields - is_out_of_stock, sales. What I want is to order this qs according to either sales but the objects having is_out_of_stock = True should always be in last of queryset. How to do it in django ? I have tried these - queryset.order_by('is_out_of_stock','sales') but this sort list by is_out_of_stock, I want to sort list by sales but all the objects having is_out_of_stock should be in last.