Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
buy x get y free drf django
i want to implement buy x get y on product models and only user are listing on order api. models.py: class Product(models.Model): name = models.CharField(max_length=50) price = models.CharField(max_length=10) def __str__(self): return self.name class OrderProduct(models.Model): order_status = ( ('created','created'), ('processing','processing'), ('ordered','ordered') ) user = models.ForeignKey(User,on_delete=models.CASCADE) item = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='products') order_status = models.CharField(choices=order_status,null=True,max_length=50) ordered_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return str(self.user) serializers.py: class Product(models.Model): name = models.CharField(max_length=50) price = models.CharField(max_length=10) def __str__(self): return self.name class OrderProduct(models.Model): order_status = ( ('created','created'), ('processing','processing'), ('ordered','ordered') ) user = models.ForeignKey(User,on_delete=models.CASCADE) item = models.ForeignKey(Product,on_delete=models.CASCADE, related_name='products') order_status = models.CharField(choices=order_status,null=True,max_length=50) ordered_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return str(self.user) serializers.py: class ProductSerializers(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class OrderProductSerializers(serializers.Serializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) item = ProductSerializers(many=True, read_only=True) class Meta: models = OrderProduct fields = ('item','user','order_status','ordered_date') views.py: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializers class OrderViewSet(viewsets.ModelViewSet): def list(self, request): queryset = OrderProduct.objects.all() serializer = OrderProductSerializers(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = OrderProduct.objects.get(pk=pk) serializer = OrderProductSerializers(queryset) return Response(serializer.data) def create(self,request): data = request.data.get("order") serializer = OrderProductSerializers(data=data,many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py: path('product/list/',ProductViewSet.as_view({'get':'list'}),name='product_list'), path('product/<pk>/',ProductViewSet.as_view({'get':'retrieve'}),name='product_retrieve'), path('product/',ProductViewSet.as_view({'post':'create'}), name='product_create'), path('order/list/',OrderViewSet.as_view({'get':'list'}),name='order_list'), path('order/<pk>/',OrderViewSet.as_view({'get':'retrieve'}),name='order_retrieve'), path('order/',OrderViewSet.as_view({'post':'create'}), name='order_create') ........................................................................................................................................................................................ -
Handle one Django form in separated HTML forms
I have a web project for uni and I took this as an opportunity to start learning Django. I have a big Django form splitted in the HTML code between several div tags, each div containing a form tag where some of Django's form fields are expanded. My problem is when submitting it. If I have a submit button in a HTML form, I will receive only the Django's form fields from that HTML form. How can I obtain the values of all the form fields? I tried adding one button at the end of all divs but that didn't work either. For example: The first "Next form" button will send me to the second form. If I click the submit button, in the backend I will receive only form.field_three and form.field_four and I would like to receive also form.field_one and form.field_two. Thank you! <div class="example-one"> <form method="POST"> {% csrf_token %} {{form.field_one}} {{form.field_two}} <input type="button" value="Next form"> </form> </div> <div class="example-two"> <form method="POST"> {% csrf_token %} {{form.field_three}} {{form.field_four}} <input type="submit" value="OK"> </form> </div> -
Sending mail in python django
I want to configure a setting to send the mail using python django. But I don't want to use username and password. Is it possible? -
I need a better way to do this
Am having issues doing something. I need a better way of doing it. It is about the get_absolute_url. everything about it is actually working fine but it failed in some part of my template. In the views i have this function def get_category_count(): queryset = Post.objects.values('categories__title').annotate(Count('categories')) return queryset and i used it right here in another function in the view like this def blog(request): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[0:3] context = { 'most_recent': most_recent, 'category_count':category_count } return render(request, 'blog.html', context) And i have actually done a category slug function like this def category(request, slug ): queryset = Post.objects.all() if slug: category_object = get_object_or_404(Category, slug=slug) queryset = queryset.filter(categories__title=category_object) context = { 'queryset':queryset, } return render(request, 'category.html', context) Now in the template of blog i have this <div class="category"> {% for cat in post.categories.all %} <a href="{{cat.get_absolute_url}}">{{ cat.title }}</a> {% endfor %} </div> now it happened that in this same template i have another section where i have this {% for cat in category_count %} <div class="item d-flex justify-content-between"> <a href="{{cat.get_absolute_url}}">{{cat.categories__title }}</a> <span>{{cat.categories__count}}</span> </div> {% endfor %} it happened that right here the get_absolute_url did not work. Maybe because of the get_category_count function in the views. Now i need a better … -
How to check password and show error message in django template?
I want to show error message if user provide the wrong password on logging. Even if I enter wrong password, it shows me Username do not match error. This is my views.py def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) return redirect('frontend:index') else: if request.user.username != request.POST['username']: messages.error(request, 'Username do not match.') return redirect('accounts:login') elif request.user.password != request.POST['password']: messages.error(request, 'Password do not match') return redirect('accounts:login') else: return render(request, 'accounts/login.html') -
How to use ajax with django pagination in table?
So in my page i have one historic table, i tried paginate that in view like this: paginator = Paginator(historic_approval, 5) # Show 50 per page page = self.request.GET.get('page') try: historic_approval = paginator.page(page) except PageNotAnInteger: historic_approval = paginator.page(1) except EmptyPage: historic_approval = paginator.page(paginator.num_pages) return Response({'list_pending': list_pending, 'historic_approval': historic_approval}) But this way every time i change a page in this table the page is refresh I tried use django el_pagination but not work for me. This my django template: {% if historic_approval %} <div class="col-md-7 col-md-offset-12" style="border-left: 3px solid #337AB7; padding-bottom:20px"> <span class="lead text-muted">{{ internal_title_list_count|default:"" }} {% trans "Meu histórico de aprovações" %} </span> <div style="border: 1px dashed #337AB7; background-color:#F4FAFF; padding:20px 10px;margin-top:10px"> {% paginate historic_approval %} {% for requisition in historic_approval %} <div class="row" style="border: 1px dashed #ddd; background-color:#fff; padding:10px; margin:10px 0;"> <div class="col-xs-12"> {{ requisition.requisition }}</br> <small class="alert-success"> {% trans 'Aprovada em' %}: {{ requisition.date_approved }}</small> </div> </div> {% endfor %} {% show_pages %} </div> </div><!-- end col --> {% endif %} </div><!-- end row --> -
Getting AttributeError when 'authenticate' in custom AuthenticationForm
I am trying to customize the default AuthenticationForm for some of my requirements in Django. Customized login works good when I am enter correct credentials. But if I enter incorrect password, then I am getting error message as below. error message (or exception) raised while authenticating at code "self.user_cache = authenticate(username=username, password=password)". Please help me if I am missing anything here. Error AttributeError at /login/ 'CustomAuthenticationForm' object has no attribute 'authenticate' Request Method: POST Request URL: http://127.0.0.1:8000/login/?next=/ Django Version: 1.6.10 Exception Type: AttributeError Exception Value: 'CustomAuthenticationForm' object has no attribute 'authenticate' Exception Location: C:\vmshare\workspace\DAU_2\dau_gui\venv\lib\site-packages\django\contrib\auth\__init__.py in authenticate, line 49 Python Executable: C:\vmshare\workspace\DAU_2\dau_gui\venv\Scripts\python.exe Python Version: 2.7.9 My customized login class CustomAuthenticationForm(AuthenticationForm): def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: try: user = User.objects.get(username=username) except User.DoesNotExist: user = None raise forms.ValidationError('User does not exist.') try: self.user_cache = authenticate(username=username, password=password) except User.DoesNotExist: raise forms.ValidationError('Incorrect password.') if user is not None: self.confirm_login_allowed(user) else: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name},) return self.cleaned_data def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError('There was a problem with your login.', code='invalid_login') In my settings.py I added this AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend','dau_gui_app.forms.CustomAuthenticationForm') -
Django - passing arguments between views
I want to pass the argument "x" from the first view to the second one for further processing but I always fail with the error: ['“$input_of_x” is not a valid UUID.'] (my user object is a UUID) I don't understand how to make those two views talk with each other, maybe somebody can explain to me how i can make x reachable in def execute(request) function. def check(request) user = request.user form = UserInputX(data=request.POST) if form.is_valid(): x = str(form.data.get("input")) check_x = \ ... if check_x == str('true'): if blabla: request.session['userID'] = x return redirect(reverse('execute')) else: messages.error(request, 'some error text output') return redirect('check') ... def execute(request): user = User.objects.get(id=request.session['userID']) form = Y_Form(request.POST) if request.method == "POST": if form.is_valid(): if request.POST['y'] == user.y: ... user.save() messages.success(request, 'some success message') return redirect('check') ... else: return redirect('execute') -
Debug Docker Container with Visual Studio Code
I have a Django project in Visual Studio Code. I start it through a virtual machine (linux) using Docker. I want to be able to debug the project by adding breakpoints. I tried following this tutorial, but can't get it: https://code.visualstudio.com/docs/containers/debug-python The application starts in "localhost: 8000", the private IP of the physical machine is 192.168.0.102 and that of the virtual machine: 192.168.56.1. My file launch.json: { "name": "Python: Remote Attach", "type": "python", "request": "attach", "port": 5678, "host": "192.168.56.1", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ] } My views.py: # -*- coding: utf-8 -*- import tempfile, time import json import ptvsd ptvsd.enable_attach(address=('192.168.56.1', 5678)) #This is ok? ptvsd.wait_for_attach() ... The error: csuperior-web | Performing system checks... csuperior-web | csuperior-web | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f4742165b70> csuperior-web | Traceback (most recent call last): csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper csuperior-web | fn(*args, **kwargs) csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run csuperior-web | self.check(display_num_errors=True) csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check csuperior-web | include_deployment_checks=include_deployment_checks, csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks csuperior-web | return checks.run_checks(**kwargs) csuperior-web | File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks csuperior-web | new_errors = check(app_configs=app_configs) csuperior-web | File … -
Overriding from_db() in django models gives NoneType object has no attribute _meta
I've been tampering with django from_db() class method, Here's what I have class URL(models.Model): full_version = models.URLField() short_version_extension = models.CharField(unique=True, blank=True, max_length=10) expiration_time = models.TimeField() class Meta: verbose_name = 'Link' @classmethod def from_db(cls, db, field_names, values): super(URL, cls).from_db(db, field_names, values) This should be a URL shortener. I'm trying to save only the extension of the generated URL instead of saving it as whole (as the site is the same in all of them), I want to override from_db() to always add the short_version_extension to the current website (the one the django project is uploaded to). here's an example. www.mydomain.com\extension\ I want to save only the extension, and when I get it from the db, I want to add the www.mydomain.com. When I tried to override from_db(), I called super(URL, cls).from_db(db, field_names, values) to check if everything is working. But it didn't work as shown in image.1 I've tried to solve it by copying the body of from_db() from django code base, like this @classmethod def from_db(cls, db, field_names, values): if len(values) != len(cls._meta.concrete_fields): values_iter = iter(values) values = [ next(values_iter) if f.attname in field_names else DEFERRED for f in cls._meta.concrete_fields ] new = cls(*values) new._state.adding = False new._state.db = db … -
How to log using django background tasks?
I can easily create logs throughout the application using the logging module, but inside a django background task it does not work. import logging from background_task import background log = logging.getLogger("django") @background(schedule=1) def do_something(): log.info("it worked") running do_something() does not log anything, but if I remove the decorator it works... Does anyone know how to make it work? -
Setting an image rendition to center crop in Wagtail
I'm working on a CMS build (Python, Django, Graphene, Wagtail). I know wagtail offers a get_rendition that can resize an image to fit given dimensions (Similar to CSS background-size: cover). The options that appear to be available are based on resizing: https://docs.wagtail.io/en/v1.3.1/topics/images/using_in_templates.html#image-tag-alt But I'm looking for just a center crop with no resizing. -
Django python Javascript change url and call views without reloading
I am creating a new Django python project. I have an html that calls on a jquery to show a chart (using chart js) My views is: def CellsHistories(request,Cell_id): CellData = cellData.cell_Data(Cell_id) context = { 'CellData':CellData, } return render(request,'Main/index.html',context) calling that from url as: urlpatterns = [ path('CellsHistories/<int:Cell_id>/',views.CellsHistories), ] and the js for the chart has an onclick function that is: onClick: function(e) { var element = this.getElementAtEvent(e); // this is the charts object in this case and element becomes the clocked bubble if (element.length > 0) { var datasetLabel = this.config.data.datasets[element[0]._datasetIndex].label; var data = this.config.data.datasets[element[0]._datasetIndex].data[element[0]._index]; } var url = window.location.href url = url.replace(/\/[^\/]*[\/]$/, '/'+element[0]._datasetIndex+'/') window.location.replace(url); document.getElementById('SelectedCellbadge').textContent = 'Cell No. ' + element[0]._datasetIndex; } That works fine. My problem is that everytime that the url changes and the views is called the page reloads at the top. I have tried the pushstate() function which changes the url but does not call the views function again (django views called through my url request). Can I please have some ideas on how to change the url and trigger the django urls, and then views but without the page going to the top? I just want to be able to use my onclick … -
Type mismatch in django serializer for request parsing
I had created the following serializers for request parsing of JSON data. However, while performing the operation, I get an unexpected error. class A(serializers.ModelSerializer): class Meta: model = CName fields = ('id','contact','email') read_only_fields=('contact',) class B(serializers.ModelSerializer): class Meta: model = PName fields = ('id','contact','number') read_only_fields=('contact',) class C(serializers.ModelSerializer): contact_number = A(many=True) contact_email = B(many=True) class Meta: model = Contact fields = ('id','name','contact_number','contact_email') def create(self,validated_data): contact_number=validated_data.pop('contact_number') contact_email =validated_data.pop('contact_email') instance = Contact.objects.create(**validated_data) for number in contact_number: PName.objects.create(contact=instance,**number) for email in contact_email: CName.objects.create(contact=instance,**email) return instance def update(self, instance, validated_data): contact_number=validated_data.pop('contact_number') contact_email =validated_data.pop('contact_name') Contact.objects.filter(id=instance.id).update(**validated_data) number_to_keep=[] email_to_keep=[] for number in contact_number: if number.get('id'): ph_id = number.pop('id') PName.objects.filter(id=ph_id).update(**number) number_to_keep.append(ph_id) else: ph=PName.objects.create(contact=instance,**number) number_to_keep.append(ph.id) for email in contact_email: if email.get('id'): em_id = email.pop('id') CName.objects.filter(id=em_id).update(**email) email_to_keep.append(em_id) else: em = CName.objects.create(contact=instance,**email) email_to_keep.append(em.id) instance.contact_number.exclude(id__in=number_to_keep).delete() instance.contact_email.exclude(id__in=email_to_keep).delete() return instance I have a json-format where I am passing the request data in the format: { "contact_number": "9999999999", "contact_email":"timsh@hotmail.com" } While calling up the serializer using the following code: contact_details = Contact.objects.get(rest = rest) contact_serializer = ContactSerializer(contact_details,data=request.data) I received the response as below: { "contact_number": { "non_field_errors": [ "Expected a list of items but got type \"unicode\"." ] }, "contact_email": { "non_field_errors": [ "Expected a list of items but got type \"unicode\"." ] } } Note: I … -
Template not file Found Django
I am trying to make a home page of a new website via django. My app name is 'blog', home page is home.html I still receive the error 404 when I go to http://127.0.0.1:8000/blog/home.html I made sure I added 'blog' to my templates in settings.py and that I added the folder templates in the main directory as well as through blog/templates/blog/home.html blog/views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'blog/home.html') blog/urls.py from django.urls import path from . import views urlpatterns = [ path('home/', views.home, name='home'), ] myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], myproject/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] Do you see anything in my code which cause problem? I receive the message in blog/views.py that "Template file 'blog' not found" on the line return render(request, 'blog/home.html') -
Latest Chrome caching ajax response despite no cache headers
I have a simple form in a modal that gets populated by a ajax request (to a server running Django) If I add choices to a choice field, those choices are not displaying for a few minutes on the modal. This issues only appeared after updating to the latest version of chrome (80.3987.149). I am including no-cache headers in the ajax response like this: response['Cache-Control'] = 'no-cache, no-store, must-revalidate' response['Pragma'] = 'no-cache' response['Expires'] = '0' But it doesn't seem to matter. My ajax call method looks like this: openAlertModalOnclick(e) { e.preventDefault(); let self = this; $.get($(e.target).attr("href"), resp => { $("#alertModal").html(resp.html).foundation("open").foundation(); }) }).fail(() => { this.showErrorToast("Error occurred while loading alerts.") }) } I am 90% sure this is an issue with just the latest version of chrome, as I could not reproduce it until I updated chrome. Is there anything else I can do to get chrome to stop caching the form? -
Why I have this import error: cannot import name 'View' from 'homepage.views'
Why I have this import error: cannot import name 'View' from 'homepage.views' URLS: from homepage.views import View urlpatterns = [ path('admin/', admin.site.urls), path('homepage/', View), ] VIEWS: from django.http import HttpResponse def View(request): return HttpResponse('hello world') I have added 'homepage' into settings under apps. Thank you! -
passing html tags arguments in django template to javascript function
I want to pass HTML string as argument in javascript, in django template. Here it is: I have bunch of links, which they are in my database. I can access these links via {% for link in links %} {{ link }} {% endfor %} in my django template. for example, I can access a certain link name with using {{ link.name }}, but I also have content specified to every links; like {{ link.content }}. the problem is; in my template I have a sidebar nav which contains several link's urls, and I want to display the content of clicked link in that page. for that, I wrote a javascript function named display: <script> function display(str){ document.getElementById('cont').innerHTML = str: } </script> which will access: <div id="cont"> </div> here it is: <a class="nav-link active" href="{{ link.link }}" onclick="display('{{ link.content }}')">{{ link.name }}</a> in the code above, the display function doesn't work. I mean, when I click the link in sidebar, it doesn't show any content, literally nothing. but for test, when I changed the display argument {{ link.content }} to something else like '<h1>hello<h1>', it worked. p.s: my link's content is an inline html tags like: '<h1><strong>&nbsp; &nbsp; &nbsp; &nbsp; … -
multiple query model in same view django
I've been doing some django these past weeks and I'm having a problem. I have a page where Articles are shown. No problem while reovering all articles from db. But now I'd like to get all categories (an Article has a category) that I have in my database. So I can display like this in my page: List of categories -cat1 -cat2 -cat3 List of articles -art1 -art2 -art3 But I don't know how to do with both queries. Here's what I've tried. class IndexView(generic.ListView): template_name = 'eduardoApp/index.html' context_object_name = 'article_list' def get_queryset(self): return Article.objects.order_by('article_name') def get_categories(request): category_list=Category.objects.all() context = {'category_list':category_list} return render(request,'eduardoApp/index.html',context) And in my view: <h2>List of categories</h2> {% if category_list %} {% for category in category_list %} <p>{{ category.name }}</p> {% endfor %} {% else %} <p>no categorys</p> {% endif %} <h2>List of articles</h2> {% if article_list %} <div class="flex-container"> {% for article in article_list %} <div><a href="{% url 'eduardoApp:detail' article.id %}">{{ article.article_name }}</a></div> {% endfor %} </div> {% else %} <p>No articles...</p> {% endif %} {% endblock %} In my view I keep seeing no categorys displayed (since category_list does not exist but don't know why and how to fix) -
Django: display choice value instead of key
Model: class Model1(models.Model): STATUS_CHOICES = [ ('A', 'active'), ('D', 'deactivated') ] status = models.CharField(max_length=1, choices=STATUS_CHOICES,default='D') Serializers: class Model1Serializers(serializers.ModelSerializer): class Meta: model = Model1 fields = '__all__' View: class View(viewsets.ModelViewSet): queryset = Model1.objects.all() serializer_class = Model1Serializers I came across get_<field_name>_display(). But I am not using any template of mine. I am using Django-REST Framework UI. -
How to fix IntegrityError during the process of saving cropped photo records
Having the model : class Photo(models.Model): file = models.ImageField(upload_to='cropped_photos/',null=True,blank=True) description = models.CharField(max_length=255, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) customer = models.ForeignKey(Woo_Customer,verbose_name="Customer",on_delete = models.CASCADE) I find difficulty in the process of saving a photo record for specific customer after the procedure of uploading and cropping an image with cropper plugin. I do not know how to pass the id of my FK(customer) to the Photo record at the phase of creating the Photo record. Here is my form: class PhotoForm(ModelForm): x = FloatField(widget=HiddenInput()) y = FloatField(widget=HiddenInput()) width = FloatField(widget=HiddenInput()) height = FloatField(widget=HiddenInput()) class Meta: model = Photo fields = ('file', 'x', 'y', 'width', 'height') def save(self): photo = super(PhotoForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.file) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(photo.file.path) return photo Here is my view: def customer_photo_gallery(request,pk): photos = Photo.objects.filter(customer_id = pk) customer = Woo_Customer.objects.get(id = pk) if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('photo_list') else: form = PhotoForm() return render(request, 'woo_customer/woo_customer_photo_gallery.html', {'form': form, 'photos': photos , 'customer': customer}) Here is the template using the cropper plugin (https://fengyuanchen.github.io/cropper/) {% block content %} <script> $(function () { /* SCRIPT TO OPEN … -
django.db.utils.InterfaceError: (0, '') when using django model
I have django.db.utils.InterfaceError: (0, '') error on django. I googled around and found this error is related with mysql connection. I added the CONN_MAX_AGE None in db settings but in vain. I don't even open connection by myself only just using django models. Does anyone knows this error? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', .... 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT'), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'CONN_MAX_AGE' : None ## add here } } These are the stacktrace Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 412, in _query rowcount = self._do_query(q) File "/usr/local/lib/python3.6/site-packages/MySQLdb/cursors.py", line 375, in _do_query db.query(q) File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) _mysql_exceptions.InterfaceError: (0, '') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
OneToOneField no 'username' member in django python3 or fstring or self attribute problems
Here is my code below. why am I getting an error from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' Why is my f-string messing up? It says instance on OneToOneField has no 'username' member? Could this just be pylint and not a real error? how do i tell? -
In Django, how do I render JSON given an OrderedDict?
I'm using Django and Python 3.7. I'm having trouble returning JSON from one of my views. I have this view code ... def get_hints(request): article_id = request.GET.get('article_id', None) article = Article.objects.get(pk=article_id) s = ArticlesService() objects = s.get_hints(article) data = ArticleSerializer(objects, many=True).data print("data: ", data) return HttpResponse(data, content_type="application/json") The service method referenced returns the following data ... def get_hints(self, article): ... sorted_articles_map = OrderedDict(sorted(rank_map.items(), key=operator.itemgetter(1), reverse=True)) return list(sorted_articles_map.keys()) The data returned from the serializer looks like this, definitely not json ... [OrderedDict([('id', 10777935), ('created_on_ms', 1577985486000.0), ('label', 'World'), ('title', "Outrage and Disgust After 'Serial Killer' ..., How do I render proper JSON? -
Django Model Filter: need to return the name not the id of a foreign key
I am trying to filter some data in a Model called WorkPacket work_packets_01012017_25032020 = WorkPacket.objects.all() work_packets_01012017_25032020 = work_packets_01012017_25032020.filter(start_date__gte=datetime.date(2017, 1, 1), start_date__lte=datetime.date(2020, 03, 25)).values('id', 'number', 'name', 'description', 'value', 'type', 'status', 'daily_rate', 'creator', 'creation_date', 'closer', 'closure_date', 'start_date', 'estimated_closure_date', 'estimated_days_overrun', 'invoice_coding', 'issued_pos', 'purchase_order', 'number_of_days', 'number_of_billed_days','number_of_remaining_days', 'number_of_over_run_days', 'effective_daily_rate', 'ahead_behind', 'earnings', 'remaining_earnings', 'reported', 'projects', 'purchase_order__customer', 'purchase_order__owner') This table has a foreign key "purchase_order" related to another model. At the end of the values returned I am trying to attach the 'purchase_order__customer', 'purchase_order__owner'. This works but is returning the ids of the customer and the owner, not the name. How can I return the names, instead? Thank you