Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Good: How can I run my django runserver command?
I have been having this error for 2 day Can somebody help? System check identified no issues (0 silenced). January 17, 2021 - 13:18:06 Django version 3.1.5, using settings 'dj_bootcamp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Boshqaruvchi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Boshqaruvchi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Boshqaruvchi\dj-bootcamp\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Boshqaruvchi\dj-bootcamp\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run run(self.addr, int(self.port), handler, File "C:\Users\Boshqaruvchi\dj-bootcamp\lib\site-packages\django\core\servers\basehttp.py", line 206, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Boshqaruvchi\dj-bootcamp\lib\site-packages\django\core\servers\basehttp.py", line 67, in init super().init(*args, **kwargs) File "C:\Users\Boshqaruvchi\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 452, in init self.server_bind() File "C:\Users\Boshqaruvchi\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Boshqaruvchi\AppData\Local\Programs\Python\Python38-32\lib\http\server.py", line 140, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Boshqaruvchi\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 756, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 13: invalid continuation byte -
admin inline ManyToMany autocomplete_fields
I want to add search for the AcademicGroupInline with using its vk_chat relation # models.py class AcademicGroup(models.Model): students = models.ManyToManyField( 'user.Student', ) vk_chat = models.OneToOneField( 'Chat', ) class Chat(models.Model): owner_id = models.BigIntegerField() name = models.CharField() # admin.py class AcademicGroupInline(admin.TabularInline): model = AcademicGroup.students.through autocomplete_fields = ( 'vk_chat', ) @admin.register(Student) class StudentAdmin(admin.ModelAdmin): inlines = [AcademicGroupInline] But I've got an error in result: <class 'user.admin.AcademicGroupInline'>: (admin.E037) The value of 'autocomplete_fields[0]' refers to 'vk_chat', which is not an attribute of 'course.AcademicGroup_students'. -
Django ModelForm for Multiple Categories of a Product in EAV data model
Hello all I am making auction website like ebay, I have this model design which has many other extra attributes model classes for different categories. But here let's take an example of a PC one which will be used for its sub-categories Desktop and Laptop. Now the problem, I want to create ModelForm for users. For instance if user selects Desktop as their product to put on auction, how will that modelform code look like, so the Desktop respected fields are given to the user to fill from the extra_pc_attributes class? The problem is that wouldn't it get tedious to write separate model for each category and also in the views.py, let alone how would each category form validate? Maybe use Jsonfield instead of creating a whole EAV old-fashioned table for extra attributes? But I am new and I don't know how it will work or even if it applies to this situation. class Categories(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class auction_product(models.Model): product_name = models.CharField(max_length=64) category = models.ForeignKey(Categories, on_delete=models.CASCADE) date_added = models.DateField(default=timezone.now) user = models.ManyToManyField(User, through='product_ownership', related_name='product_user') product_bid = models.ManyToManyField(User, through='bid', related_name='product_bid') product_comment = models.ManyToManyField(User, through='comment') album = models.OneToOneField(ImageAlbum, related_name='product_model', on_delete=models.CASCADE) def __str__(self): return … -
Django Modelform Instance Uodate with Clean_field of modelform in form.py
I want to Update some value of a Book instance in Django from. I have put clean_field() methods in forms.py. So, everytime I update the value in a form it validates the clean_field and raises a validationError for those two fields. I want to bypass that while I update the object's some parameter like bookPrice or publicationDate. so, I can update that value without getting an error on existing fields. I have put clean_field() for bookname,bookisbn. views.py def updateBook(request, key_id): book = Book.objects.get(bookIsbn__exact=key_id) # date format 2/21/2020 print(request.method) if request.method == 'POST': form = BookUploadForm(request.POST, request.FILES, instance=book) if form.is_valid(): form.save() return redirect('bookList') else: print(form.errors.as_data()) form = BookUploadForm(request.POST or None, request.FILES or None, instance=book) template = 'storeApp-Templates/bookUpdate.html' context = {'book': book, 'form': form} return render(request, template, context) form.py class BookUploadForm(forms.ModelForm): class Meta: model = Book fields = "__all__" widgets = { 'bookName': forms.TextInput(attrs={'class': 'form-controls'}), 'bookPrice': forms.TextInput(attrs={'class': 'form-controls'}), 'bookAuthor': forms.TextInput(attrs={'class': 'form-controls'}), 'bookIsbn': forms.TextInput(attrs={'class': 'form-controls'}), 'bookPublicationDate': forms.DateInput(attrs={'class': 'form-controls'}), } bookPublicationDate = forms.DateField(widget=AdminDateWidget()) # this methods will generate error for book update as well as new book Upload def clean_bookName(self, *args, **kwargs): bookname = self.cleaned_data.get('bookName') qs = Book.objects.filter(bookName__exact=bookname) if qs.exists(): raise forms.ValidationError("This BookName has already been used.") return bookname def clean_bookIsbn(self, *args, **kwargs): bookisbn … -
can't understand error and type of error _new in django
File "C:\Users\XXX CCCC\AppData\Local\Programs\Python\Python39\lib\site-packages\ortools\constraint_solver\pywrapcp.py", line 2842, in __init__ _pywrapcp.RoutingModel_swiginit(self, _pywrapcp.new_RoutingModel(*args)) TypeError: Wrong number or type of arguments for overloaded function 'new_RoutingModel'. Possible C/C++ prototypes are: operations_research::RoutingModel::RoutingModel(operations_research::RoutingIndexManager const &) operations_research::RoutingModel::RoutingModel(operations_research::RoutingIndexManager const &,operations_research::RoutingModelParameters const &) I'm new in python please help to solve -
How to save PNG file using FileSystemStorage in Views
I am missing something in the documentation, but cannot figure out what. When a user sends a POST request, I want to generate PNG and put it to the ImageField. I generate PNG with qrcode generator, which give PymagingImage object. I tried to pass it to the FileSystemStorage. Later I tried using BytesIO, so I could open PngImageFile object and try to pass it too. In both cases, I failed, and I am getting object has no attribute 'read' error. As I understood from the documentation I have to use File or ImageFile object for FileSystemStorage to work. However, I cannot find a way how to convert my PNG to correct type. I would really appreciate if someone could pinpoint the error in my code or my logic. Thanks! views.py: qr = qrcode.make("123456", image_factory=PymagingImage) # PymagingImage object buffer = BytesIO() qr.save(buffer, "PNG") # PngImageFile object qr_from_buffer = Image.open(buffer) fs = FileSystemStorage() qr_img = fs.save("qrcode.png", qr_from_buffer) -
Email doesn't get sent in when I host with apache2 - Django
I am creating an eCommerce site and while in my local machine it has worked perfectly fine with no errors and emails are being sent without any error. However, when I hosted it on Linode(ubuntu) using apache2 my website seems to be working perfectly fine but only emails don't get sent... I usually wait around 2 mins when I submit a form to send an email, but it throws me with the contact_us_error.html template I have created. My Settings.py... import json with open('/etc/config.json') as config_file: config = json.load(config_file) ... EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config.get('EBLOSSOM_EMAILID') EMAIL_HOST_PASSWORD = config.get('EBLOSSOM_EMAILPASS') AUTHENTICATION_BACKENDS = ['user.backends.EmailBackend'] And in my views.py... try: send_mail( 'Subject', 'Content', 'email_address', ['email_address'], fail_silently=False, ) return render(request, "store/email_confirmation.html") except: return render(request, "store/contact_us_error.html") This is the code that is currently stored in my server. I know for a fact that my environmental variables are read by Django, but it just doesn't seem to send emails when hosted in Linode. The current IP address of my server is http://192.46.213.68/ . Any help would be greatly appreciated thanks! -
Django rest framework: how to look up UUIDs properly and (with slugs?)
I'm struggling to figure out how to use uuids properly. I'm following Daniel Feldroys Two Scoops of Django, but I'm finding uuids difficult. My app was working before using sequential user ids, now I want to change it to a uuid to make the API more secure. But my question is: How to I actually look up the unique user ID? None of the views (http://127.0.0.1:8000/api/) seem to be displaying any data, despite that I can see data in Admin. I'm guessing I need to supply the unique user ID (http://127.0.0.1:8000/api/), but since this is autogenerated when I post objects to the database, how do you obtain the uuid? Is it only when you create the objects in the first place, for extra security? But if I have existing objects that I migrate over from another API, can I run python manage.py shell and look up the uuids of existing objects some how? I'm also conceptually struggling with the roles of slugs. how do I use them to find the correct web url? This is my models.py import uuid as uuid_lib from django.db import models from django.urls import reverse from .rewards import REWARDS class TimeStampedModel(models.Model): """ An abstract base class … -
My navbar brand is taking a whole lot of space
I was writing an html page with bootstrap and then I come across some sort of kind of error the navbrand is too long. It takes up a whole lot of space in my navbar at the point when I view it on mobile It takes up a whole line and the hamburger icon goes to the bottom. This problem doesn't occur with text only with images. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Urci</title> <!-- BOOTSTRAP --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- CSS --> <!-- CSS --> <link rel='stylesheet' href="{% static 'home/css/custom.css' %}"> <!-- FONTS --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Lato&family=Oswald:wght@300&family=Roboto+Condensed&display=swap" rel="stylesheet"> <!-- W3 --> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light custom-navbar"> <div class="container-fluid"> <a class="navbar-brand urci-brand" href="{% url 'home' %}"><img class="branding "src="{% static 'home/images/Urci-Logo.png' %}" alt=""></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav custom-navbar"> <a class="nav-link" href="{% url 'bod' %} ">Board of Directors</a> <a class="nav-link" href="#">Events</a> {% if user.is_authenticated %} <div class="navbar-nav ml-auto"> <a class="nav-link" href="{% url 'announcement:create' %}">Create Announcement</a> <a class="nav-link" href="#">Create Events</a> {% endif … -
Django can send email from Python Shell but Gmail blocks mail when sent from front end form
I'm trying to make a password reset via email page following the tutorial here: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication#password_reset_templates I can send emails while in the Python-Django shell but when I try to send it via that form, Gmail blocks my messages. I have my email settings in settings.py configured as: #gmail_send/settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'foo@gmail.com' EMAIL_HOST_PASSWORD = os.environ['EMAIL_PASSWORD'] EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER When I do this using the shell, I'm able to receive the email: >>> from django.core.mail import send_mail >>> send_mail('test email', 'hello world', 'your@email.com', ['test@email.com']) My password reset form looks like this (base_generic just has some bootstrap and jquery CDN stuff along with a navbar) {% extends "OracleOC/base_generic.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} {% if form.email.errors %} {{ form.email.errors }} {% endif %} <p>Please enter your email:</p> <p>{{ form.email }}</p> <input type="submit" class="btn btn-primary main_menu_button" value="Reset password"> </form> {% endblock %} When I press submit, everything looks fine and I get a [17/Jan/2021 07:04:12] "GET /accounts/password_reset/done/ HTTP/1.1" 200 2105 in my Django console but I get a copy of the message in my sender gmail box with this message: Gmail blocked my … -
Django REST framework - filtering against query params with date and string parameter
I created my "API" using REST framework, now trying to do filtering for it. That's how my models.py look for Schedule model. class Schedule(models.Model): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) bus = models.ForeignKey(Bus, on_delete=models.PROTECT) travel_date_time = models.DateTimeField() I want to filter departure and travel_date_time on query parameters. Basically field departure comes from following models. class BusCompanyRoute(models.Model): route = models.ForeignKey(Route, on_delete=models.PROTECT) and route is linked with 'Route' model in following way class Route(models.Model): departure = models.ForeignKey( Location, on_delete=models.PROTECT, related_name='route_departure' ) class Meta: default_permissions = () verbose_name = 'Route' verbose_name_plural = 'Routes' I basically use usecases.py for my logic section so in my views.py file I have following code to get query paramters. class BusCompanyTicketDetailView(generics.ListAPIView, BusCompanyMixin): serializer_class = serializers.TicketDetailResponseSerializer def get_queryset(self): travel_date = (self.request.query_params.get('travel_date')) destination = (self.request.query_params.get('destination')) return usecases.ListBusCompanyTicketUseCase( bus_company=self.get_bus_company(), date=travel_date, destination=destination ).execute() and my usecase file have following code. class ListBusCompanyTicketUseCase(BaseUseCase): def __init__(self, bus_company: BusCompany, date: datetime, destination): self._bus_company = bus_company self._date = date self._destination = destination # print(datetime) def execute(self): self._factory() return self._schedules def _factory(self): self._schedules = Schedules.objects.filter(bus__bus_company=self._bus_company ,travel_date_time__date=self._date ,bus_company_route__route__destination=self._destination) Finally my url with query parameter is as follows http://127.0.0.1:8000/api/v1/ticket/bus-company/1037a4cc-ff38-4948-978a-5a7b92cb7a41/list?travel_date=2021-1-2&destination=florida I was getting correct query only with travel_date_time but on adding destiantion I am getting error as ValidationError at /api/v1/ticket/bus-company/1037a4cc-ff38-4948-978a-5a7b92cb7a41/list ['“florida” is … -
How to pass the value from v-for to a simple django filter
I have the following component in a django template <div class="trow" v-for="(item, idx) in data"> </div> Now if I try to write the following inside the div {{ item.co.name }} I won't get the value, I will have to write the following to get the value {% verbatim %} {{ item.co.name }} {% endverbatim %} Now my problem is that I have to do something with this value so I wrote a simple filter like this from django import template from django.templatetags.static import static register = template.Library() @register.filter def define(val=None): return static(f"images/{val.lower()}.svg") but I can't do the following <div class="trow" v-for="(item, idx) in data"> {% verbatim %} {{ item.co.name | define }} {% endverbatim %} </div> I've also tried a lot of combinations with no luck, how can I solve this? -
convert mongoose schema to django model
I have below javascript schema const mongoose = require('mongoose'); const pointSchema = new mongoose.Schema({ timestamp: Number, coords: { latitude: Number, longitude: Number, altitude: Number, accuracy: Number, heading: Number, speed: Number } }); const trackSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, name: { type: String, default: '' }, locations: [pointSchema] }); mongoose.model('Track', trackSchema); I'm trying to convert above file to Django models. wondering how to write that locations: [pointSchema] and const pointSchema in my models.py. Is it possible to convert that ? -
Understanding Django to put python web app into a site
I'm trying to create a portfolio to show my python web apps. I've created a github with a main portfolio page that uses an HTML template with my own edits. What I'm trying to do is place each individual project, that I'm working on, into that main site. I understand how to clone github to my VSCode etc. and I understand how to make the front-end side of the website with Django BUT what I am not understanding is how to format the web apps to be used on the site like I hope for. For example, I created a thesaurus project specifically on python (from a course), but I don't understand where or what I code in Django that the user can actually use it. In other words, I'm not finding the answer to create a Charfield (for the user to input) and then it prints into a separate box below it, while using the same python script. What I also can't figure out, is where would my database JSON file (with all the definitions) be stored in order for the user input to print. Or is that already done within the python script that I don't need to … -
How can I update a Django QuerySet, so that it doesn't return cached data?
The QuerySet in my Django ListView view doesn't automatically update when I create a new record in the model. The Django admin updates and the database updates, but the view does not update. I've come to realise that this is happening because the QuerySet is using cached data. To re-execute the QuerySet on a get request, I have unsuccessfully tried various versions of the code below... def get_queryset(self): self.user = self.request.user queryset = Strategy.objects.filter(user=self.user) updated_queryset = queryset.update() return updated_queryset Instead of updating my QuerySet each time the webpage is refreshed, this is returning an empty QuerySet. What do I need to do to update the QuerySet on a GET request? -
ImportError: Couldn't import Django. PYTHONPATH
there was an error 'account.User' that has not been installed But I solved this problem. After that, there was an error 'The SECRET_KEY setting must not be empty.' I don't know whether my method to solve this problem is correct or not, I applied some solutions with Google. But now, there is an error ' ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?' But i already installed django and virtualenv. I don't know how to do it. I spent lots of days recent error Traceback (most recent call last): File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/core/management/init.py", line 12, in from django.conf import settings File "/Users/leejunseo/PycharmProjects/ITM coding/venv/lib/python3.9/site-packages/django/conf/init.py", line 21, in from .base import * ModuleNotFoundError: No module named 'django.conf.base' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 21, in main() File "/Users/leejunseo/PycharmProjects/ITM coding/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? MY code manage.py … -
Serialize and Deserialize nested and foreign key with Django Rest Framework
I am creating an Ecommerce website and I am stuck in the backend trying to serialize and deserialize data using Django Rest Framework. Here's my model file from django.db import models # Create your models here. class Company(models.Model): company_name = models.CharField(max_length=200, null=True) def __str__(self): return self.company_name class Category(models.Model): category_name = models.CharField(max_length=100, null=True) def __str__(self): return self.category_name class Tags(models.Model): tag_name = models.CharField(max_length=100, null=True) def __str__(self): return self.tag_name class Product(models.Model): product_name = models.CharField(max_length=999, null=True) product_description = models.TextField(max_length=999, null=True) product_price = models.IntegerField(null=True) product_company = models.ForeignKey(Company,null=True, on_delete=models.SET_NULL) tag = models.ManyToManyField(Tags) category = models.ManyToManyField(Category) product_availability = models.BooleanField(default=True) stocks_count = models.DecimalField(null=True, decimal_places=1, max_digits=3) def __str__(self): return self.product_name Here I have nested Many to Many relationships and Foreign Key relationship which I want to be able to read and write with DRF My Serializers file is as below: from rest_framework import serializers from .models import * class CategorySerializer(serializers.ModelSerializer): def to_representation(self, value): return value.category_name class Meta: model = Category fields = ('category_name',) class TagsSerializer(serializers.ModelSerializer): def to_representation(self, value): return value.tag_name class Meta: model = Tags fields = ('tag_name',) class CompanySerializer(serializers.ModelSerializer): def to_representation(self, value): return value.company_name class Meta: model = Company fields = ('company_name',) class ProductSerializer(serializers.ModelSerializer): tag = TagsSerializer(many=True) category = CategorySerializer(many=True) product_company = CompanySerializer() class Meta: model = Product … -
OAuth server using django-oauth-server
I'm developing a system where I have a central authentication server (using django-oauth-toolkit) for multiple web apps (clients, uses DRF to provide api endpoints to front-end SPA). The auth server will only be for authenticating users, while the api calls from the front-end side will be to the client apps not the auth server. This brings me to the question, If I'm getting access-token from auth server, how can I secure my api endpoints of the app server? In cases where authorization and api calls are on the same server, I would use DRF authentication that handles the creation of access token, but since the token is created by auth server, I was wondering how to handle the access token and api calls to the client. Hope anybody can clarify this. -
Django-React authentication: limit users who can obtain simpleJWT tokens
I have two React frontends for my backend: first one is used by all users, second one is an admin panel which can only be used by is_staff users. What is the best way to limit access using simplejwt tokens? I have overriden TokenObtainPairSerializer to include additional fields like 'is_staff'. So I have two questions: is just checking the is_staff field on the frontend safe enough? Doesn't seem to me like a good idea. if I want to create second API url entry for admin authentication and override authentication logic on backend side to only issue tokens to staff users. What method/class exactly should I override to change this? Is this a good idea? -
fields do not recognise django
I have been having a problem working with formsets in my project and I've been trying to get to the bottom of this. While doing so, a couple of different errors have been appearing. Generally, what I want to do is create an object of entity A (workout) and get redirected to a template/url that lets me "fill" it with objects of entity B, which I will be making at that point dynamically using model formsets. The problem seems to be revolving around the form, more specifically: if I write the fields one by one, as in : CycleFormSet = modelformset_factory( Cycle, fields=('reps', 'place_in_workout', 'exercise', 'number_of_times', 'break_inbetween'), extra=1 ) Then, I get the error: Unknown field(s) (place_in_workout, break_inbetween, reps, number_of_times) when I attempt to run the server. If I use exclude for some field, or do fields = 'all' , then I don't get an error at this point. However, I get the error : ['ManagementForm data is missing or has been tampered with'] when I try to post the data of the workout object. Me code: models.py class Exercise(models.Model): name = models.CharField(max_length=150) description = models.TextField(max_length=500) def __str__(self): return self.name class Workout(models.Model): name = models.CharField(max_length=150, null=True) created_by_user = models.ForeignKey(User, null=True, … -
How to access GreenPlum from Django?
I am doing a Django application that gets data from a Postgres DB. Is there a way to make it use GreenPlum instead? I am using these settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testDB', 'USER': 'postgresUser', 'PASSWORD': 'postgresPasswd', 'HOST': 'localhost', 'PORT': '5432', } } Thanks -
i am trying to import " django.shortcuts import get_objects_or_404" in my django views file but is giving an error
I am getting the folllowing error: from django.shortcuts import render,get_objects_or_404,redirect ImportError: cannot import name 'get_objects_or_404' from 'django.shortcuts' this is the error I am getting in my django project can anyone help me in fixing this -
module 'jwt' has no attribute 'ExpiredSignature'
I have been developing a Django application using graphene/graphql running over AWS using Docker alpine image. I have been using django-grapql-jwt module for calling jwt authentication in my application. Where it is calling ExpiredSignature from PyJWT instead of ExpiredSignatureError. And graphQL is returning "module 'jwt' has no attribute 'ExpiredSignature'" error. How to resolve the issue? -
Embedding Data Tables and Plots in a Local/Private webpage using Dash
This one is a generic question. I know that I can create a dash app from my csv file to the local server ( 127.0.0), but instead of hosting it to that webpage, is it possible to host it to a shared page inside my company which anyone can access whenever they want it to. I may run the code on my machine and in one scheduled run (say per day) the data will be populated and whenever within that day anyone else will access the webpage/dashboard will be able to get that data and see plots/tables etc depending on the application and interactivity. Next day when someone else looks at the data ( that will be new data assuming the code on my machine has run and populated new data). I am finding dash useful but not sure how it can be hosted/embedded into a separate webpage. Any help or ideas or suggestions will be immensely appreciated. -
not able to make entries in mapping table - Python Django
I am trying to create a form with the help of that I can make entries in the table, but I couldn't able to understand the logic what should I do here, the mapping table stores the foreign key references. My code is as shown below: models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size = models.CharField("Product Size", max_length=20, null=False) def __str__(self): return "{size_id}-->{prod_size}".format(size_id=self.size_id, prod_size=self.prod_size) class SizeProductMapping(models.Model): size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True) size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") def __str__(self): return ".`. {}_____{}".format(self.size_id, self.prod_id) here is the function to add data in the table. views.py def sizeProductMap(request): if request.method == 'POST': size_id = request.POST['size_id'] size_id = int(size_id) print(size_id) product_id = request.POST['product_id'] product_id = int(product_id) print(product_id) sizeProductMap_update = SizeProductMapping(size_id=size_id, prod_id=product_id) sizeProductMap_update.save() return redirect('/admin1/productSize') else: sizeProductMap_show = SizeProductMapping.objects.all() # start paginator logic paginator = Paginator(sizeProductMap_show, 3) page = request.GET.get('page') try: sizeProductMap_show = paginator.page(page) except PageNotAnInteger: size_show = paginator.page(1) except EmptyPage: sizeProductMap_show = paginator.page(paginator.num_pages) # end …